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

前端之家收集整理的这篇文章主要介绍了如何使用PHPExcel将html表导出到Excel?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
因为在不同浏览器之间很难处理不同的标准,所以我放弃尝试使用js或jQuery导出html表.我想知道我是否可以将html中的表重新发送回服务器并在服务器上生成.xls文件用户下载.

现在在服务器端使用PHPExcel,我的代码是这样的:

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

ini_set('zlib.output_compression','Off'); 
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
//the folowing two lines make sure it is saved as a xls file
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename='.$filename);

$objReader = PHPExcel_IOFactory::createReader('HTML');
$objPHPExcel = $objReader->load($table);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
$objWriter->save('PHP://output');

exit;

问题是我无法直接加载html表.我该怎么处理?

还有一个问题是,当我在PHP中设置标题时,单击按钮时文件不会下载.实际上,我可以查看POST响应的Header的所有属性,以及响应的内容(在FireBug中),这些都是正确的.

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

要插入整个HTML表,必须从HTMLReader中读取它

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

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

猜你在找的PHP相关文章