使用Django和Angular2下载Excel文件

时间:2017-05-05 09:46:41

标签: python angularjs django excel filesaver.js

我有一个项目,我将文件保存在SMB文件夹中,并使用Django作为背面,Angular 2作为正面。我已成功设法下载.csv文件,但是当下载.xls文件时,它已损坏。文件中的行如下所示:

  

管理-格里舍姆
  的Ba == O' X< * 8X @" 1Arial1Arial1Arial1Arial1 Arial1 Arial1 $ Arial1Arial1Calibri1

这是我的views.py文件:

 '''Download file'''
def get(self, request, file_name):

    bicloudreposervice = BiCloudRepoService()

    file_obj = bicloudreposervice.get_user_file(request.user.email, file_name)
    file_path = file_obj.name

    with open(file_path, 'rb') as tmp:

        if 'xls' in file_name:
            resp = HttpResponse(tmp, content_type='application/vnd.ms-excel;charset=UTF-8')
        else:
            resp = HttpResponse(tmp, content_type='application/text;charset=UTF-8')

        resp['Content-Disposition'] = "attachment; filename=%s" % file_name

    self.logger.debug('Downloading file')

    return resp

typescript中服务文件中的相关功能如下所示:

  downloadFile(fileName: string){
     let headers = this.headers;

     let options = new RequestOptions({ headers: headers });

     return this.http.get(this.connectorsUrl+'download-file/' + fileName + '/', options)
                .map(res => res)
                .catch(this.utils.handleError);
  }

组件文件:

  import * as FileSaver from "file-saver";
   ...

  downloadFile(name){
   this.connectorsService.downloadFile(name).subscribe(
   res => {this.successDownloadFile(res, name);},
   error =>  this.errorMessage = <any>error,
   ()=> {});
 }

 successDownloadFile(res: any, name: String){

  this.showLoader = false;
  let blob;

  blob = new Blob([res._body], {type: 'application/vnd.ms-excel'});

  FileSaver.saveAs(blob, name.toString());
}

相应的html文件:

...
<div (click)="downloadFile(file.name)">
    <i class="material-icons">file_download</i>
</div>
...

我使用外部库FileSaver,但我也试过从Blob创建一个URL对象,并在Angular中创建window.open,但文件看起来仍然相同。 在Angular中创建Blob时,我在views.py和content_type='application/vnd.ms-excel;charset=UTF-8'中尝试了{type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});

我能做错什么?也许我应该在Django中以不同的方式处理文件? 提前感谢您的帮助。

0 个答案:

没有答案