PhpSpreadSheet: How to save Workbook sheets in individual CSV files



PHP Snippet 1:

$excel = 'excelfile.xlsx';
$name = 'newCsvName';
$reader = new Xlsx();
$reader->setReadDataOnly(true);

//Get all sheets in file
$sheets = $reader->listWorksheetNames($excel);

//Loop for each sheet and save an individual file
foreach($sheets as $sheet){
   //Load the file
   $spreadsheet = $reader->load($excel);

   //Write the CSV file
   $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
   $writer->setDelimiter(";");
   $csvPath = 'csv_files/' . $dir . '/' . $name.'_'.$sheet.'.csv';
   $writer->save($csvPath);
}

PHP Snippet 2:

$reader->setLoadSheetsOnly([$sheet]);

PHP Snippet 3:

$excel = 'excelfile.xlsx';
$name = 'newCsvName';
$reader = new Xlsx();
$reader->setReadDataOnly(true);

//Get all sheets in file
$sheets = $reader->listWorksheetNames($excel);

//Loop for each sheet and save an individual file
foreach($sheets as $sheet){

   //Load the file
   $reader->setLoadSheetsOnly([$sheet]);
   $spreadsheet = $reader->load($excel);

   //Write the CSV file
   $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
   $writer->setDelimiter(";");
   $csvPath = 'csv_files/' . $dir . '/' . $name.'_'.$sheet.'.csv';
   $writer->save($csvPath);
}