Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhpSpreadsheet only save the first worksheet as csv

I tried to save a specific worksheet from an XLSX as CSV. First I tried to use setActiveSheetIndexByName() function to set active sheet and call the writer method of \PhpOffice\PhpSpreadsheet\Writer\Csv, but no luck. Somehow the writer save the first worksheet. I tried indexing by name, by number, but not a little difference.

Now there is a code I experimenting with:

$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$reader->setReadDataOnly(true);

$spreadsheet = $reader->load('infile.xlsx');
foreach($spreadsheet->getAllSheets() as $sheet)
{
   $spreadsheet->setActiveSheetIndexByName($sheet->getTitle());
   $activeSheet = $spreadsheet->getActiveSheet();
   $title = $activeSheetgetTitle();
   echo $title . PHP_EOL;
   $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
   $writer->save($title . '.csv', 2);
}

The console output is as I expected: the list of spreadsheet names. The file system output is almost as I expected: a lot of CSV files with proper names. However the content is the same. I mean bit by bit the same content as the first worksheet. No matter if I change the active sheet.

My question is, how can I save CSV file based on a speficict worksheet?

UPDATE: If I reorder the worksheets on workbook, I got the CSV I need. But this is merely an instant hack, and it will not work when I'll need to work with more worksheet.

like image 419
user28698937 Avatar asked Nov 24 '25 00:11

user28698937


1 Answers

Write a specific worksheet

CSV files can only contain one worksheet. Therefore, you can specify which sheet to write to CSV:

$writer->setSheetIndex(0); // default is 0

Source: Reading and Writing to file - PhpSpreadsheet Docs

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);

$currentSheetIndex = $spreadsheet->getActiveSheetIndex();
$writer->setSheetIndex($currentSheetIndex); // or any other one

$writer->save("title.csv");
  • PhpOffice\PhpSpreadsheet\Writer\Csv default sheetIndex - GitHub
  • setSheetIndex - GitHub
like image 105
rozsazoltan Avatar answered Nov 25 '25 14:11

rozsazoltan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!