如何使用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;

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...