利用XSSFWorkbook 來生成.xlsx型別的Excel表格
阿新 • • 發佈:2019-02-11
以下是一個demo:
@RequestMapping("/downExample") public void downExample(HttpServletResponse response,HttpServletRequest request){ String advProJson = request.getParameter("advProJson"); List<AdvProEntity> advProList = JsonChangeUtil.jsonToList(advProJson, AdvProEntity.class); XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("報表"); XSSFCellStyle style = wb.createCellStyle(); //設定style---cell中水平的對齊方式 style.setAlignment(HorizontalAlignment.CENTER); //設定style---cell中垂直方向的對齊方式 style.setVerticalAlignment(VerticalAlignment.CENTER); //合併單元格 引數說明:1:開始行 2:結束行 3:開始列 4:結束列 sheet.addMergedRegion(new CellRangeAddress(0,0,0,8)); sheet.addMergedRegion(new CellRangeAddress(1,2,8,8)); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellValue("報表報告"); cell.setCellStyle(style); row = sheet.createRow(1); for(int i=0;i<9;i++){ //設定列寬 sheet.setColumnWidth(i, 4000); //設定行高 //row.setHeight((short)1000); if(i==0){ cell = row.createCell(0); cell.setCellValue("日期"); cell.setCellStyle(style); }else if(i==8){ cell = row.createCell(i); cell.setCellValue("TOTAL"); cell.setCellStyle(style); }else{ Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DAY_OF_MONTH, -6+i-1); String date = DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd"); cell = row.createCell(i); cell.setCellValue(date); cell.setCellStyle(style); } } row = sheet.createRow(2); for(int i=0;i<9;i++){ if(i==0){ cell = row.createCell(i); cell.setCellValue("時段"); cell.setCellStyle(style); }else{ cell = row.createCell(i); cell.setCellValue("資料"); cell.setCellStyle(style); } } for(int k=0;k<24;k++){ row = sheet.createRow(2+1+k); cell = row.createCell(0); cell.setCellValue(String.valueOf(k)+":00-"+String.valueOf(k)+":59"); cell.setCellStyle(style); for(int g=0;g<8;g++){ cell = row.createCell(1+g); cell.setCellValue(advProList.get(k).getMap().get(String.valueOf(g))); cell.setCellStyle(style); } } try { response.setHeader("content-Disposition","attachment;filename=" + URLEncoder.encode("報表.xlsx","utf-8")); OutputStream out = response.getOutputStream(); wb.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } }