【问题标题】:Angular2 excel file download via Spring boot通过 Spring Boot 下载 Angular2 excel 文件
【发布时间】:2017-11-08 04:02:26
【问题描述】:

我正在尝试通过从 angular2 连接 spring boot 来下载 excel 文件。 我的靴子如下所示

@RequestMapping(method = RequestMethod.GET,value="/downloadExcel/{weekEnd}",produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity  downloadLastWeekOOOData(@PathVariable String weekEnd,HttpServletRequest request,HttpServletResponse response) throws IOException{


    File result=new File("C:\\sayan\\poi-test.xls");
    String type=result.toURL().openConnection().guessContentTypeFromName("poi-test.xls");
    FileInputStream inputStream = new FileInputStream(new File("C:\\sayan\\poi-test.xls"));
    byte[]out=org.apache.commons.io.IOUtils.toByteArray(inputStream);

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("content-disposition", "attachment; filename=" + "poi-test.xlsx");
    responseHeaders.add("Content-Type",type);

    ResponseEntity  respEntity = new ResponseEntity(out, responseHeaders,HttpStatus.OK);
    System.out.println(respEntity.getBody());
    return respEntity;

}

angular2 代码如下:

downloadExcel(weekEnd: string) {
let downloadSuccess: boolean = false;
this.lastWeekOOOService.downloadExcel(weekEnd)
  .subscribe(blob => {
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = "Report.xlsx";
    link.click();
  },
  error => console.log("Error downloading the file."),
  () => console.info("OK"));

}

服务看起来像:

downloadExcelOOO(weekEnd:string): Observable<Response> {
    return this._http.get('http://localhost:8080/downloadExcel/'+weekEnd)
                .map(res => new Blob([res],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
                .catch(this.handleError);
}

但我下载的文件 Report.xlsx 已损坏。

【问题讨论】:

  • 尝试在你的 Angular 代码中设置 contentType。
  • 已在服务中设置:类型:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  • 起初它显示一个警告框,上面写着“您尝试打开的文件的格式与文件扩展名指定的格式不同。在打开之前验证文件没有损坏并且来自受信任的来源文件。你想现在打开它吗?”单击“是”时,xls 文件将打开一个单元格,如下所示:响应状态:200 对 URL:169.172.218.252:8080/downloadExcel/downloadExcelOOO/2017-11-05

标签: excel spring angular spring-boot download


【解决方案1】:

在春季将excel作为输入流复制到响应输出流。 在 Angular 中将 httpoptions 放入 post 中,在 httpoptions 中将参数 responseType:'arraybuffer' 作为 'arraybuffer'。在订阅中直接使用 blob 中的 arraybuffer 对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-03
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多