PHPExcel下载文件 [英] PHPExcel download file

查看:575
本文介绍了PHPExcel下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载一个使用PHPExcel生成的excel文件.我遵循了 PHPExcel强制下载问题中的代码,但无济于事.记录接收到的数据后,控制台仅显示完整的这些符号.但是,当我将$objWriter->save('php://output');更改为$objWriter->save('filename.xlsx');时,它只是将文件下载到Web服务器的根文件夹中,而没有任何下载的指示.文件.以下是我的php文件的代码段

I wanted to download an excel file generated by using PHPExcel. I followed the code from PHPExcel Force Download Issue and to no avail. After I log the data receive, my console only shows full of these symbols �.However, when I change the $objWriter->save('php://output'); to $objWriter->save('filename.xlsx'); then it just download the file to my root folder in my web server without any indication of downloading a file. Below is the code snippet for my php file

<?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代码段:

Here is my angularjs code snippet:

$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文件.

Note: I'm using AngularJS $http.post to call the php file.

浏览器:谷歌浏览器

我已经尝试了来自PHPExcel 01simple-download-xlsx.php的示例php代码,结果也相同.

I have tried the sample php code from PHPExcel 01simple-download-xlsx.php and the result also same.

更新:我已经找到了一些解决方案,方法是搜索通过接受Excel作为响应来获取AngularJS,但下载后,似乎文件中出现乱码或类似于我注销的符号损坏的符号安慰.除此之外,文件名是随机文本和数字,而不是我在php代码中分配的文件名.代码如下:

UPDATE:I have found some solution by searching about getting AngularJS by accepting Excel as a response but after download it, it seems the file is corrupted with gibberish text or symbols similar to the one that logs out in my console. Besides that, the filename is random text and numbers instead of the filename I assigned in my php code. The code is as below:

var blob = new Blob([data], {type: "application/vnd.ms-excel"});
                    var objectUrl = URL.createObjectURL(blob);

推荐答案

我找到了使用AngularJS下载的解决方案,该解决方案可以即时更改文件名.我们将需要下载 FileSave.js ,并将其包含在index.html的标题中.代码段如下:

I have found a solution to download using AngularJS with ability to change the filename on the fly. We will need to download FileSave.js and include in the header of index.html. The code snippet is as below:

main.js

$scope.fetchReport = function(){
            $http({
                url: 'path_to_php_file',
                method: 'POST',
                responseType: 'arraybuffer',
                headers: {
                    'Content-type': 'application/json',
                    'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                }
            }).success(function(data){
                var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
                saveAs(blob, file_name_to_be+'.xlsx');
            }).error(function(){
                //Some error log
            });
        }

index.html

index.html

<button class="btn btn-primary" ng-click="fetchReport()">Get Report</button>

php文件与问题中的文件相同,只需在exit;

php file is same as in the question, just need to add a few lines before exit;

header('Content-disposition: attachment; filename='.$filename);
header('Content-Length: ' . filesize($filename));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');

//Replace php://output with $filename and add code below after that(before exit;)
readfile($filename);

注意:仅适用于HTML5支持的浏览器.

Note: It's only for HTML5 suppported browser.

这篇关于PHPExcel下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆