如何使用PHPExcel将html表导出为ex​​cel?

 IvyShao520 发布于 2023-01-11 16:17

因为在不同浏览器之间很难处理不同的标准,所以我放弃尝试使用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中),这些都是正确的.

1 个回答
  • 要将内容直接放入$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;
    

    2023-01-11 16:20 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有