poi导入导出excel

迷南。 2022-06-05 06:25 479阅读 0赞

1.引入poi jar

要良好支持XSSF的话,下载poi 3.1以上的哦!

  • maven:


    org.apache.poi
    poi
    3.14-beta1
  • jar:poi 3.14-beta1下载

2. excel对应映射model

  1. public class ExcelMapping {
  2. private String headTextName;//列头(标题)名
  3. private String propertyName;//对应字段名
  4. private Integer cols;//合并单元格数
  5. private XSSFCellStyle cellStyle;//单元格样式
  6. public ExcelMapping() {
  7. }
  8. public ExcelMapping(String headTextName, String propertyName) {
  9. this.headTextName = headTextName;
  10. this.propertyName = propertyName;
  11. }
  12. public ExcelMapping(String headTextName, String propertyName, Integer cols) {
  13. super();
  14. this.headTextName = headTextName;
  15. this.propertyName = propertyName;
  16. this.cols = cols;
  17. }
  18. ....//get、set方法
  19. }

3. poi 生成 excel

  1. /** * 多列头创建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 */
  2. public static XSSFWorkbook createExcelFile(Class clazz, List objs,Map<Integer, List<ExcelMapping>> map,String sheetName) throws IllegalArgumentException,IllegalAccessException,
  3. InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException{
  4. // 创建新的Excel 工作簿
  5. XSSFWorkbook workbook = new XSSFWorkbook();
  6. // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
  7. XSSFSheet sheet = workbook.createSheet(sheetName);
  8. // 以下为excel的字体样式以及excel的标题与内容的创建,下面会具体分析;
  9. createFont(workbook);//字体样式
  10. createTableHeader(sheet, map);//创建标题(头)
  11. createTableRows(sheet, map, objs, clazz);//创建内容
  12. return workbook;
  13. }

4.样式createFont

  1. public static void createFont(XSSFWorkbook workbook) {
  2. // 表头
  3. XSSFCellStyle fontStyle = workbook.createCellStyle();
  4. XSSFFont font1 = workbook.createFont();
  5. font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
  6. font1.setFontName("黑体");
  7. font1.setFontHeightInPoints((short) 14);// 设置字体大小
  8. fontStyle.setFont(font1);
  9. fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
  10. fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框
  11. fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框
  12. fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框
  13. fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
  14. // 内容
  15. XSSFCellStyle fontStyle2 =workbook.createCellStyle();
  16. XSSFFont font2 = workbook.createFont();
  17. font2.setFontName("宋体");
  18. font2.setFontHeightInPoints((short) 10);// 设置字体大小
  19. fontStyle2.setFont(font2); fontStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
  20. fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框
  21. fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框
  22. fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框
  23. fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
  24. }

4.多行列头的生成以及单元格的合并 createTableHeader(sheet, map)

  1. /** * 根据ExcelMapping 生成列头(多行列头) * * @param sheet * 工作簿 * @param map * 每行每个单元格对应的列头信息 */
  2. public static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelMapping>> map) {
  3. int startIndex=0;//cell起始位置
  4. int endIndex=0;//cell终止位置
  5. for (Map.Entry<Integer, List<ExcelMapping>> entry : map.entrySet()) {
  6. XSSFRow row = sheet.createRow(entry.getKey());
  7. List<ExcelMapping> excels = entry.getValue();
  8. for (int x = 0; x < excels.size(); x++) {
  9. //合并单元格
  10. if(excels.get(x).getCols()>1){
  11. if(x==0){ endIndex+=excels.get(x).getCols()-1;
  12. CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
  13. sheet.addMergedRegion(range);
  14. startIndex+=excels.get(x).getCols();
  15. }else{
  16. endIndex+=excels.get(x).getCols();
  17. CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
  18. sheet.addMergedRegion(range);
  19. startIndex+=excels.get(x).getCols();
  20. }
  21. XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());
  22. cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
  23. if (excels.get(x).getCellStyle() != null) {
  24. cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
  25. }
  26. cell.setCellStyle(fontStyle);
  27. }else{
  28. XSSFCell cell = row.createCell(x);
  29. cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
  30. if (excels.get(x).getCellStyle() != null) {
  31. cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
  32. }
  33. cell.setCellStyle(fontStyle);
  34. }
  35. }
  36. }
  37. }

5. 创建excel内容文本 createTableRows(sheet, map, objs, clazz)

PropertyDescriptor获取get、set详解

  1. /** * * @param sheet * @param map * @param objs * @param clazz */
  2. @SuppressWarnings("rawtypes")
  3. public static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelMapping>> map, List objs, Class clazz)
  4. throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException,
  5. ClassNotFoundException, ParseException {
  6. // Class clazz = Class.forName(classBeanURL);
  7. int rowindex = map.size();
  8. int maxKey = 0;
  9. List<ExcelMapping> ems = new ArrayList<>();
  10. for (Map.Entry<Integer, List<ExcelMapping>> entry : map.entrySet()) {
  11. if (entry.getKey() > maxKey) {
  12. maxKey = entry.getKey();
  13. }
  14. }
  15. ems = map.get(maxKey);
  16. List<Integer> widths = new ArrayList<Integer>(ems.size());
  17. for (Object obj : objs) {
  18. XSSFRow row = sheet.createRow(rowindex);
  19. for (int i = 0; i < ems.size(); i++) {
  20. ExcelMapping em = (ExcelMapping) ems.get(i);
  21. // 获得get方法
  22. PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
  23. Method getMethod = pd.getReadMethod();
  24. Object rtn = getMethod.invoke(obj);
  25. String value = "";
  26. // 如果是日期类型 进行 转换
  27. if (rtn != null) {
  28. if (rtn instanceof Date) {
  29. value = DateUtils.formatFullDate((Date) rtn);
  30. } else {
  31. value = rtn.toString();
  32. }
  33. }
  34. XSSFCell cell = row.createCell(i);
  35. if (null != fontStyle2) {
  36. cell.setCellStyle(fontStyle2);
  37. }
  38. cell.setCellValue(value);
  39. cell.setCellType(XSSFCell.CELL_TYPE_STRING);
  40. cell.setCellStyle(FontStyle4);
  41. // 获得最大列宽
  42. int width = value.getBytes().length * 300;
  43. // 还未设置,设置当前
  44. if (widths.size() <= i) {
  45. widths.add(width);
  46. continue;
  47. }
  48. // 比原来大,更新数据
  49. if (width > widths.get(i)) {
  50. widths.set(i, width);
  51. }
  52. }
  53. rowindex++;
  54. }
  55. // 设置列宽
  56. for (int index = 0; index < widths.size(); index++) {
  57. Integer width = widths.get(index);
  58. width = width < 2500 ? 2500 : width + 300;
  59. width = width > 10000 ? 10000 + 300 : width + 300;
  60. sheet.setColumnWidth(index, width);
  61. }
  62. }

6.生成对应model数据源的excel

  1. public XSSFWorkbook exportWorkBook(UserModel model) throws CommonException {
  2. List<UserModel> users = userService.selectByExample(model);//数据源
  3. if (users == null || users.size()==0) {
  4. throw new Exception("暂无导出数据");
  5. }
  6. Map<String, List<UserModel>> resultMap = userModel.getResultMap();//多列标题头情况
  7. List<ExcelMapping> ems = new ArrayList<>();
  8. Map<Integer, List<ExcelMapping>> map = new LinkedHashMap<>();
  9. XSSFWorkbook book = null;
  10. // 添加列头信息
  11. ems.add(new ExcelMapping("人员基本信息", "basicInformation", 3));
  12. ems.add(new ExcelMapping("证件信息", "idcInformation", 6));
  13. ems.add(new ExcelMapping("其他信息", "otherInformation", 10));
  14. ems.add(new ExcelMapping("公司信息", "bigCsrInformation", 5));
  15. map.put(0, ems);
  16. // 添加第二列头信息
  17. List<ExcelMapping> ems2 = new ArrayList<>();
  18. ems2.add(new ExcelMapping("员工姓名", "userName", 0));
  19. ems2.add(new ExcelMapping("员工姓名(英/拼音)", "userNameEn", 0));
  20. ems2.add(new ExcelMapping("生日", "birthday", 0));
  21. ems2.add(new ExcelMapping("身份证号码", "idcNo", 0));
  22. ems2.add(new ExcelMapping("护照号码", "passNo", 0));
  23. ems2.add(new ExcelMapping("护照有效期至", "passEndTime", 0));
  24. ems2.add(new ExcelMapping("其他证件类型", "otherIdcName", 0));
  25. ems2.add(new ExcelMapping("其他证件号", "otherIdcNo", 0));
  26. ems2.add(new ExcelMapping("其他证件有效期", "otherIdcEnd", 0));
  27. ems2.add(new ExcelMapping("所属部门", "departName", 0));
  28. ems2.add(new ExcelMapping("职务", "job", 0));
  29. ems2.add(new ExcelMapping("会员卡号", "vipNo", 0));
  30. ems2.add(new ExcelMapping("联系电话", "contactPhone", 0));
  31. ems2.add(new ExcelMapping("手机", "mobile", 0));
  32. ems2.add(new ExcelMapping("email", "email", 0));
  33. ems2.add(new ExcelMapping("国籍", "nationality", 0));
  34. ems2.add(new ExcelMapping("居住地", "address", 0));
  35. ems2.add(new ExcelMapping("邮编", "postCode", 0));
  36. ems2.add(new ExcelMapping("备注", "remark", 0));
  37. ....
  38. map.put(1, ems2);
  39. try {
  40. book=createExcelFile
  41. (UserModel.class, users, map);
  42. } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | ClassNotFoundException
  43. | IntrospectionException | ParseException e) {
  44. e.printStackTrace();
  45. }
  46. return book;
  47. }

7. springMVC excel导出

  1. @RequestMapping(value = "/export/auto", method = RequestMethod.GET)
  2. @ResponseBody
  3. public JsonResult exportUserByAuto(HttpServletRequest request,
  4. HttpServletResponse response,@ModelAttribute UserModel model)
  5. throws CommonException {
  6. response.reset();
  7. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
  8. String dateStr = sdf.format(new Date());
  9. // 指定下载的文件名
  10. response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xls");
  11. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  12. response.setHeader("Pragma", "no-cache");
  13. response.setHeader("Cache-Control", "no-cache");
  14. response.setDateHeader("Expires", 0);
  15. XSSFWorkbook workbook=exportWorkBook(model);
  16. try {
  17. OutputStream output = response.getOutputStream();
  18. BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
  19. bufferedOutPut.flush();
  20. workbook.write(bufferedOutPut);
  21. bufferedOutPut.close();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. return ResultRender.renderResult("导出成功");
  26. }

8. springMVC 导入excel

  1. @RequestMapping(value = "/upload",method=RequestMethod.POST)
  2. @ResponseBody
  3. public JsonResult uploadUsers(HttpServletRequest request,
  4. @RequestParam MultipartFile file) throws CommonException{
  5. //手工导入
  6. try {
  7. MultipartRequest multipartRequest=(MultipartRequest) request;
  8. MultipartFile excelFile=multipartRequest.getFile("file");
  9. if(excelFile!=null){
  10. List<UserModel> models=userService.insertUserByExcel(excelFile);
  11. if(models!=null && models.size()>0){
  12. return ResultRender.renderResult("名单导入成功", models);
  13. }else{
  14. return ResultRender.renderResult("名单导入失败", models);
  15. }
  16. }else{
  17. return ResultRender.renderResult("上传失败");
  18. }
  19. } catch (Exception e) {
  20. throw new Exception("上传文件出错");
  21. }
  22. }

发表评论

表情:
评论列表 (有 0 条评论,479人围观)

还没有评论,来说两句吧...

相关阅读