簡體   English   中英

使用PhpSpreadsheet在PHP中閱讀XLS

[英]Read XLS in PHP using 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,但似乎也沒有用

我會與您的客戶核對一下,看看他們是否使用的是真正的Excel或其他電子表格。

如果他們使用其他電子表格並使用“導出為Excel”功能進行導出,則可以解釋為什么PHPSpreadsheet無法將其識別為任何可能的有效excel格式。

在這種情況下,並取決於電子表格中的內容,可能值得要求他們將電子表格導出為csv (逗號分隔值)文件,因為這種格式很簡單,應該是有效的輸出。 然后,您可以使用fgetcsv()函數調用來讀取它,而不必使用PHPSpreadsheet。

<?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());

}

嘗試刪除此語句

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

並用它來改變

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM