【问题标题】:Download Excel in JavaScript from servlet response从 servlet 响应下载 JavaScript 中的 Excel
【发布时间】:2019-10-21 08:39:37
【问题描述】:

我在其他地方看到过很多类似的问题,但一直没能解决这个问题。

我想在我的应用程序中使用 Apache POI (3.17) 下载 Excel 文档。我在 Spring 服务中生成文档,然后将其作为响应传递回要下载的 JavaScript 客户端。但是,文件已损坏,因为“文件格式或文件扩展名无效”。

春季服务:

final Workbook workbook = new XSSFWorkbook();
final Sheet sheet = workbook.createSheet("Test");

Row row = sheet.getRow(1);
if (row == null)
{
    row = sheet.createRow(1);
}

Cell cell = row.getCell(0);
if (cell == null)
{
    cell = row.createCell(0);
}

cell.setCellValue("Testing123");

final ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
outArray = outByteStream.toByteArray();
outByteStream.flush();
outByteStream.close();
workbook.close();

小服务程序:

final ByteArrayResource resource = new ByteArrayResource(
                this.downloadService.downloadExcel(request, response, baseRequest));

final HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());

return ResponseEntity.ok()
        .headers(headers)
        .contentLength(resource.contentLength())
        .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
        .body(resource);

JavaScript 客户端:

var contentTypeHeader = 'application/vnd.ms-excel';
var blob = new Blob([result],{type: contentTypeHeader});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();

我哪里错了?

【问题讨论】:

    标签: javascript java excel spring apache-poi


    【解决方案1】:

    好吧,我确实想通了。我找到了解决问题的解决方案:

    Getting corrupted file while exporting .xls file using java/javascript and apache POI

    我需要在我的 servlet 中将文件编码为字符串,然后将其传递给客户端并解码为 Blob。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 2020-02-22
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      相关资源
      最近更新 更多