如何在Angular 4中下载excel / Zip文件

时间:2017-09-11 10:08:29

标签: excel angular file download

我使用角4作为前端,而内腔5.4作为后端。

我的要求是将一些数据导出为ex​​cel和zip文件。

使用{ saveAs }包中的导入'file-saver/FileSaver';进行文件下载。

Angular 4代码:

downloadExcel() {

const type = 'application/vnd.ms-excel';
const headers = { headers: new Headers({ 'Accept': type }) };
const filename = 'file.xls';

this.http.get('http://10.2.2.109/Download/exportExcel', headers)
  .toPromise()
  .then(response => this.saveToFileSystem(response, type, filename));

return false;


}



private saveToFileSystem(response, __type, filename) {
    const contentDispositionHeader: string = response.headers.get('Content-Disposition');

if (contentDispositionHeader !== null) {
  const parts: string[] = contentDispositionHeader.split(';');
  //const filename = parts[1].split('=')[1];
  const blob = new Blob([response._body], { type: __type });
  saveAs(blob, filename);
} else {
  alert('Cant download.....');
  // handling download condition if content disposition is empty
  const blob = new Blob([response._body], { type: __type });
  saveAs(blob, filename);
}


}

流明代码

public function exportExcel(Request $request) {
        $file = storage_path();
        $file_name = 'book1.xls';
        $headers = [
            'Content-type' => 'application/vnd.ms-excel',
            'Content-Disposition' => 'attachment;filename="' . $file_name,
            'X-Filename' => $file_name,
            'Content-Transfer-Encoding' => 'binary',
            'Content-Length' => filesize($file . '/' . $file_name),
            'Cache-Control' => 'max-age=0',
            'Cache-Control' => 'max-age=1',
            'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
            'Last-Modified' => gmdate('D, d M Y H:i:s') . ' GMT',
            'Cache-Control' => 'cache, must-revalidate',
            'Pragma' => 'public',
            'Set-Cookie' => 'fileDownload=true; path=/',
            'Access-Control-Expose-Headers' => 'Content-Length,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma'
        ];

        return response()->download($file . '/' . $file_name, $file_name, $headers);
    }

问题

  1. const contentDispositionHeader: string = response.headers.get('Content-Disposition');似乎总是空着的。
  2. 我们无法打开下载的文件,显示已损坏的邮件。
  3. 用于文本文件下载
  4. 请帮我解决此问题。或者为angular

    指定任何其他工作代码//包

2 个答案:

答案 0 :(得分:9)

试试这个:

downloadExcel() {

  const type = 'application/vnd.ms-excel';
  const filename = 'file.xls';
  const options = new RequestOptions({
            responseType: ResponseContentType.Blob,
            headers: new Headers({ 'Accept': type })
        });

  this.http.get('http://10.2.2.109/Download/exportExcel', options)
           .catch(errorResponse => Observable.throw(errorResponse.json()))
           .map((response) => { 
                 if (response instanceof Response) {
                    return response.blob();
                 }
                 return response;
            })
           .subscribe(data => saveAs(data, filename),
                      error => console.log(error)); // implement your error handling here

}

关键点是RequestOptions上的responseType: ResponseContentType.Blob和获取回复时的response.blob()

一般情况下,不建议您访问响应的_body属性,如下所示:response._body,而应调用相关方法根据其获取正文内容类型(如response.blob()response.json()等)

答案 1 :(得分:0)

如果输入数据是JSON格式,您可以使用json2csv。该函数的输出将为CSV,可以在Microsoft Excel或Google表格中打开。

安装包:

$ npm install json2csv --save

将以下内容添加到您的组件中:

var json2csv = require('json2csv');
var fields = ['field1', 'field2', 'field3'];
var result = json2csv({ data: myData, fields: fields });