简体   繁体   中英

PHPExcel - read 4 CSV files into a single workbook with 4 spreedsheets

I need to aggregate 4 CSV files into a single, Excel workbook using PHPExcel.

Working on a single CSV file and a mono-spreadsheet workbook all works fine. Using more than one CSV, I'm unable to get each CSV file into a seperate sheet.

How can I achieve this using PHPExcel?

There is an example of this in the Documentation/Examples/Readers directory in the SVN repository for PHPEXcel: It's Example #13

include 'PHPExcel/IOFactory.php';


$inputFileType = 'CSV';
$inputFileNames = array('./example1.csv','./example2.csv','./example3.csv','./example4.csv');

$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$inputFileName = array_shift($inputFileNames);
$objPHPExcel = $objReader->load($inputFileName);
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
foreach($inputFileNames as $sheet => $inputFileName) {
    $objReader->setSheetIndex($sheet+1);
    $objReader->loadIntoExisting($inputFileName,$objPHPExcel);
    $objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
}


$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $objPHPExcel->setActiveSheetIndexByName($loadedSheetName);
    echo $loadedSheetName,PHP_EOL;
    $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
    var_dump($sheetData);
    echo PHP_EOL;
}

You didn't specify exactly where the problem is...
For multiple worksheet excel file proceed as following:

  1. Load CSV file
  2. Create new worksheet
  3. Write CSV to new worksheet
  4. Go to 1

From docs:
If you need to create more worksheets in the workbook, here is how:

$objWorksheet1 = $objPHPExcel->createSheet();
$objWorksheet1->setTitle('Another sheet');

To set active worksheet:

$objWorksheet1->setActiveSheetIndex($index);

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