為什么老師這里讀取excel文件要使用HSSFWorkBook,而沒有使用輸入流FileInputStream?我現在遇到一個bug,前端使用a標簽進行下載。a標簽超鏈接指向后臺的下載接口。下載接口使用FileInputStream讀取項目下的excel文件。通過response.getOutputStream輸出流寫出文件。這樣的下載思路正確嗎?運行結果是下載的excel文件打開內容為空。這個問題在哪里?老師能指導一下嗎?
前端代碼:
<a?:href="'/api/campaign-api/coupon/down'"?download="down.xlsx">下載</a>
后端代碼:
1.接口
@ApiOperation(value?=?"下載")
@GetMapping("/down")
public?void?downTemplate(HttpServletResponse?response)?{
????String?fileName?=?"down.xlsx";
????couponService.down(response,?fileName);
}2.實現類
public?void?down(HttpServletResponse?response?,String?filename)?{
????//?讀取要下載的文件,保存到文件輸入流
????FileInputStream?in?=?null;
????OutputStream?out?=?null;
????try?{
????????//?要下載的目標文件
????????File?file?=?new?File("src\\main\\resources\\static"?+?"\\"?+?filename);
????????//?如果文件不存在
????????if?(!file.exists())?{
????????????throw?new?BusinessException("Could?not?read?file");
????????}
????????//?設置響應頭,控制瀏覽器下載該文件
????????response.setHeader("Content-Disposition",?"attachment;filename="+filename);
????????response.setHeader("Content-Type",?"application/octet-stream;charset=UTF-8");
????????response.setContentType("application/octet-stream");
????????in?=?new?FileInputStream(file);
????????//?創建輸出流
????????out?=?response.getOutputStream();
????????//?創建緩沖區
????????byte?buffer[]?=?new?byte[1024];
????????int?len?=?0;
????????//?循環將輸入流中的內容讀取到緩沖區當中
????????while?((len?=?in.read(buffer))?>?0)?{
????????????//?輸出緩沖區的內容到瀏覽器,實現文件下載
????????????out.write(buffer,?0,?len);
????????}
????????//?關閉文件輸入流
????????in.close();
????????//?關閉輸出流
????????out.close();
????}?catch?(Exception?e)?{
????????e.printStackTrace();
????}
}
2019-07-09
正確流程:1.獲取到數據 2.解析到excle中 3.將解析的excel轉換成輸出流到前端,僅表示個人看法?
2019-07-09
沒看到對excel文件的操作,感覺你流程就不對?