2011-11-09 124 views
-2

我一直在尋找幾天來找到一個PHP腳本,它將讀取MsExcel(myFile.xls)文件並將其轉換爲CSV(myFile.csv)文件並將其輸出。有誰知道我可以做這個和/或幾個代碼示例?如何將XLS轉換爲PHP中的CSV文件?

+0

XLS意味着MS Excel中,對不對?在Windows上,可以使用Office自動化(基本上是一個榮耀的VB腳本)來完成它。你有沒有考慮過?或者LibreOffice方法會更可口嗎? – hardmath

回答

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); 
+3

通過它的外觀,該腳本將CSV轉換爲XLS – Shane

+0

我需要XLS到CSV – Shane

+0

@Shane首先下載類文件 - http://www.phpclasses.org/browse/package/1919.html – SB24