简体   繁体   中英

PHPexcel CSV master file

I would like to have multiple csv's and add them in a master csv file. It when I add an extra csv file in the array it throws a exception error.

Uncaught exception 'Exception' with message 'Workbook already contains a worksheet named 'Worksheet'. Rename the external sheet first.' in
Please find below my code

include'../Classes/PHPExcel.php';
include'../Classes/PHPExcel/IOFactory.php';

$filenames = array('Sheet1.csv','Sheet2.csv');

$bigExcel = new PHPExcel();
$bigExcel->removeSheetByIndex(0);

$reader = new PHPExcel_Reader_CSV();

foreach ($filenames as $filename) {
$excel = $reader->load($filename);
foreach ($excel->getAllSheets() as $sheet) {
    $bigExcel->addExternalSheet($sheet);
}
foreach ($excel->getNamedRanges() as $namedRange) {
    $bigExcel->addNamedRange($namedRange);
}
}
$writer = new PHPExcel_Writer_CSV($bigExcel);
$writer->save('2007-write.csv');

The problem is with the following code:

foreach ($excel->getAllSheets() as $sheet) {
    $bigExcel->addExternalSheet($sheet);
}

For file 1 you add a sheet called worksheet, and then for file two you try to add a sheet with the same name.

I suggest you check if a sheetname has already been added, and if so you can use "setActiveSheetIndex" to switch to the existing sheet.

Another option is to change the name to worksheet(2) if you find one that already exists.

But since you called it CSV I dont think you can use worksheets. So in the end it should all just go in a single worksheet, so no need to keep adding new workheets. Just create one and add all the data to that one.

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