且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用PHPExcel将HTML表格导出到Excel?

更新时间:2023-02-04 22:00:48

要将内容直接放入$objPHPExcel,您需要创建一个工作表,然后逐个单元格设置值,这不是您想要的.

To put contents directly into $objPHPExcel you would need to create a worksheet and then set values cell by cell, which is not what you want.

要插入整个HTML表,必须从HTMLReader

To insert a whole HTML table, you must read it from an HTMLReader

Writer下面的代码中,将用于将内容输出到文件中

In the code below the Writer will be used to output the content to file

$filename = "DownloadReport";
$table    = $_POST['table'];

// save $table inside temporary file that will be deleted later
$tmpfile = tempnam(sys_get_temp_dir(), 'html');
file_put_contents($tmpfile, $table);

// insert $table into $objPHPExcel's Active Sheet through $excelHTMLReader
$objPHPExcel     = new PHPExcel();
$excelHTMLReader = PHPExcel_IOFactory::createReader('HTML');
$excelHTMLReader->loadIntoExisting($tmpfile, $objPHPExcel);
$objPHPExcel->getActiveSheet()->setTitle('any name you want'); // Change sheet's title if you want

unlink($tmpfile); // delete temporary file because it isn't needed anymore

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // header for .xlxs file
header('Content-Disposition: attachment;filename='.$filename); // specify the download file name
header('Cache-Control: max-age=0');

// Creates a writer to output the $objPHPExcel's content
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$writer->save('php://output');
exit;