gpt4 book ai didi

angularjs - 将响应下载为 excel 文件

转载 作者:行者123 更新时间:2023-12-01 07:53:15 26 4
gpt4 key购买 nike

文件未在浏览器中下载。我正在准备文件并将其写入响应输出流。

休息API在那里:

@RequestMapping(value = "/export-companies",
method = {RequestMethod.GET, RequestMethod.HEAD})
@Timed
public void downloadCompanies(HttpServletResponse response) throws URISyntaxException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");

Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});

Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}

try {
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
byte [] outArray = outByteStream.toByteArray();
response.setContentType("application/ms-excel");
response.setContentLength(outArray.length);
response.setHeader("Expires:", "0"); // eliminates browser caching
response.setHeader("Content-Disposition", "attachment; filename=template.xls");
OutputStream outStream = response.getOutputStream();
outStream.write(outArray);
outStream.flush();
workbook.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

从前端(使用 Angular JS):
(function() {
'use strict';

angular
.module('MyApp')
.factory('CompanyExportService', CompanyExportService);

CompanyExportService.$inject = ['$resource'];

function CompanyExportService ($resource) {
var service = $resource('api/export-companies', {}, {
'get': {
method: 'GET',
isArray: false
}
});

return service;
}
})();

文件内容以不可读的格式作为响应。但是文件不会在浏览器中下载。

最佳答案

Angular 将接收文件内容仅仅是字符序列。您需要从这些字符创建一个文件并在前端启动浏览器下载。

你可以这样做 -

var blob = new Blob([data], 
{type: 'application/vnd.openxmlformat-officedocument.spreadsheetml.sheet;'});
saveAs(blob, fileName);

哪里 data是您从 API 收到的响应。 saveAs函数是 FileSaver.js 的一部分图书馆。尽管您可以查看如何手动执行此操作,但为什么要重新发明轮子?

关于angularjs - 将响应下载为 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38603209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com