Apache POI 学习笔记
1 介绍
Apache POI 是一个功能强大的开源库,专门用于处理 Microsoft Office 各种文件格式。通过 POI,我们可以在 Java 程序中轻松实现对 Office 文件(特别是 Excel)的读写操作。
主要应用场景:
- 银行网银系统导出交易明细
- 各种业务系统生成 Excel 报表
- 批量导入业务数据到系统中
2 入门案例
Apache POI 不仅可以将数据写入 Excel 文件,还可以读取 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>
2.1 将数据写入 Excel 文件
1). 代码实现
public class POITest {
/**
* 基于POI向Excel文件写入数据
* @throws Exception
*/
public static void write() throws Exception{
//在内存中创建一个Excel文件对象
XSSFWorkbook excel = new XSSFWorkbook();
//创建Sheet页
XSSFSheet sheet = excel.createSheet("itcast");
//在Sheet页中创建行,0表示第1行
XSSFRow row1 = sheet.createRow(0);
//创建单元格并在单元格中设置值,单元格编号也是从0开始,1表示第2个单元格
row1.createCell(1).setCellValue("姓名");
row1.createCell(2).setCellValue("城市");
XSSFRow row2 = sheet.createRow(1);
row2.createCell(1).setCellValue("张三");
row2.createCell(2).setCellValue("北京");
XSSFRow row3 = sheet.createRow(2);
row3.createCell(1).setCellValue("李四");
row3.createCell(2).setCellValue("上海");
FileOutputStream out = new FileOutputStream(new File("D:\\name.xlsx"));
//通过输出流将内存中的Excel文件写入到磁盘上
excel.write(out);
//关闭资源
out.flush();
out.close();
excel.close();
}
public static void main(String[] args) throws Exception {
write();
}
}
2). 实现效果
执行上述代码后,会在 D 盘生成一个名为 name.xlsx
的 Excel 文件,其中包含一个名为 “itcast” 的 Sheet 页,并成功写入了我们设置的内容。
2.2 读取 Excel 文件中的数据
1). 代码实现
public class POITest {
/**
* 基于POI读取Excel文件
* @throws Exception
*/
public static void read() throws Exception{
FileInputStream in = new FileInputStream(new File("D:\\name.xlsx"));
//通过输入流读取指定的Excel文件
XSSFWorkbook excel = new XSSFWorkbook(in);
//获取Excel文件的第1个Sheet页
XSSFSheet sheet = excel.getSheetAt(0);
//获取Sheet页中的最后一行的行号
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
//获取Sheet页中的行
XSSFRow titleRow = sheet.getRow(i);
//获取行的第2个单元格
XSSFCell cell1 = titleRow.getCell(1);
//获取单元格中的文本内容
String cellValue1 = cell1.getStringCellValue();
//获取行的第3个单元格
XSSFCell cell2 = titleRow.getCell(2);
//获取单元格中的文本内容
String cellValue2 = cell2.getStringCellValue();
System.out.println(cellValue1 + " " +cellValue2);
}
//关闭资源
in.close();
excel.close();
}
public static void main(String[] args) throws Exception {
read();
}
}
2). 实现效果
执行上述代码后,程序会读取 name.xlsx
文件中的数据,并在控制台输出每行的内容。输出结果将包含我们之前写入的"姓名"、“城市"以及"张三”、“北京”、“李四”、"上海"等数据。
通过这两个简单的例子,我们可以看到 Apache POI 提供了一种简单而强大的方式来操作 Excel 文件,无论是写入数据还是读取数据都非常方便。