我需要使用 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,但似乎也没有用
最佳答案
<?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());
}
关于php - 使用 PhpSpreadsheet 在 PHP 中读取 XLS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52318370/