如何使用PHPExcel将html表导出到Excel?
发布时间:2020-12-13 13:37:24 所属栏目:PHP教程 来源:网络整理
导读:因为在不同浏览器之间很难处理不同的标准,所以我放弃尝试使用js或jQuery导出html表.我想知道我是否可以将html中的表重新发送回服务器并在服务器上生成.xls文件供用户下载. 现在在服务器端使用PHPExcel,我的代码是这样的: $filename = "DownloadReport";$tab
因为在不同浏览器之间很难处理不同的标准,所以我放弃尝试使用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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |