使用Java导入、导出excel详解(附有封装好的工具类)

- 日理万妓 2024-04-23 12:58 56阅读 0赞
  • ? :是江迪呀
  • ✒️本文关键词JavaExcel导出工具类后端
  • ☀️每日 一言:有些事情不是对的才去坚持,而是坚持了它才是对的!

文章目录

  • 前言
  • 一、引入`Apache POI`依赖
  • 二、用法`&`步骤
    • 2.1 创建`Excel`的元素
      • (1)创建`WokrBook`
      • (2)创建`Sheet`
      • (3)创建行`Row`
      • (4)创建单元格`Cell`
      • (5) 填充数据
    • 2.3 样式和字体
      • (1)左右垂直居中
      • (2)字体加粗、颜色
      • (3)调整列宽和高
      • (4)倾斜、下划线
    • 2.4 进阶用法
      • (1)合并单元格
      • (2)字段必填
      • (3)添加公式
      • (4)下拉选择
      • (5)设置单元格的数据类型
  • 三、导出完整示例
    • (1)代码
    • (2)工具类
    • (2)结果
  • 四、导入完整示例
    • (1)代码
    • (2)工具类
    • (3)结果

前言

我们在日常开发中,一定遇到过要将数据导出为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

  1. Workbook workbook = new XSSFWorkbook();

(2)创建Sheet

  1. Sheet sheet = workbook.createSheet();

设置sheet的名称

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

(3)创建行Row

  1. Row row = sheet.createRow(0);

(4)创建单元格Cell

  1. 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) 填充数据

  1. cell.setCellValue("苹果");

2.3 样式和字体

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

  1. 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单元格使用该样式:

  1. cell.setCellStyle(style);

(3)调整列宽和高

  1. Sheet sheet = workbook.createSheet();
  2. //自动调整列的宽度来适应内容
  3. sheet.autoSizeColumn(int column);
  4. // 设置列的宽度
  5. sheet.setColumnWidth(2, 20 * 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(0, 0, 0, 5));
  • CellRangeAddress()方法四个参数分别是fristRow:起始行、lastRow:结束行、fristCol:起始列、lastCol:结束列。
    如果你想合并从第一行到第二行从一列到第十列的单元格(一共合并20格),那么就是CellRangeAddress(0,1,0,10)

(2)字段必填

  1. //创建数据验证
  2. DataValidationHelper dvHelper = sheet.getDataValidationHelper();
  3. //创建要添加校验的单元格对象
  4. CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 10);
  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:求和函数

    //创建SUM公式
    FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    Cell sumCell = row.createCell(0);
    sumCell.setCellFormula(“SUM(A1:A10)”);
    //计算SUM公式结果
    Cell sumResultCell = row.createCell(1);
    sumResultCell.setCellValue(evaluator.evaluate(sumCell).getNumberValue());

  • AVERAGE:平均数函数

    //创建AVERAGE公式
    FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    Cell averageCell = row.createCell(0);
    averageCell.setCellFormula(“AVERAGE(A1:A10)”);

    //计算AVERAGE公式结果
    Cell averageResultCell = row.createCell(1);
    averageResultCell.setCellValue(evaluator.evaluate(averageCell).getNumberValue());

  • COUNT:计数函数

    //创建COUNT公式
    FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    Cell countCell = row.createCell(0);
    countCell.setCellFormula(“COUNT(A1:A10)”);

    //计算COUNT公式结果
    Cell countResultCell = row.createCell(1);
    countResultCell.setCellValue(evaluator.evaluate(countCell).getNumberValue());

  • IF:条件函数

    //创建IF公式
    FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    Cell ifCell = row.createCell(0);
    ifCell.setCellFormula(“IF(A1>B1,\”Yes\”,\”No\”)”);

    //计算IF公式结果
    Cell ifResultCell = row.createCell(1);
    ifResultCell.setCellValue(evaluator.evaluate(ifCell).getStringValue());

  • CONCATENATE:连接函数

    //创建CONCATENATE公式
    FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    Cell concatenateCell = row.createCell(0);
    concatenateCell.setCellFormula(“CONCATENATE(A1,\” \”,B1)”);

    //计算CONCATENATE公式结果
    Cell concatenateResultCell = row.createCell(1);
    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)设置单元格的数据类型

  • 数字格式

    // 设置单元格样式 - 数字格式
    CellStyle numberCellStyle = workbook.createCellStyle();
    numberCellStyle.setDataFormat(workbook.createDataFormat().getFormat(“#,##0.00”));
    //指定单元格
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellStyle(numberCellStyle);

  • 日期格式

    // 设置单元格样式 - 日期格式
    CellStyle dateCellStyle = workbook.createCellStyle();
    dateCellStyle.setDataFormat(workbook.createDataFormat().getFormat(“yyyy-MM-dd”));
    //指定单元格
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    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. }

(2)结果

在这里插入图片描述

四、导入完整示例

(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)结果

学生信息集合:
在这里插入图片描述

发表评论

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

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

相关阅读