Reputation: 307
Hello I am trying to build multiple xls
files using PhpSpreadsheet library in a foreach
loop but instead of reading data it shows the file names only.If I use the same code for a single file it works. I am not sure what I am doing wrong.
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>";
Upvotes: 3
Views: 1285
Reputation: 307
You need to disconnect from the worksheet and also unset the variable to make it work like this
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
In your case you code will look like this
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;
Upvotes: 2