简体   繁体   中英

PhpSpreadsheet reading through multiple files in php

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>";

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM