SpringBoot 2x 操作 Excel 导入导出

介绍

在本教程中,学习如何使用Apache POIJExcel APIs来处理Excel电子表格。

这两个库都可用于动态读取,写入和修改Excel电子表格的内容,并提供将Microsoft Excel集成到Java应用程序中的有效方法。

快速创建实例

前往 start.spring.io/ 如下所示

初始化项目
点击GENERATE生产一个zip解压导入IDEA工具即可

Maven 依赖

首先,我们需要切换国内依赖下载源,在pom.xml文件中<build></build>后添加

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
xml复制代码<repositories>
<!--阿里云主仓库,代理了maven central和jcenter仓库-->
<repository>
<id>aliyun</id>
<name>aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<!--阿里云代理Spring 官方仓库-->
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://maven.aliyun.com/repository/spring</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<!--阿里云代理Spring 插件仓库-->
<pluginRepository>
<id>spring-plugin</id>
<name>spring-plugin</name>
<url>https://maven.aliyun.com/repository/spring-plugin</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

然后将以下依赖项添加到我们的pom.xml文件中:

1
2
3
4
5
6
7
8
9
10
11
xml复制代码<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>

Apache POI

Apache POI 库同时支持.xls.xlsx文件,并且在处理Excel文件比其他Java库更为优秀。

它提供了用于为Excel文件建模的Workbook界面,以及为Excel文件的元素建模的工作表,行和单元格界面,以及两种文件格式的每个界面的实现。

使用较新的.xlsx文件格式时,应使用XSSFWorkbookXSSFSheetXSSFRow和XSSFCell类。

要使用旧的.xls格式,请使用HSSFWorkbookHSSFSheetHSSFRow和HSSFCell类。

读取 Excel

让我们创建一个方法来打开一个.xlsx文件,然后从该文件的第一张表中读取内容。

因为单元格中数据的类型不同,读取单元格内容的方法可以自己定义。

可以使用Cell接口的getCellTypeEnum()方法确定单元格内容的类型。

首先,让我们获取文件的后缀来判断用HSSFWorkbook还是XSSFWorkbook进行处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
java复制代码String[] postfixArray = path.split("\\.");
int lastIndex = postfixArray.length - 1;
String postfix = postfixArray[lastIndex];
Workbook wb;
switch (postfix) {
case ExcelUtil.MICROSOFT_EXCEL_2003:
wb = new HSSFWorkbook(fileInput);
break;
case ExcelUtil.MICROSOFT_EXCEL_2007:
wb = new XSSFWorkbook(fileInput);
break;
default:
throw new Exception("文件不符合要求");
}

开始读取Excel文件

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
java复制代码    public static List<List<String>> readExcel(String path) throws Exception {
File excelFile = new File(path);
if (!excelFile.exists()) {
throw new FileNotFoundException("文件不存在");
}
FileInputStream fileInput = new FileInputStream(excelFile);
/*
根据文件后缀判断用xls或是xlsx处理
*/
String[] postfixArray = path.split("\\.");
int lastIndex = postfixArray.length - 1;
String postfix = postfixArray[lastIndex];

Workbook wb;
switch (postfix) {
case ExcelUtil.MICROSOFT_EXCEL_2003:
wb = new HSSFWorkbook(fileInput);
break;
case ExcelUtil.MICROSOFT_EXCEL_2007:
wb = new XSSFWorkbook(fileInput);
break;
default:
throw new Exception("文件不符合要求");
}
List<List<String>> dataList = new ArrayList<>();
/*
* wb.getSheetAt(0) 简单的取第一个sheet的表格读取
*/
for (Row row : wb.getSheetAt(0)) {
List<String> rowList = new ArrayList<>();
for (Cell cell : row) {
rowList.add(getCellValue(cell));
}
dataList.add(rowList);
}
return dataList;
}

获取单元格的getCellValue()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
java复制代码public static String getCellValue(Cell cell) {
switch (cell.getCellType()) {
case BOOLEAN:
return ......;
case STRING:
return ......;
case NUMERIC:
return ......;
case FORMULA:
return ......;
default:
return "";
}
}

当单元格类型的枚举值为STRING时,将使用Cell接口的getStringCellValue()方法读取内容

1
java复制代码return cell.StringCellValue()

具有NUMERIC内容类型的单元格可以包含日期或数字,可以通过以下方式进行读取:

1
2
3
4
5
6
java复制代码if (DateUtil.isCellDateFormatted(cell)) {
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
return timeFormatter.format(cell.getLocalDateTimeCellValue());
} else {
return cell.getNumericCellValue() + "";
}

对于BOOLEAN值,我们有getBooleanCellValue()方法:

1
java复制代码return String.valueOf(cell.getBooleanCellValue());

当单元格类型为FORMULA时,我们可以使用getCellFormula()方法:

1
java复制代码return cell.getCellFormula() + "";

执行测试结果:

image.png

导出 Excel

Apache POI使用上一节中介绍的相同接口来写入 Excel 文件。

让我们创建一个方法,把之前导入的数据进行导出到新的 Excel 文件:

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
java复制代码public static void exportExcel(List<List<String>> dataList) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("sheetNameTest");

Row header = sheet.createRow(0);

CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.INDIGO.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

XSSFFont font = workbook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 16);
font.setColor(IndexedColors.WHITE.getIndex());
headerStyle.setFont(font);
headerStyle.setBorderBottom(BorderStyle.THIN); //下边框
headerStyle.setBorderLeft(BorderStyle.THIN);//左边框
headerStyle.setBorderTop(BorderStyle.THIN);//上边框
headerStyle.setBorderRight(BorderStyle.THIN);//右边框

// 取标题
List<String> headerList = dataList.get(0);
for (int i = 0; i < headerList.size(); i++) {
sheet.setColumnWidth(i, headerList.get(i).length()*512);
Cell headerCell = header.createCell(i);
headerCell.setCellStyle(headerStyle);
headerCell.setCellValue(headerList.get(i));
}

CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
style.setBorderBottom(BorderStyle.THIN); //下边框
style.setBorderLeft(BorderStyle.THIN);//左边框
style.setBorderTop(BorderStyle.THIN);//上边框
style.setBorderRight(BorderStyle.THIN);//右边框

for (int i = 1; i < dataList.size(); i++) {
Row row = sheet.createRow(i);
List<String> rowList = dataList.get(i);
for (int j = 0; j < rowList.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(rowList.get(j));
cell.setCellStyle(style);
}
}
File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "test_emp.xlsx";

System.out.println(fileLocation);
FileOutputStream outputStream = new FileOutputStream(fileLocation);
workbook.write(outputStream);
workbook.close();

}

测试

1
2
3
4
5
6
7
8
9
10
java复制代码@SpringBootTest
class SpringbootExcelApplicationTests {

@Test
void contextLoads() throws Exception {
List<List<String>> dataList = ExcelUtil.readExcel("employees.xlsx");
ExcelUtil.exportExcel(dataList);
}

}

输出文档截图

image.png

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%