csv 到 excel 转换

2022-08-30 17:59:00

有没有办法通过apache / .htaccess根据请求将csv文件转换为excel文件


答案 1

使用 PHPExcel

include 'PHPExcel/IOFactory.php';

$objReader = PHPExcel_IOFactory::createReader('CSV');

// If the files uses a delimiter other than a comma (e.g. a tab), then tell the reader
$objReader->setDelimiter("\t");
// If the files uses an encoding other than UTF-8 or ASCII, then tell the reader
$objReader->setInputEncoding('UTF-16LE');

$objPHPExcel = $objReader->load('MyCSVFile.csv');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('MyExcelFile.xls');

答案 2

PHPExcel 已弃用。你必须使用PhpSpreadsheet

使用PhpSpreadsheet,您可以通过以下代码将csv转换为xlsx:

$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Csv');

// If the files uses a delimiter other than a comma (e.g. a tab), then tell the reader
// $reader->setDelimiter("\t");
// If the files uses an encoding other than UTF-8 or ASCII, then tell the reader
// $reader->setInputEncoding('UTF-16LE');

$objPHPExcel = $reader->load('/home/superman/projects/test/csv-app/file.csv');
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
$objWriter->save('excel_file.xlsx');

推荐