Apache POI简介

Apache POI是一个用Java编写的跨平台的免费开源的Java API。它提供了一组API,使Java程序能够读取和写入Microsoft Office格式档案。其中读写Excel文件的功能应用最为广泛。除此之外,还有一个专门操作Excel的工具包jxl。

导入maven依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>

POI的结构

  • HSSF:提供读写Microsoft Excel XLS格式档案的功能(97-2003)
  • XSSF:提供读写Microsoft Excel OOXML XLSX格式档案的功能(2007及以上版本)
  • HWPF:提供读写Microsoft Word DOC格式档案的功能
  • HSLF:提供读写Microsoft PowerPoint格式档案的功能
  • HDGF:提供读Microsoft Visio格式档案的功能(建模/画图)
  • HPBF:提供读Microsoft Publisher格式档案的功能
  • HSMF:提供读Microsoft Outlook格式档案的功能(邮件)

读取Excel文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void readExcel() throws Exception {
// 1、创建工作簿对象
XSSFWorkbook workbook = new XSSFWorkbook("G:/hello.xlsx");
// 2、获得工作表对象
XSSFSheet sheet = workbook.getSheetAt(0);
// 3、遍历工作表,获得行对象
for (Row row : sheet) {
// 4、遍历行对象,获得列对象
for (Cell cell : row) {
// 5、获得列里面的内容
System.out.println(cell.getStringCellValue());
}
System.out.println("------------");
}
// 6、关闭工作簿
workbook.close();
}

写入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
public void writeExcel() throws Exception {
// 1、创建工作簿对象
XSSFWorkbook workbook = new XSSFWorkbook();
// 2、创建工作表对象
XSSFSheet xssfSheet = workbook.createSheet("学生名单");
// 3、创建行
XSSFRow row01 = xssfSheet.createRow(0);
// 4、创建列并设置内容
row01.createCell(0).setCellValue("姓名");
row01.createCell(1).setCellValue("性别");
row01.createCell(2).setCellValue("地址");

XSSFRow row02 = xssfSheet.createRow(1);
row02.createCell(0).setCellValue("张三");
row02.createCell(1).setCellValue("男");
row02.createCell(2).setCellValue("深圳");

XSSFRow row03 = xssfSheet.createRow(2);
row03.createCell(0).setCellValue("李四");
row03.createCell(1).setCellValue("男");
row03.createCell(2).setCellValue("北京");

// 5、通过输出流写入磁盘
FileOutputStream os = new FileOutputStream("G:/student.xlsx");
workbook.write(os);
os.flush();
os.close();

// 6、关闭工作簿
workbook.close();
}