PhpSpreadSheet:如何将工作簿表保存在单个 CSV 文件中

PhpSpreadSheet: How to save Workbook sheets in individual CSV files

我正在使用 PhpSpreadSheet,我需要将工作簿中包含的 sheet 保存为单独的 CSV 文件。

我尝试使用 $reader->setLoadAllSheets();,但最后我总是有一个 CSV 文件,其中包含工作簿的第一个 sheet。

这是我的代码示例:

    $excel = 'excelfile.xlsx';
    $name = 'newCsvName';

    //Read the file
    $reader = new Xlsx();
    $reader->setReadDataOnly(true);
    $reader->setLoadAllSheets();
    $spreadsheet = $reader->load($excel);

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

我就是这样解决的。 我首先将包含的每个 sheet 加载到 excel 文件中,然后保存一个包含信息的新 CSV 文件。我敢肯定应该有更好的方法,但效果很好。

$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);
}

上面的答案漏掉了重要的一行:

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

这使得 reader 加载特定的 sheet,然后允许循环打开特定的 sheet 并将其写入 CSV,否则您会发现此代码创建每个sheet 名称,但包含文档第一个 sheet 中的内容。

$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);
}