如何在PHP中将XLS转换为CSV文件?

时间:2011-11-09 17:16:06

标签: php parsing csv xls

我一直在寻找能够读取MsExcel(myFile.xls)文件并将其转换为CSV(myFile.csv)文件并输出的PHP脚本。有谁知道我怎么做这个和/或可能是一些代码示例?

1 个答案:

答案 0 :(得分:2)

此代码读取.xls文件,然后逐行将其转换为.csv。

但我会建议寻找任何外部库或功能来做同样的事情,这会更容易 -

/* Get the excel.php class here: http://www.phpclasses.org/browse/package/1919.html */
require_once("../classes/excel.php");
$inputFile=$argv[1];
$xlsFile=$argv[2];

if( empty($inputFile) || empty($xlsFile) ) {
    die("Usage: ". basename($argv[0]) . " in.csv out.xls\n" );
}

$fh = fopen( $inputFile, "r" );
if( !is_resource($fh) ) {
    die("Error opening $inputFile\n" );
}

/* Assuming that first line is column headings */
if( ($columns = fgetcsv($fh, 1024, "\t")) == false ) {
    print( "Error, couldn't get header row\n" );
    exit(-2);
}
$numColumns = count($columns);

/* Now read each of the rows, and construct a
    big Array that holds the data to be Excel-ified: */
$xlsArray = array();
$xlsArray[] = $columns;
while( ($rows = fgetcsv($fh, 1024, "\t")) != FALSE ) {
    $rowArray = array();
    for( $i=0; $i<$numColumns;$i++ ) {
        $key = $columns[$i];
        $val = $rows[$i];
        $rowArray["$key"] = $val;
    }
    $xlsArray[] = $rowArray;
    unset($rowArray);
}
fclose($fh);

/* Now let the excel class work its magic. excel.php
    has registered a stream wrapper for "xlsfile:/"
    and that's what triggers its 'magic': */
$xlsFile = "xlsfile:/".$xlsFile;
$fOut = fopen( $xlsFile, "wb" );
if( !is_resource($fOut) ) {
    die( "Error opening $xlsFile\n" );
}
fwrite($fOut, serialize($xlsArray));
fclose($fOut);

exit(0);