【发布时间】:2015-05-15 11:24:37
【问题描述】:
我想下载一个使用 PHPExcel 生成的 excel 文件。我按照PHPExcel Force Download Issue 的代码进行操作,但无济于事。在我记录数据接收后,我的控制台只显示这些符号...但是,当我将 $objWriter->save('php://output'); 更改为 $objWriter->save('filename.xlsx'); 时,它只是将文件下载到我的 Web 服务器的根文件夹中,而没有任何迹象表明下载了文件。下面是我的 php 文件的代码 sn-p
<?php
$con = mysqli_connect('localhost', 'root', '', 'test');
mysqli_select_db($con, 'test');
$qry = "SELECT * FROM lostitem";
$res = mysqli_query($con, $qry);
require_once '/Classes/PHPExcel.php';
include '/Classes/PHPExcel/Writer/Excel2007.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
/** Determine filename **/
$filename = "report.xlsx";
/** Set header information **/
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$F=$objPHPExcel->getActiveSheet();
$Line=1;
$F->setCellValue('A'.$Line, 'Lost Item ID');
$F->setCellValue('B'.$Line, 'Lost Item Title');
$F->setCellValue('C'.$Line, 'Lost Item Description');
while($Trs=mysqli_fetch_assoc($res)){//extract each record
++$Line;
$F->setCellValue('A'.$Line, $Trs['LostItemID']);
$F->setCellValue('B'.$Line, $Trs['LostItemTitle']);
$F->setCellValue('C'.$Line, $Trs['LostItemDescription']);//write in the sheet
//++$Line;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>
这是我的 angularjs 代码 sn-p:
$scope.getReport = function(type){
if(type == 'lost'){
$http.post("getLostItemReport.php")
.success(function(data, status, headers, config){
console.log("Get report data: " + data);
})
}
}
注意:我使用 AngularJS $http.post 来调用 php 文件。
浏览器:谷歌浏览器
编辑:我尝试了 PHPExcel 01simple-download-xlsx.php 中的示例 php 代码,结果也相同。
更新:我通过接受 Excel 作为响应来搜索有关获取 AngularJS 的方法找到了一些解决方案,但下载后,该文件似乎被乱码文本或符号损坏,类似于在我的安慰。除此之外,文件名是随机文本和数字,而不是我在我的 php 代码中分配的文件名。代码如下:
var blob = new Blob([data], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
【问题讨论】:
-
已经试过了。您可以在我的问题代码中看到它们。
-
那个“乱码”是 Excel 文件.... xls 和 xlsx 都是二进制格式.... angular 不知道如何处理内容类型为
application/vnd.ms-excel或application/vnd.openxmlformats-officedocument.spreadsheetml.sheet的原始二进制流 -
是的。我还发现它实际上是excel文件。感谢您指出 angular 不知道如何处理内容类型为
application/vnd.ms-excel或application/vnd.openxmlformats-officedocument.spreadsheetml.sheet的原始二进制流。将尝试搜索解决该问题。
标签: php angularjs phpexcel export-to-excel