【问题标题】:How would I convert an XLS to a CSV file in PHP?如何在 PHP 中将 XLS 转换为 CSV 文件?
【发布时间】:2011-11-09 17:16:06
【问题描述】:

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

【问题讨论】:

  • XLS 表示 MS Excel,对吗?在 Windows 上,可以使用 Office 自动化(基本上是一个美化的 VB 脚本)来完成它。你考虑过吗?或者 LibreOffice 方法会更受欢迎吗?

标签: php parsing csv xls


【解决方案1】:

此代码读取 .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);

【讨论】:

  • 从表面上看,该脚本将 CSV 转换为 XLS
  • @Shane 先下载类文件-phpclasses.org/browse/package/1919.html
  • excel.php 类执行 CSV 到 XLS 和 XLS 到 CSV 的操作
  • @Shane 转到此页面 - phpclasses.org/browse/package/1919.html 在这里您可以找到一些示例文件
猜你喜欢
  • 2014-03-13
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 2011-12-07
  • 2015-11-11
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多