簡體   English   中英

PhpSpreadsheet 讀取 php 中的多個文件

[英]PhpSpreadsheet reading through multiple files in php

您好,我正在嘗試在foreach循環中使用 PhpSpreadsheet 庫構建多個xls文件,但它沒有讀取數據,而是僅顯示文件名。如果我對單個文件使用相同的代碼,它就可以工作。 我不確定我做錯了什么。

require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__."/export.php";

        use PhpOffice\PhpSpreadsheet\Helper\Sample;
        use PhpOffice\PhpSpreadsheet\IOFactory;
        use PhpOffice\PhpSpreadsheet\Spreadsheet;
        use PhpOffice\PhpSpreadsheet\Writer\Xls;

define('ROOT_PATH', dirname(__DIR__));
define('INSTALL_FOLDER', '/combine'); //Script installation directory if any leave '' if in root
define('DAT_FILES_FOLDER','/CompactedData'); // .dat files folder where generated
define('MAIN_PATH', ROOT_PATH.INSTALL_FOLDER);

function checkIsAValidDate($myDateString){
    return (bool)strtotime($myDateString);
}

$datFilesPath = MAIN_PATH.DAT_FILES_FOLDER;
$getAllFiles = glob($datFilesPath . "/*.xls");
$content = null;
$content_data = null;
$rowKey = null;
$file_name = null;


foreach ($getAllFiles as $fileIndex => $getfileName):
    $rows = null;
    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load( $getfileName );
    $worksheet = $spreadsheet->getActiveSheet();
    $rows = [];
    foreach ($worksheet->getRowIterator() AS $row) {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
        $cells = [];
        foreach ($cellIterator as $cell) {
            $cells[] = $cell->getValue();
        }
        $rows[] = $cells;
    }

$filesDataComplete = array(
    "filename" => $getfileName,
    "fileData" => $rows
);
endforeach;

echo "<pre>";
print_r($filesDataComplete);
echo "</pre>";

您需要斷開與工作表的連接並取消設置變量以使其像這樣工作

$spreadsheet->disconnectWorksheets();
unset($spreadsheet);

在您的情況下,您的代碼將如下所示

foreach ($getAllFiles as $fileIndex => $getfileName):
    $rows = null;
    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load( $getfileName );
    $worksheet = $spreadsheet->getActiveSheet();
    $rows = [];
    foreach ($worksheet->getRowIterator() AS $row) {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
        $cells = [];
        foreach ($cellIterator as $cell) {
            $cells[] = $cell->getValue();
        }
        $rows[] = $cells;
    }

    $spreadsheet->disconnectWorksheets();
    unset($spreadsheet);

$filesDataComplete = array(
    "filename" => $getfileName,
    "fileData" => $rows
);
endforeach;

暫無
暫無

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

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