SpringMVC实现poi 解析excel 导入导出 详解
听说csdn编辑支持markdown了,果断从博客园转了过来(谁让我是markdown中毒依赖者~~)。这是我在csdn博客上的第一篇文章。最近,我在公司的项目上做了许多个模块涉及excel的导入导出解析,想把这些模块总结成文字,与大家分享,有不足之处,还望指正!
1.引入poi jar
要良好支持XSSF的话,下载poi 3.1以上的哦!
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14-beta1</version></dependency>
2. excel对应映射model
public class ExcelMapping { private String headTextName; private String propertyName; private Integer cols; private XSSFCellStyle cellStyle; public ExcelMapping() { } public ExcelMapping(String headTextName, String propertyName) { this.headTextName = headTextName; this.propertyName = propertyName; } public ExcelMapping(String headTextName, String propertyName, Integer cols) { super(); this.headTextName = headTextName; this.propertyName = propertyName; this.cols = cols; } ....}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
3. poi 生成 excel
/** * 多列头创建EXCEL * * @param sheetName 工作簿名称 * @param clazz 数据源model类型 * @param objs excel标题列以及对应model字段名 * @param map 标题列行数以及cell字体样式 * @return * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException * @throws ClassNotFoundException * @throws IntrospectionException * @throws ParseException */public static XSSFWorkbook createExcelFile(Class clazz, List objs,Map<Integer, List<ExcelMapping>> map,String sheetName) throws IllegalArgumentException,IllegalAccessException,InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException{ XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(sheetName); createFont(workbook); createTableHeader(sheet, map); createTableRows(sheet, map, objs, clazz); return workbook; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
4.样式createFont
public static void createFont(XSSFWorkbook workbook) { // 表头 XSSFCellStyle fontStyle = workbook.createCellStyle() XSSFFont font1 = workbook.createFont() font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD) font1.setFontName("黑体") font1.setFontHeightInPoints((short) 14) fontStyle.setFont(font1) fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN) fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN) fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN) fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN) fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER) // 内容XSSFCellStyle fontStyle2 =workbook.createCellStyle()XSSFFont font2 = workbook.createFont()font2.setFontName("宋体")font2.setFontHeightInPoints((short) 10)fontStyle2.setFont(font2) fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN) fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN) fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN) fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER)}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
public static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelMapping>> map) { int startIndex=0; int endIndex=0; for (Map.Entry<Integer, List<ExcelMapping>> entry : map.entrySet()) { XSSFRow row = sheet.createRow(entry.getKey()); List<ExcelMapping> excels = entry.getValue(); for (int x = 0; x < excels.size(); x++) { if(excels.get(x).getCols()>1){ if(x==0){ endIndex+=excels.get(x).getCols()-1; CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex); sheet.addMergedRegion(range); startIndex+=excels.get(x).getCols(); }else{ endIndex+=excels.get(x).getCols(); CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex); sheet.addMergedRegion(range); startIndex+=excels.get(x).getCols(); } XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols()); cell.setCellValue(excels.get(x).getHeadTextName()); if (excels.get(x).getCellStyle() != null) { cell.setCellStyle(excels.get(x).getCellStyle()); } cell.setCellStyle(fontStyle); }else{ XSSFCell cell = row.createCell(x); cell.setCellValue(excels.get(x).getHeadTextName()); if (excels.get(x).getCellStyle() != null) { cell.setCellStyle(excels.get(x).getCellStyle()); } cell.setCellStyle(fontStyle); } } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
5. 创建excel内容文本 createTableRows(sheet, map, objs, clazz)
PropertyDescriptor获取get、set详解
/** * * @param sheet * @param map * @param objs * @param clazz */ @SuppressWarnings("rawtypes") public static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelMapping>> map, List objs, Class clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException, ClassNotFoundException, ParseException { int rowindex = map.size(); int maxKey = 0; List<ExcelMapping> ems = new ArrayList<>(); for (Map.Entry<Integer, List<ExcelMapping>> entry : map.entrySet()) { if (entry.getKey() > maxKey) { maxKey = entry.getKey(); } } ems = map.get(maxKey); List<Integer> widths = new ArrayList<Integer>(ems.size()); for (Object obj : objs) { XSSFRow row = sheet.createRow(rowindex); for (int i = 0; i < ems.size(); i++) { ExcelMapping em = (ExcelMapping) ems.get(i); PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz); Method getMethod = pd.getReadMethod(); Object rtn = getMethod.invoke(obj); String value = ""; if (rtn != null) { if (rtn instanceof Date) { value = DateUtils.formatFullDate((Date) rtn); } else { value = rtn.toString(); } } XSSFCell cell = row.createCell(i); if (null != fontStyle2) { cell.setCellStyle(fontStyle2); } cell.setCellValue(value); cell.setCellType(XSSFCell.CELL_TYPE_STRING); cell.setCellStyle(FontStyle4); int width = value.getBytes().length * 300; if (widths.size() <= i) { widths.add(width); continue; } if (width > widths.get(i)) { widths.set(i, width); } } rowindex++; } for (int index = 0; index < widths.size(); index++) { Integer width = widths.get(index); width = width < 2500 ? 2500 : width + 300; width = width > 10000 ? 10000 + 300 : width + 300; sheet.setColumnWidth(index, width); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
6.生成对应model数据源的excel
public XSSFWorkbook exportWorkBook(UserModel model) throws CommonException { List<UserModel> users = userService.selectByExample(model); if (users == null || users.size()==0) { throw new Exception("暂无导出数据"); } Map<String, List<UserModel>> resultMap = userModel.getResultMap(); List<ExcelMapping> ems = new ArrayList<>(); Map<Integer, List<ExcelMapping>> map = new LinkedHashMap<>(); XSSFWorkbook book = null; ems.add(new ExcelMapping("人员基本信息", "basicInformation", 3)); ems.add(new ExcelMapping("证件信息", "idcInformation", 6)); ems.add(new ExcelMapping("其他信息", "otherInformation", 10)); ems.add(new ExcelMapping("公司信息", "bigCsrInformation", 5)); map.put(0, ems); List<ExcelMapping> ems2 = new ArrayList<>(); ems2.add(new ExcelMapping("员工姓名", "userName", 0)); ems2.add(new ExcelMapping("员工姓名(英/拼音)", "userNameEn", 0)); ems2.add(new ExcelMapping("生日", "birthday", 0)); ems2.add(new ExcelMapping("身份证号码", "idcNo", 0)); ems2.add(new ExcelMapping("护照号码", "passNo", 0)); ems2.add(new ExcelMapping("护照有效期至", "passEndTime", 0)); ems2.add(new ExcelMapping("其他证件类型", "otherIdcName", 0)); ems2.add(new ExcelMapping("其他证件号", "otherIdcNo", 0)); ems2.add(new ExcelMapping("其他证件有效期", "otherIdcEnd", 0)); ems2.add(new ExcelMapping("所属部门", "departName", 0)); ems2.add(new ExcelMapping("职务", "job", 0)); ems2.add(new ExcelMapping("会员卡号", "vipNo", 0)); ems2.add(new ExcelMapping("联系电话", "contactPhone", 0)); ems2.add(new ExcelMapping("手机", "mobile", 0)); ems2.add(new ExcelMapping("email", "email", 0)); ems2.add(new ExcelMapping("国籍", "nationality", 0)); ems2.add(new ExcelMapping("居住地", "address", 0)); ems2.add(new ExcelMapping("邮编", "postCode", 0)); ems2.add(new ExcelMapping("备注", "remark", 0)); .... map.put(1, ems2); try { book=createExcelFile (UserModel.class, users, map); } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | IntrospectionException | ParseException e) { e.printStackTrace(); } return book; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
7. springMVC excel导出
@RequestMapping(value = "/export/auto", method = RequestMethod.GET) @ResponseBody public JsonResult exportUserByAuto(HttpServletRequest request, HttpServletResponse response,@ModelAttribute UserModel model) throws CommonException { response.reset() SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms") String dateStr = sdf.format(new Date()) // 指定下载的文件名 response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xls") response.setContentType("application/vnd.ms-excel;charset=UTF-8") response.setHeader("Pragma", "no-cache") response.setHeader("Cache-Control", "no-cache") response.setDateHeader("Expires", 0) XSSFWorkbook workbook=exportWorkBook(model) try { OutputStream output = response.getOutputStream() BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output) bufferedOutPut.flush() workbook.write(bufferedOutPut) bufferedOutPut.close() } catch (IOException e) { e.printStackTrace() } return ResultRender.renderResult("导出成功") }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
8. springMVC 导入excel
@RequestMapping(value = "/upload",method=RequestMethod.POST) @ResponseBody public JsonResult uploadUsers(HttpServletRequest request, @RequestParam MultipartFile file) throws CommonException{ try { MultipartRequest multipartRequest=(MultipartRequest) request; MultipartFile excelFile=multipartRequest.getFile("file"); if(excelFile!=null){ List<UserModel> models=userService.insertUserByExcel(excelFile); if(models!=null && models.size()>0){ return ResultRender.renderResult("名单导入成功", models); }else{ return ResultRender.renderResult("名单导入失败", models); } }else{ return ResultRender.renderResult("上传失败"); } } catch (Exception e) { throw new Exception("上传文件出错"); } }