Apache POI-操作Excel表格
1. 需求
大多数项目的在运营过程中,会产生运营数据,如外卖系统中需要统计每日的订单完成数、每种菜品的销量等数据,这些都是商家关心的事情,如果可以将这些数据整理成Excel表格,可以让商家更直观地了解到这些数据。
Apache POI这个开源项目就可以用于处理微软各式各样的文件,如读、写、创建文件等,这里主要介绍的是如何处理Excel文件。
2. 优点
- 开源免费:不需要侧重关心数据安全等方面的问题。
- 跨平台:Apache POI是使用Java语法编写的,在任何支持Java语言的平台下面都可以使用。
- 容易集成:在springboot项目中使用起来非常方便。
3. 缺点
- 操作繁琐:Apache POI中丰富的api,增加了使用的难度
- 性能:处理大型Excel文件的时候,会大量占用内存
- 不支持新功能:无法及时同步Excel这个软件更新的功能
4. 应用场景
5. 使用方法
Apache POI中提供的api处理Excel表格的大多数逻辑都和直接使用Excel(微软)这个软件类似。
最后,直接在模板文件中填充从数据库中处理好的数据即可。
6. SpringBoot工程中处理Excel表格
-
导入Maven坐标
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
-
获取输入流(获取Excel文件)
-
获取Sheet页(可设置Sheet的名称)
-
获取行(可直接获取最后一行有内容的行号, 最后一行的行号从0开始的)
-
获取列(可直接获取最后一列有内容的行号,最后一行的列号从1开始的)
-
对Excel文件进行读写操作
-
获取输出流(将Excel文件保存到磁盘上或者输出到浏览器上面)
7. Demo示例
@Test
public void writeExcel() throws IOException {
XSSFWorkbook excel = new XSSFWorkbook();
XSSFSheet sheet = excel.createSheet("user");
XSSFRow row0 = sheet.createRow(0);
XSSFRow row1 = sheet.createRow(1);
XSSFRow row2 = sheet.createRow(2);
row0.createCell(0).setCellValue("name");
row0.createCell(1).setCellValue("age");
row1.createCell(0).setCellValue("aimin");
row1.createCell(1).setCellValue("22");
row2.createCell(0).setCellValue("Tony");
row2.createCell(1).setCellValue("22");
FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\WORKSPACE-Java\\normal-project\\Apache_POI_test\\files\\info.xlsx"));
excel.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
excel.close();
}
@Test
public void readExcel() throws Exception{
XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File("D:\\WORKSPACE-Java\\normal-project\\Apache_POI_test\\files\\info.xlsx")));
XSSFSheet sheet = excel.getSheet("user");
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
XSSFRow row = sheet.getRow(i);
short lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
System.out.print(row.getCell(j) + " ");
}
System.out.println();
}
excel.close();
}