javascript - 从 servlet 响应中下载 JavaScript 中的 Excel

标签 javascript java excel spring apache-poi

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

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

Spring 服务:

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();

Servlet:

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();

我哪里出错了?

最佳答案

好吧,我实际上已经弄清楚了。我找到了解决该问题的解决方案:

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

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

关于javascript - 从 servlet 响应中下载 JavaScript 中的 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58482636/

相关文章:

javascript - JQuery Mobile 对话框页面无法正常工作

javascript - Click 事件不在 <object> 标记上执行

javascript - Javascript、CoffeeScript、TypeScript、ES5 和 ES6 之间的关系

java - org.openqa.selenium.NoSuchWindowException : Unable to get browser

java - 调整 Jackrabbit 数据模型(VERSION_BUNDLE 表)

vba - 使用集合作为类中的属性(参数不可选)

javascript - 键盘事件在 Bing AJAX V8 中不起作用

java - EasyMock:获取 EasyMock.anyObject() 的真实参数值?

excel - 如何在 Excel 中动态插入列?

excel - 将单元格中的日期时间与两个日期VBA进行比较