如何使用PHP将Excel XLS转换为CSV

2022-08-30 14:15:20

任何人都可以指导我如何使用PHP将XLS转换为CSV?

我有excel电子表格,其中包含文档列表,我想使用PHP将其转换为CSV格式。


答案 1

这肯定会奏效,

require_once 'Classes/PHPExcel/IOFactory.php';

$inputFileType = 'Excel5';
$inputFileName = 'YOUR_EXCEL_FILE_PATH';

$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);

$loadedSheetNames = $objPHPExcelReader->getSheetNames();

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');

foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $objWriter->setSheetIndex($sheetIndex);
    $objWriter->save($loadedSheetName.'.csv');
}

希望这有帮助...


答案 2

由于 PHPExcel 已被弃用,因此使用 PhpSpreadsheet 库重写 @Rajat Modi 提供的代码。

https://github.com/PHPOffice/PhpSpreadsheet

https://phpspreadsheet.readthedocs.io/en/develop/

<?php 

require 'vendor\autoload.php';

use \PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use \PhpOffice\PhpSpreadsheet\Writer\Csv;

$xls_file = "Example.xlsx";

$reader = new Xlsx();
$spreadsheet = $reader->load($xls_file);

$loadedSheetNames = $spreadsheet->getSheetNames();

$writer = new Csv($spreadsheet);

foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $writer->setSheetIndex($sheetIndex);
    $writer->save($loadedSheetName.'.csv');
}

推荐