php - 使用 PhpSpreadsheet 在 PHP 中读取 XLS

标签 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,但似乎也没有用

最佳答案

<?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/

相关文章:

Excel : Conditional formatting

excel - 如何选择列范围中的最后一个单元格?

PHP:处理 CSV 或 XLS 文件

excel - 当我读入一个变量时,为什么 matlab 返回这个变量?

java - 将 xls 转换为图像

php - Paypal - 不支持货币

PHP 和 MySQL - 为什么依赖系统时间设置是不安全的?

php - MySQL : Select query performance issue

sql-server - 将包含数据的列更改为现有表

php - Activerecord 时区格式不正确