使用PhpSpreadsheet在PHP中阅读XLS

时间:2018-09-13 16:52:38

标签: php excel xls phpspreadsheet

我有使用PhpSpreadsheet读取XLS文件(不是xlsx)的要求,但遇到了麻烦。我试过了(正如文档所说,但是...)

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;

$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("lista.xls");
$worksheet = $spreadsheet->getActiveSheet();

echo '<table>' . PHP_EOL;
foreach ($worksheet->getRowIterator() as $row) {
    echo '<tr>' . PHP_EOL;
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
                                                       //    even if a cell value is not set.
                                                       // By default, only cells that have a value
                                                       //    set will be iterated.
    foreach ($cellIterator as $cell) {
        echo '<td>' .
             $cell->getValue() .
             '</td>' . PHP_EOL;
    }
    echo '</tr>' . PHP_EOL;
}
echo '</table>' . PHP_EOL;

echo "<br>fin";

但不起作用(它只能用于xlsx文件,而不能用于xls文件!)

然后我尝试以其他方式打开文件:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$sheet = $reader->load("lista.xls");

但也不起作用...

我真的需要解决这个问题……请帮助! PS:我已经尝试过BasicExcel和PHPExcel,但似乎也没有用

4 个答案:

答案 0 :(得分:6)

<?php
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();

$inputFileType = 'Xlsx';
$inputFileName = './mysheet.xlsx';

/**  Create a new Reader of the type defined in $inputFileType  **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/**  Advise the Reader that we only want to load cell data  **/
$reader->setReadDataOnly(true);

$worksheetData = $reader->listWorksheetInfo($inputFileName);

foreach ($worksheetData as $worksheet) {

$sheetName = $worksheet['worksheetName'];

echo "<h4>$sheetName</h4>";
/**  Load $inputFileName to a Spreadsheet Object  **/
$reader->setLoadSheetsOnly($sheetName);
$spreadsheet = $reader->load($inputFileName);

$worksheet = $spreadsheet->getActiveSheet();
print_r($worksheet->toArray());

}

答案 1 :(得分:5)

我会与您的客户核实,看看他们是否使用的是真正的Excel或其他电子表格。

如果他们使用其他电子表格并使用“导出为Excel”功能进行导出,这可以解释为什么PHPSpreadsheet无法将其识别为任何可能的有效excel格式。

在这种情况下,并取决于电子表格中的内容,可能值得要求他们将电子表格导出为csv(以逗号分隔的值)文件,因为这种格式非常简单,应该是有效输出。然后,您可以使用fgetcsv()函数调用来阅读它,而不必使用PHPSpreadsheet。

答案 2 :(得分:0)

这里的问题是在加载文件后将其转换为数组

$file = "file.xlsx";
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
$spreadsheet = $spreadsheet->getActiveSheet();
$data_array =  $spreadsheet->toArray();

答案 3 :(得分:-1)

尝试删除此语句

$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("lista.xls");

并对此进行更改

$inputFileName = "lista.xls";
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($inputFileName);
$reader->setReadDataOnly(TRUE);
$spreadsheet = $reader->load($inputFileName);