当前位置:   article > 正文

Java导入、导出excel保姆级教程(附封装好的工具类)

java导入excel

前言

我们在日常开发中,一定遇到过要将数据导出为Excel的需求,那么怎么做呢?在做之前,我们需要思考下Excel的组成。Excel是由四个元素组成的分别是:WorkBook(工作簿)、Sheet(工作表)、Row(行)、Cell(单元格),其中包含关系是从左至右,一个WorkBook可以包含多个Sheet,一个Sheet又是由多个Row组成,一个Row是由多个Cell组成。知道这些后那么我们就使用java来将数据以Excel的方式导出。让我们一起来学习吧!

一、引入Apache POI依赖

使用Java实现将数据以Excel的方式导出,需要依赖第三方的库。我们需要再pom.xml中引入下面的依赖:

  1. <dependency>
  2.      <groupId>org.apache.poi</groupId>
  3.      <artifactId>poi</artifactId>
  4.      <version>4.1.2</version>
  5.  </dependency>
  6.  <dependency>
  7.      <groupId>org.apache.poi</groupId>
  8.      <artifactId>poi-ooxml</artifactId>
  9.      <version>4.1.2</version>
  10.  </dependency>

二、用法&步骤

2.1 创建Excel的元素

1)创建WokrBook

Workbook workbook = new XSSFWorkbook();

2)创建Sheet

Sheet sheet = workbook.createSheet();

设置sheet的名称

Sheet sheet = workbook.createSheet("sheet名称");

3)创建行Row

Row row = sheet.createRow(0);

4)创建单元格Cell

Cell cell = row.createCell(0, CellType.STRING);

可以指定单元格的类型,支持的类型有下面7种:

  1. _NONE(-1),
  2. NUMERIC(0),
  3. STRING(1),
  4. //公式
  5. FORMULA(2),
  6. BLANK(3),
  7. //布尔
  8. BOOLEAN(4),
  9. ERROR(5);

5) 填充数据

cell.setCellValue("苹果");

2.3 样式和字体

如果我们需要导出的Excel美观一些,如设置字体的样式加粗、颜色、大小等等,就需要创建样式和字体。

创建样式:

CellStyle cellStyle = workbook.createCellStyle();

1)左右垂直居中

  1. //左右居中
  2. excelTitleStyle.setAlignment(HorizontalAlignment.CENTER);
  3. // 设置垂直居中
  4. excelTitleStyle.setVerticalAlignment(VerticalAlignment.CENTER);

2)字体加粗、颜色

创建加粗样式并设置到CellStyle 中:

  1. Font font = workbook.createFont();
  2. //字体颜色为红色
  3. font.setColor(IndexedColors.RED.getIndex());
  4. //字体加粗
  5. font.setBold(true);
  6. cellStyle.setFont(font);

指定Cell单元格使用该样式:

cell.setCellStyle(style);

3)调整列宽和高

  1. Sheet sheet = workbook.createSheet();
  2. //自动调整列的宽度来适应内容
  3. sheet.autoSizeColumn(int column); 
  4. // 设置列的宽度
  5. sheet.setColumnWidth(220 * 256);

autoSizeColumn()传递的参数就是要设置的列索引。setColumnWidth()第一个参数是要设置的列索引,第二参数是具体的宽度值,宽度 = 字符个数 * 256(例如20个字符的宽度就是20 * 256

4)倾斜、下划线

  1. Font font = workbook.createFont();
  2. font.setItalic(boolean italic); 设置倾斜
  3. font.setUnderline(byte underline); 设置下划线

2.4 进阶用法

1)合并单元格

  1. Workbook workbook = new XSSFWorkbook();
  2. Sheet sheet = workbook.createSheet(fileName);
  3. sheet.addMergedRegion(new CellRangeAddress(0005));

CellRangeAddress()方法四个参数分别是fristRow:起始行、lastRow:结束行、fristCol:起始列、lastCol:结束列。

如果你想合并从第一行到第二行从一列到第十列的单元格(一共合并20格),那么就是CellRangeAddress(0,1,0,10)

2)字段必填

  1. //创建数据验证
  2. DataValidationHelper dvHelper = sheet.getDataValidationHelper();
  3. //创建要添加校验的单元格对象
  4. CellRangeAddressList addressList = new CellRangeAddressList(00010);
  5. //创建必填校验规则
  6. DataValidationConstraint constraint = validationHelper.createCustomConstraint("NOT(ISBLANK(A1))");
  7. //设置校验
  8. DataValidation validation = dvHelper.createValidation(constraint, addressList);
  9. //校验不通过 提示
  10. validation.setShowErrorBox(true);
  11. sheet.addValidationData(validation);

CellRangeAddressList()方法传递四个参数,分别是:fristRow:起始行、lastRow:结束行、fristCol:起始列、lastCol:结束列。CellRangeAddressList(0, 0, 0, 10)表示的就是给第一行从第一列开始到第十列一共十个单元格添加数据校验。

3)添加公式

SUM:求和函数

  1. //创建SUM公式
  2. FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  3. Cell sumCell = row.createCell(0);
  4. sumCell.setCellFormula("SUM(A1:A10)");
  5. //计算SUM公式结果
  6. Cell sumResultCell = row.createCell(1);
  7. sumResultCell.setCellValue(evaluator.evaluate(sumCell).getNumberValue());

AVERAGE:平均数函数

  1. //创建AVERAGE公式
  2. FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  3. Cell averageCell = row.createCell(0);
  4. averageCell.setCellFormula("AVERAGE(A1:A10)");
  5. //计算AVERAGE公式结果
  6. Cell averageResultCell = row.createCell(1);
  7. averageResultCell.setCellValue(evaluator.evaluate(averageCell).getNumberValue());

COUNT:计数函数

  1. //创建COUNT公式
  2. FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  3. Cell countCell = row.createCell(0);
  4. countCell.setCellFormula("COUNT(A1:A10)");
  5. //计算COUNT公式结果
  6. Cell countResultCell = row.createCell(1);
  7. countResultCell.setCellValue(evaluator.evaluate(countCell).getNumberValue());

IF:条件函数

  1. //创建IF公式
  2. FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  3. Cell ifCell = row.createCell(0);
  4. ifCell.setCellFormula("IF(A1>B1,\"Yes\",\"No\")");
  5. //计算IF公式结果
  6. Cell ifResultCell = row.createCell(1);
  7. ifResultCell.setCellValue(evaluator.evaluate(ifCell).getStringValue());

CONCATENATE:连接函数

  1. //创建CONCATENATE公式
  2. FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  3. Cell concatenateCell = row.createCell(0);
  4. concatenateCell.setCellFormula("CONCATENATE(A1,\" \",B1)");
  5. //计算CONCATENATE公式结果
  6. Cell concatenateResultCell = row.createCell(1);
  7. concatenateResultCell.setCellValue(evaluator.evaluate(concatenateCell).getStringValue());

4)下拉选择

  1. //下拉值
  2. private List<String> grade = Arrays.asList("高""中""低");
  3. (此处省略n行代码)
  4. Sheet sheet = workbook.createSheet("sheet");
  5. DataValidation dataValidation = this.addPullDownConstraint(i, sheet, grade );
  6. sheet.addValidationData(dataValidation);

5)设置单元格的数据类型

数字格式

  1. // 设置单元格样式 - 数字格式
  2. CellStyle numberCellStyle = workbook.createCellStyle();
  3. numberCellStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00"));
  4. //指定单元格
  5. Row row = sheet.createRow(0);
  6. Cell cell = row.createCell(0);
  7. cell.setCellStyle(numberCellStyle);

日期格式

  1. // 设置单元格样式 - 日期格式
  2. CellStyle dateCellStyle = workbook.createCellStyle();
  3. dateCellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd"));
  4. //指定单元格
  5. Row row = sheet.createRow(0);
  6. Cell cell = row.createCell(0);
  7. cell.setCellStyle(dateCellStyle);

三、导出完整示例

下面的示例使用SpringBoot项目来演示:

pom.xml依赖:

  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-web</artifactId>
  4.     <version>2.7.5</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>org.springframework.boot</groupId>
  8.     <artifactId>spring-boot-starter</artifactId>
  9.     <version>2.7.5</version>
  10. </dependency>
  11. <dependency>
  12.     <groupId>org.apache.poi</groupId>
  13.     <artifactId>poi</artifactId>
  14.     <version>4.1.2</version>
  15. </dependency>
  16. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
  17. <dependency>
  18.     <groupId>org.apache.poi</groupId>
  19.     <artifactId>poi-ooxml</artifactId>
  20.     <version>4.1.2</version>
  21. </dependency>
  22. <dependency>
  23.     <groupId>org.projectlombok</groupId>
  24.     <artifactId>lombok</artifactId>
  25.     <version>1.16.16</version>
  26. </dependency>
  27. <!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
  28. <dependency>
  29.     <groupId>com.alibaba</groupId>
  30.     <artifactId>fastjson</artifactId>
  31.     <version>2.0.21</version>
  32. </dependency>
  33. <dependency>
  34.     <groupId>org.apache.commons</groupId>
  35.     <artifactId>commons-lang3</artifactId>
  36.     <version>3.12.0</version>
  37. </dependency>

Controller层代码:

  1. package shijiangdiya.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.web.bind.annotation.PostMapping;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import shijiangdiya.utils.ExportUtils;
  7. import javax.servlet.http.HttpServletResponse;
  8. @RestController
  9. @RequestMapping("/sync")
  10. public class ExportController {
  11. }

1)代码

  1. @Autowired
  2. private HttpServletResponse response;
  3. @PostMapping("/export")
  4. public void export() {
  5.  //模拟json数据
  6.     String data = "[{\n" +
  7.             "    \"studentId\": \"20210101\",\n" +
  8.             "    \"name\": \"Alice\",\n" +
  9.             "    \"age\": 20,\n" +
  10.             "    \"credit\": 80\n" +
  11.             "  },\n" +
  12.             "  {\n" +
  13.             "    \"studentId\": \"20210102\",\n" +
  14.             "    \"name\": \"Bob\",\n" +
  15.             "    \"age\": 21,\n" +
  16.             "    \"credit\": 85\n" +
  17.             "  },\n" +
  18.             "  {\n" +
  19.             "    \"studentId\": \"20210103\",\n" +
  20.             "    \"name\": \"Charlie\",\n" +
  21.             "    \"age\": 22,\n" +
  22.             "    \"credit\": 90\n" +
  23.             "  },\n" +
  24.             "  {\n" +
  25.             "    \"studentId\": \"20210104\",\n" +
  26.             "    \"name\": \"David\",\n" +
  27.             "    \"age\": 20,\n" +
  28.             "    \"credit\": 75\n" +
  29.             "  },\n" +
  30.             "  {\n" +
  31.             "    \"studentId\": \"20210105\",\n" +
  32.             "    \"name\": \"Emily\",\n" +
  33.             "    \"age\": 21,\n" +
  34.             "    \"credit\": 82\n" +
  35.             "  },\n" +
  36.             "  {\n" +
  37.             "    \"studentId\": \"20210106\",\n" +
  38.             "    \"name\": \"Frank\",\n" +
  39.             "    \"age\": 22,\n" +
  40.             "    \"credit\": 88\n" +
  41.             "  },\n" +
  42.             "  {\n" +
  43.             "    \"studentId\": \"20210107\",\n" +
  44.             "    \"name\": \"Grace\",\n" +
  45.             "    \"age\": 20,\n" +
  46.             "    \"credit\": 81\n" +
  47.             "  },\n" +
  48.             "  {\n" +
  49.             "    \"studentId\": \"20210108\",\n" +
  50.             "    \"name\": \"Henry\",\n" +
  51.             "    \"age\": 21,\n" +
  52.             "    \"credit\": 89\n" +
  53.             "  },\n" +
  54.             "  {\n" +
  55.             "    \"studentId\": \"20210109\",\n" +
  56.             "    \"name\": \"Isaac\",\n" +
  57.             "    \"age\": 22,\n" +
  58.             "    \"credit\": 92\n" +
  59.             "  },\n" +
  60.             "  {\n" +
  61.             "    \"studentId\": \"20210110\",\n" +
  62.             "    \"name\": \"John\",\n" +
  63.             "    \"age\": 20,\n" +
  64.             "    \"credit\": 78\n" +
  65.             "  },\n" +
  66.             "  {\n" +
  67.             "    \"studentId\": \"20210111\",\n" +
  68.             "    \"name\": \"Kelly\",\n" +
  69.             "    \"age\": 21,\n" +
  70.             "    \"credit\": 84\n" +
  71.             "  },\n" +
  72.             "  {\n" +
  73.             "    \"studentId\": \"20210112\",\n" +
  74.             "    \"name\": \"Linda\",\n" +
  75.             "    \"age\": 22,\n" +
  76.             "    \"credit\": 87\n" +
  77.             "  },\n" +
  78.             "  {\n" +
  79.             "    \"studentId\": \"20210113\",\n" +
  80.             "    \"name\": \"Mike\",\n" +
  81.             "    \"age\": 20,\n" +
  82.             "    \"credit\": 77\n" +
  83.             "  },\n" +
  84.             "  {\n" +
  85.             "    \"studentId\": \"20210114\",\n" +
  86.             "    \"name\": \"Nancy\",\n" +
  87.             "    \"age\": 21,\n" +
  88.             "    \"credit\": 83\n" +
  89.             "  },\n" +
  90.             "  {\n" +
  91.             "    \"studentId\": \"20210115\",\n" +
  92.             "    \"name\": \"Oscar\",\n" +
  93.             "    \"age\": 22,\n" +
  94.             "    \"credit\": 91\n" +
  95.             "  },\n" +
  96.             "  {\n" +
  97.             "    \"studentId\": \"20210116\",\n" +
  98.             "    \"name\": \"Paul\",\n" +
  99.             "    \"age\": 20,\n" +
  100.             "    \"credit\": 76\n" +
  101.             "  },\n" +
  102.             "  {\n" +
  103.             "    \"studentId\": \"20210117\",\n" +
  104.             "    \"name\": \"Queen\",\n" +
  105.             "    \"age\": 21,\n" +
  106.             "    \"credit\": 86\n" +
  107.             "  },\n" +
  108.             "  {\n" +
  109.             "    \"studentId\": \"20210118\",\n" +
  110.             "    \"name\": \"Rachel\",\n" +
  111.             "    \"age\": 22,\n" +
  112.             "    \"credit\": 94\n" +
  113.             "  },\n" +
  114.             "  {\n" +
  115.             "    \"studentId\": \"20210119\",\n" +
  116.             "    \"name\": \"Sarah\",\n" +
  117.             "    \"age\": 20,\n" +
  118.             "    \"credit\": 79\n" +
  119.             "  },\n" +
  120.             "  {\n" +
  121.             "    \"studentId\": \"20210120\",\n" +
  122.             "    \"name\": \"Tom\",\n" +
  123.             "    \"age\": 21,\n" +
  124.             "    \"credit\": 80\n" +
  125.             "  }\n" +
  126.             "]\n";
  127.     ExportUtils.exportExcel("学生信息", data, Student.class, response);
  128. }

2)工具类

  1. /**
  2.  * 数据导出
  3.  * @param fileName 导出excel名称
  4.  * @param data 导出的数据
  5.  * @param c 导出数据的实体class
  6.  * @param response 响应
  7.  * @throws Exception
  8.  */
  9. public static void exportExcel(String fileName, String data, Class<?> c, HttpServletResponse response) throws Exception {
  10.     try {
  11.         // 创建表头
  12.         // 创建工作薄
  13.         Workbook workbook = new XSSFWorkbook();
  14.         Sheet sheet = workbook.createSheet();
  15.         // 创建表头行
  16.         Row rowHeader = sheet.createRow(0);
  17.         if (c == null) {
  18.             throw new RuntimeException("Class对象不能为空!");
  19.         }
  20.         Field[] declaredFields = c.getDeclaredFields();
  21.         List<String> headerList = new ArrayList<>();
  22.         if (declaredFields.length == 0) {
  23.             return;
  24.         }
  25.         for (int i = 0; i < declaredFields.length; i++) {
  26.             Cell cell = rowHeader.createCell(i, CellType.STRING);
  27.             String headerName = String.valueOf(declaredFields[i].getName());
  28.             cell.setCellValue(headerName);
  29.             headerList.add(i, headerName);
  30.         }
  31.         // 填充数据
  32.         List<?> objects = JSONObject.parseArray(data, c);
  33.         Object obj = c.newInstance();
  34.         if (!CollectionUtils.isEmpty(objects)) {
  35.             for (int o = 0; o < objects.size(); o++) {
  36.                 Row rowData = sheet.createRow(o + 1);
  37.                 for (int i = 0; i < headerList.size(); i++) {
  38.                     Cell cell = rowData.createCell(i);
  39.                     Field nameField = c.getDeclaredField(headerList.get(i));
  40.                     nameField.setAccessible(true);
  41.                     String value = String.valueOf(nameField.get(objects.get(o)));
  42.                     cell.setCellValue(value);
  43.                 }
  44.             }
  45.         }
  46.         response.setContentType("application/vnd.ms-excel");
  47.         String resultFileName = URLEncoder.encode(fileName, "UTF-8");
  48.         response.setHeader("Content-disposition""attachment;filename=" + resultFileName + ";" + "filename*=utf-8''" + resultFileName);
  49.         workbook.write(response.getOutputStream());
  50.         workbook.close();
  51.         response.flushBuffer();
  52.     } catch (Exception e) {
  53.         throw new RuntimeException(e);
  54.     }
  55. }

3)结果

f5b4317d5830a9f19798e4c4e778cd7d.png

四、导入完整示例

1)代码

  1. @PostMapping("/import")
  2. public void importExcel(@RequestParam("excel") MultipartFile excel){
  3.     Workbook workbook = null;
  4.     try {
  5.         workbook = WorkbookFactory.create(excel.getInputStream());
  6.         Sheet sheet = workbook.getSheetAt(0);
  7.         List<Student> students = new ArrayList<>();
  8.         int i = 0;
  9.         for (Row row : sheet) {
  10.             Row row1 = sheet.getRow(i + 1);
  11.             if(row1 != null){
  12.                 Student data = new Student();
  13.                 data.setStudentId(Integer.parseInt(row1.getCell(0).getStringCellValue()));
  14.                 data.setName(row1.getCell(1).getStringCellValue());
  15.                 data.setAge(Integer.parseInt(row1.getCell(2).getStringCellValue()));
  16.                 data.setCredit(Integer.parseInt(row1.getCell(3).getStringCellValue()));
  17.                 students.add(data);
  18.             }
  19.         }
  20.         System.out.println(students);
  21.         workbook.close();
  22.     } catch (IOException e) {
  23.         throw new RuntimeException(e);
  24.     }

2)工具类

  1. /**
  2.      * 导入
  3.      * @param workbook 工作簿
  4.      * @param c 实体类
  5.      * @return 实体类集合
  6.      */
  7.     public static <T> List<T> importExcel(Workbook workbook,Class<?> c){
  8.         List<T> dataList = new ArrayList<>();
  9.         try {
  10.             Sheet sheet = workbook.getSheetAt(0);
  11.             int i = 0;
  12.             T o = null;
  13.             for (Row row : sheet) {
  14.                 Row row1 = sheet.getRow(i + 1);
  15.                 if(row1 != null){
  16.                     o = (T) c.newInstance();
  17.                     Field[] declaredFields = c.getDeclaredFields();
  18.                     for (int i1 = 0; i1 < declaredFields.length; i1++) {
  19.                         String name = declaredFields[i1].getName();
  20.                         Field declaredField1 = o.getClass().getDeclaredField(name);
  21.                         declaredField1.setAccessible(true);
  22.                         Cell cell = row1.getCell(i1);
  23.                         String type = declaredFields[i1].getType().getName();
  24.                         String value = String.valueOf(cell);
  25.                         if(StringUtils.equals(type,"int") || StringUtils.equals(type,"Integer")){
  26.                             declaredField1.set(o,Integer.parseInt(value));
  27.                         } else if(StringUtils.equals(type,"java.lang.String") || StringUtils.equals(type,"char") || StringUtils.equals(type,"Character") ||
  28.                                 StringUtils.equals(type,"byte") || StringUtils.equals(type,"Byte")){
  29.                             declaredField1.set(o,value);
  30.                         } else if(StringUtils.equals(type,"boolean") || StringUtils.equals(type,"Boolean")){
  31.                             declaredField1.set(o,Boolean.valueOf(value));
  32.                         } else if(StringUtils.equals(type,"double") || StringUtils.equals(type,"Double")){
  33.                             declaredField1.set(o,Double.valueOf(value));
  34.                         } else if (StringUtils.equals(type,"long") || StringUtils.equals(type,"Long")) {
  35.                             declaredField1.set(o,Long.valueOf(value));
  36.                         } else if(StringUtils.equals(type,"short") || StringUtils.equals(type,"Short")){
  37.                             declaredField1.set(o,Short.valueOf(value));
  38.                         } else if(StringUtils.equals(type,"float") || StringUtils.equals(type,"Float")){
  39.                             declaredField1.set(o,Float.valueOf(value));
  40.                         }
  41.                     }
  42.                 }
  43.                 dataList.add(o);
  44.             }
  45.             workbook.close();
  46.             return dataList;
  47.         }catch (Exception e){
  48.             e.printStackTrace();
  49.         }
  50.         return dataList;
  51.     }

注意:导入工具类仅限Java的八大基础数据类型和String类型。如果还有其他类型需要自己扩展。

3)结果

学生信息集合:

16dedaeebd6858cbe2d332c16705bf86.png

来源|blog.csdn.net/qq_42785250/article/details/129654178

  1. 后端专属技术群
  2. 构建高质量的技术交流社群,欢迎从事编程开发、技术招聘HR进群,也欢迎大家分享自己公司的内推信息,相互帮助,一起进步!
  3. 文明发言,以交流技术、职位内推、行业探讨为主
  4. 广告人士勿入,切勿轻信私聊,防止被骗
  5. 加我好友,拉你进群
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/272953
推荐阅读
相关标签
  

闽ICP备14008679号