基于SpringBoot简单演示了ApachePOI对Excel的写入与读取
ApachePOI简介
简介
Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目
简单来说就是,可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作
应用场景:银行网银系统导出交易明细、各种业务系统导出Excel报表、批量导入业务数据等
入门案例
首先要导入Apache POI的Maven坐标
1
2
3
4
5
6
7
8
9
10
|
<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>
|
写入
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
|
package com.yuanyu.test;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
/**
* 使用POI实现Excel文件读取和写入
*/
public class POITest {
/**
* 通过POI创建Excel文件并写入数据
*/
public static void write() throws Exception {
// 在内存中创建Excel文件
XSSFWorkbook excel = new XSSFWorkbook();
// 在Excel文件中创建一个工作簿
XSSFSheet sheet = excel.createSheet("POI测试");
// 在sheet中第一行创建行对象(rownum编号从0开始)
XSSFRow row = sheet.createRow(0);
// 在行对象中创建单元格对象并设置单元格内容
row.createCell(0).setCellValue("编号");
row.createCell(1).setCellValue("姓名");
// 在第二行创建一个新的行对象并设置单元格内容
row = sheet.createRow(1);
row.createCell(0).setCellValue("1");
row.createCell(1).setCellValue("张三");
// 通过输出流将Excel文件写入磁盘
FileOutputStream out = new FileOutputStream("G:\\!Temp\\ApachePOI测试\\POI测试.xlsx");
excel.write(out);
// 关闭输出流
out.close();
// 关闭Excel文件
excel.close();
}
public static void main(String[] args) throws Exception {
write();
}
}
|
读取
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
|
package com.yuanyu.test;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
/**
* 使用POI实现Excel文件读取和写入
*/
public class POITest {
/**
* 通过POI读取Excel文件
*/
public static void read() throws Exception {
// 创建输入流,通过输入流读取Excel文件
FileInputStream in = new FileInputStream(new File("G:\\!Temp\\ApachePOI测试\\POI测试.xlsx"));
// 读取磁盘中的Excel文件
XSSFWorkbook excel = new XSSFWorkbook(in);
// 获取Excel文件中的第一个工作簿
XSSFSheet sheet = excel.getSheetAt(0);
// 获取工作簿中的最后一行的行号
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
// 获取第i行
XSSFRow row = sheet.getRow(i);
// 获取该行第一个单元格内容
String cellValue1 = row.getCell(0).getStringCellValue();
// 获取该行第二个单元格内容
String cellValue2 = row.getCell(1).getStringCellValue();
// 输出单元格内容
System.out.println(cellValue1 + " " + cellValue2);
}
// 关闭输入流
in.close();
// 关闭Excel文件
excel.close();
}
public static void main(String[] args) throws Exception {
read();
}
}
|