gpt4 book ai didi

PhpSpreadsheet 读取 php 中的多个文件

转载 作者:行者123 更新时间:2023-12-05 04:57:14 27 4
gpt4 key购买 nike

你好,我正在尝试在 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;

关于PhpSpreadsheet 读取 php 中的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64524957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com