我在angular中創建了一個工廠來調用spring rest服務來下載xls文件。如何使用Angular和Spring Rest服務下載xls文件?
這是我廠:
angular.module('app')
.factory('SportsbookServiceCustom', function ($http) {
return {
exportToXLS: function() {
return $http.get('api/sportsbooks/downloadXLS').then(function (response) {
return response.data;
});
}
};
});
我有我的休息服務驗證碼:
@RequestMapping(value = "/sportsbooks/downloadXLS")
public void downloadXLS(HttpServletResponse response) {
Pageable pageable = new PageRequest(0, 20, Direction.ASC, "id");
Page<Sportsbook> page = sportsbookRepositoryCustom.findAll(pageable, null, null, null);
List<Sportsbook> sportsbookList = page.getContent();
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);
}
}
if (workbook != null) {
// Writing file to outputstream
try {
InputStream fileInputStream = new ByteArrayInputStream(workbook.getBytes());
OutputStream output = response.getOutputStream();
response.reset();
response.setContentLength((int) (workbook.getBytes().length));
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=yourFileName.xls");
IOUtils.copyLarge(fileInputStream, output);
output.flush();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
的代碼運行沒有錯誤,但下載的文件不能正常工作。什麼是錯誤?
_ _ 「是什麼錯誤?」 - 這是我們對你的期望的信息。沒有東西被髮回給客戶嗎? 'response.data'是空的嗎?最重要的是,你想要做什麼? 'exportToXLS'本身什麼都不做。如果你想要一個文件在瀏覽器中顯示或保存,那麼只需創建一個用戶可以點擊的鏈接。 – zeroflagL