java中對於excel文件的操作,有讀取,寫入,上傳等功能,在對excel文件進行操作時,為了讓使用者更加直觀的制作excel數據,必然會有下載模板excel文件功能,
這里以學生基本信息模板excel文件為例,實現對指定路徑下的excel文件進行下載的后台代碼。
對excel文件的操作使用到poi接口,對於不同拓展名的excel文件調用不同的對象,maven導入jar包語句可以參考poi導入jar包。
我們在這里操作的對象是.xlsx格式的excel文件。代碼如下:
/** * 學生excel模板下載,可用於批量新建,修改學生對象, * * @param response * @param request * @return */ @RequestMapping(value = "downLoadStuInfoExcel", produces = "text/html;charset=UTF-8") public void downLoadStuInfoExcel(HttpServletResponse response, HttpServletRequest request) { JSONObject rt = new JSONObject(); //json對象,用來記錄下載狀態值,寫入log中,也可以把狀態值返回到前台,這一部分可有可無。 rt.put("status", "1"); rt.put("message", ""); rt.put("result", ""); //學生新建excel下載模板保存地址從配置文件中讀取 String folderPath = ResourceBundle.getBundle("systemconfig").getString("stuExcelDownLoadPath") + File.separator + "stuTemplateExcel.xlsx"; File excelFile = new File(folderPath); //判斷模板文件是否存在 if (!excelFile.exists() || !excelFile.isFile()) { rt.put("status", "0"); rt.put("message", "模板文件不存在"); // return rt.toJSONString(); } //文件輸入流 FileInputStream fis = null; XSSFWorkbook wb = null; //使用XSSFWorkbook對象讀取excel文件 try { fis = new FileInputStream(excelFile); wb = new XSSFWorkbook(fis); fis.close(); } catch (Exception e) { e.printStackTrace(); rt.put("status", "0"); rt.put("message", "模板文件讀取失敗"); // return rt.toJSONString(); } //設置contentType為vnd.ms-excel response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setCharacterEncoding("utf-8"); // 對文件名進行處理。防止文件名亂碼,這里前台直接定義了模板文件名,所以就不再次定義了 //String fileName = CharEncodingEdit.processFileName(request, "stuTemplateExcel.xlsx"); // Content-disposition屬性設置成以附件方式進行下載 response.setHeader("Content-disposition", "attachment;filename=stuTemplateExcel.xlsx"); //調取response對象中的OutputStream對象 OutputStream os = null; try { os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); rt.put("status", "0"); rt.put("message", "模板文件下載失敗"); } logger.info("下載學生模板文件結果:" + rt.toJSONString()); //return rt.toJSONString(); }
注意事項:
- 對excel文件讀取使用了FileInputStream對象,然后生成新的XSSFWorkbook對象
- 在文件的讀取和寫入的動作完成后,把對應的流關閉
下載得到的excel模板文件:
以上就是對Java中下載excel文件后台處理的總結歸納。歡迎一起探討更加高效的解決方案