Spring+SpringMvc的Excel匯出功能
阿新 • • 發佈:2018-12-30
該功能採用的是Excel2007版,以Map鍵值對作為資料匯出,當然List資料也是一樣的。Excel模板存放於:WebRoot-WEB-INF下面建立一個自己的資料夾:excelModelFile裡,excel模板表頭要自己先設計好。下面之間貼程式碼
1.controller:
@Controller public class ExcelController { public static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ExcelController.class); @ResponseBody@RequestMapping(value="excelDownload.html",method={RequestMethod.POST}) public JSONObject excelDownload(HttpServletRequest request, HttpServletResponse response) { System.out.println("通過 jquery.form.js 提供的ajax方式匯出檔案!"); JSONObject js = new JSONObject(); JSONObject resultJs = new JSONObject();String reqStr = request.getParameter("Data"); if(reqStr == null){ return resultDataJs("","請選擇要匯出的資料!",false,resultJs); } JSONObject dataJs = JSONObject.fromObject(reqStr); OutputStream os = null; Workbook wb = null; //工作薄 String type = dataJs.getString("type");//這是用於多個檔案匯出時的標識//這裡只舉例一個 try { if("bmSend".equals(type)){ wb = writeBMSendDtl(js,wb,os,response,dataJs,resultJs); } //else if("bmReceipt".equals(type)){ //wb = writeBMReceiptDtl(js,wb,os,response,dataJs,resultJs); //} if(wb == null){ return resultDataJs("",resultJs.getString("erroe"),false,resultJs); } os = response.getOutputStream(); wb.write(os); } catch (Exception e) { return resultDataJs("","下載出錯了,請聯絡客服!",false,resultJs); } finally{ try { os.flush(); os.close(); } catch (IOException e) { return resultDataJs("","下載出錯了,請聯絡客服!",false,resultJs); } } return resultDataJs("","下載完成",true,resultJs); } /** * 出庫明細匯出 * @param js * @param wb * @param os * @param response * @param dataJs * @return * @throws Exception */ private Workbook writeBMSendDtl(JSONObject js, Workbook wb, OutputStream os, HttpServletResponse response,JSONObject dataJs,JSONObject resultJs) throws Exception{ logger.info("進入荒料出庫明細匯出介面"); js = SlswUtils.erpAxisRequest(Global.WSDLURL, "ReportDataWebService", "getBMOut", "{ user:'sczx',password:'123456',reqKey:'SSS',data:[{"+analysisJson(dataJs)+"}] }");//這是呼叫別人的報表介面返回的資料 List<Map<String,Object>> jsList = (List<Map<String, Object>>) js.get("list"); if(jsList == null){ resultJs.put("error","荒料出庫明細匯出失敗,沒有查詢到相應資料,若有疑問請聯絡客服!"); resultJs.put("flag",false); return null; } JSONObject jsDtl = SlswUtils.erpAxisRequest(Global.WSDLURL, "ReportDataWebService", "getBMOutDtl", "{ user:'sczx',password:'123456',reqKey:'SSS',data:[{"+analysisJson(dataJs)+"}] }");//這是呼叫別人的報表介面返回的資料 List<Map<String,Object>> jsOutDtl = (List<Map<String, Object>>) jsDtl.get("list");//這裡獲取介面返回的集合資料 logger.info("荒料出庫明細匯出介面,ERP呼叫介面完成,開始寫入EXCEL"); //匯出Excel檔案資料 File file =ExportExcelUtil.getExcelDemoFile("/ExcelModelFile/荒料出庫明細.xlsx"); String sheetName ="荒料出庫彙總";//分頁名稱 String sheetName2="荒料出庫明細"; wb = ExcelModel.writeBMSendAndReceipDtlExcel(wb,file, sheetName,sheetName2,jsList,jsOutDtl);//因為該excel有兩個分頁 logger.info("荒料出庫明細匯出 資料解析完成=="); ExportExcelUtil.outResponseForDown(response,"荒料出庫.xlsx",wb,os); resultJs.put("flag",true); return wb; }}
2.匯出excelUtil類:
public class ExportExcelUtil { public static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ExportExcelUtil.class); /** * 描述:根據檔案路徑獲取專案中的檔案 * @param fileDir 檔案路徑 * @return * @throws Exception */ public static File getExcelDemoFile(String fileDir) throws Exception{ String classDir = null; String fileBaseDir = null; File file = null; classDir = Thread.currentThread().getContextClassLoader().getResource("/").getPath(); fileBaseDir = classDir.substring(0, classDir.lastIndexOf("classes")); logger.info("檔案地址===="+(fileBaseDir+fileDir)); file = new File(fileBaseDir+fileDir); logger.info("判斷讀取檔案boolean == "+file.exists()); if(!file.exists()){ throw new Exception("模板檔案不存在!"); } return file; } /** * 描述:設定簡單的Cell樣式 * @return */ public static CellStyle setSimpleCellStyle(Workbook wb,String str){ CellStyle cs = wb.createCellStyle(); cs.setBorderBottom(CellStyle.BORDER_THIN); //下邊框 cs.setBorderLeft(CellStyle.BORDER_THIN);//左邊框 cs.setBorderTop(CellStyle.BORDER_THIN);//上邊框 cs.setBorderRight(CellStyle.BORDER_THIN);//右邊框 if("center".equals(str)){ cs.setAlignment(CellStyle.ALIGN_CENTER); // 居中對齊 } else if("right".equals(str)){ cs.setAlignment(CellStyle.ALIGN_RIGHT); // 右對齊 } else if("left".equals(str)){ cs.setAlignment(CellStyle.ALIGN_LEFT); // 左對齊 } return cs; } public static Workbook getWorkbook(InputStream inStr, String fileName) { Workbook wb = null; String fileType = fileName.substring(fileName.lastIndexOf(".")); try { if(".xls".equals(fileType)){ wb = new HSSFWorkbook(inStr); }else if(".xlsx".equals(fileType)){ wb = new XSSFWorkbook(inStr); //2007+ } } catch (IOException e) { e.printStackTrace(); } return wb; } public static void outResponseForDown(HttpServletResponse response,String fileName,Workbook wb, OutputStream os) throws IOException{ response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8")); /*os = response.getOutputStream(); wb.write(os);*/ } }
3.ExcelModel類:
public class ExcelModel { public static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ExcelModel.class); /** * 荒料出庫明細匯出 * 荒料入庫明細匯出 * * @param file * @param sheetName * @param lis * @return * @throws Exception */ public static Workbook writeBMSendAndReceipDtlExcel(Workbook wb, File file, String sheetName, String sheetName2, List<Map<String, Object>> lis, List<Map<String, Object>> listJson) throws Exception { Row row = null; Cell cell = null; FileInputStream fis = new FileInputStream(file); wb = ExportExcelUtil.getWorkbook(fis, file.getName()); //獲取工作薄 Sheet sheet = wb.getSheet(sheetName); //迴圈插入資料 int lastRow = sheet.getLastRowNum() + 1; //插入資料的資料ROW for (int i = 0; i < lis.size(); i++) { row = sheet.createRow(lastRow + i); //建立新的ROW,用於資料插入 Map<String, Object> map = lis.get(i); //按專案實際需求,在該處將物件資料插入到Excel中 //Cell賦值開始 cell = row.createCell(0); cell.setCellValue(i + 1); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "center")); cell = row.createCell(1); cell.setCellValue(map.get("mtlname").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "left")); cell = row.createCell(2); cell.setCellValue(map.get("qty").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); cell = row.createCell(3); cell.setCellValue(map.get("weight").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); cell = row.createCell(4); cell.setCellValue(map.get("volume").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); } Sheet sheet2 = wb.getSheet(sheetName2); //迴圈插入資料 int lastRow2 = sheet2.getLastRowNum() + 1; for (int i = 0; i < listJson.size(); i++) { row = sheet2.createRow(lastRow2 + i); //建立新的ROW,用於資料插入 Map<String, Object> map = listJson.get(i); //按專案實際需求,在該處將物件資料插入到Excel中 //Cell賦值開始 cell = row.createCell(0); cell.setCellValue(i + 1); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "center")); cell = row.createCell(1); cell.setCellValue(getSubTime(map.get("billdate").toString())); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); cell = row.createCell(2); cell.setCellValue(map.get("mtlname").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "left")); cell = row.createCell(3); cell.setCellValue(map.get("materialtype").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "left")); cell = row.createCell(4); cell.setCellValue(map.get("msid") + "/" + map.get("csid")); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); cell = row.createCell(5); cell.setCellValue(map.get("whsname").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "left")); cell = row.createCell(6); cell.setCellValue(map.get("storeareaname").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "left")); cell = row.createCell(7); cell.setCellValue(map.get("locationname").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "left")); cell = row.createCell(8); cell.setCellValue(map.get("lenght").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); cell = row.createCell(9); cell.setCellValue(map.get("width").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); cell = row.createCell(10); cell.setCellValue(map.get("height").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); cell = row.createCell(11); cell.setCellValue(map.get("weight").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); cell = row.createCell(12); cell.setCellValue(map.get("volume").toString()); cell.setCellStyle(ExportExcelUtil.setSimpleCellStyle(wb, "right")); } return wb; } }
4.到這裡匯出功能就完成了,但是要注意的是檔案地址一定不能有空格或中文否則都會發生錯誤。
模板位置:
模板excel設計: