為什么老師這里讀取excel文件要使用HSSFWorkBook,而沒有使用輸入流FileInputStream?我現(xiàn)在遇到一個(gè)bug,前端使用a標(biāo)簽進(jìn)行下載。a標(biāo)簽超鏈接指向后臺(tái)的下載接口。下載接口使用FileInputStream讀取項(xiàng)目下的excel文件。通過response.getOutputStream輸出流寫出文件。這樣的下載思路正確嗎?運(yùn)行結(jié)果是下載的excel文件打開內(nèi)容為空。這個(gè)問題在哪里?老師能指導(dǎo)一下嗎?
前端代碼:
<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.實(shí)現(xiàn)類
public?void?down(HttpServletResponse?response?,String?filename)?{ ????//?讀取要下載的文件,保存到文件輸入流 ????FileInputStream?in?=?null; ????OutputStream?out?=?null; ????try?{ ????????//?要下載的目標(biāo)文件 ????????File?file?=?new?File("src\\main\\resources\\static"?+?"\\"?+?filename); ????????//?如果文件不存在 ????????if?(!file.exists())?{ ????????????throw?new?BusinessException("Could?not?read?file"); ????????} ????????//?設(shè)置響應(yīng)頭,控制瀏覽器下載該文件 ????????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); ????????//?創(chuàng)建輸出流 ????????out?=?response.getOutputStream(); ????????//?創(chuàng)建緩沖區(qū) ????????byte?buffer[]?=?new?byte[1024]; ????????int?len?=?0; ????????//?循環(huán)將輸入流中的內(nèi)容讀取到緩沖區(qū)當(dāng)中 ????????while?((len?=?in.read(buffer))?>?0)?{ ????????????//?輸出緩沖區(qū)的內(nèi)容到瀏覽器,實(shí)現(xiàn)文件下載 ????????????out.write(buffer,?0,?len); ????????} ????????//?關(guān)閉文件輸入流 ????????in.close(); ????????//?關(guān)閉輸出流 ????????out.close(); ????}?catch?(Exception?e)?{ ????????e.printStackTrace(); ????} }
2019-07-09
正確流程:1.獲取到數(shù)據(jù) 2.解析到excle中 3.將解析的excel轉(zhuǎn)換成輸出流到前端,僅表示個(gè)人看法?
2019-07-09
沒看到對(duì)excel文件的操作,感覺你流程就不對(duì)?