Java引入POI
1. POI简介
POI(Poor Obfuscation Implementation)是开源项目,提供了Java操作Microsoft Office格式文件(如Word、Excel、PowerPoint)的API。POI提供了读写、创建和修改Office文档的功能,对于需要处理Office文件的Java开发者来说非常有用。
2. 使用POI读取Excel文件
在使用POI读取Excel文件之前,首先需要添加POI的依赖项。可以通过Maven或手动下载POI的JAR文件,然后将其添加到项目中。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
下面是一个使用POI读取Excel文件的例子:
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) {
try {
File file = new File("example.xlsx");
FileInputStream fis = new FileInputStream(file);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
CellType cellType = cell.getCellType();
if (cellType == CellType.STRING) {
System.out.print(cell.getStringCellValue() + "\t");
} else if (cellType == CellType.NUMERIC) {
System.out.print(cell.getNumericCellValue() + "\t");
}
}
System.out.println();
}
workbook.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码通过WorkbookFactory.create(fis)
方法创建一个Workbook
对象,然后通过getSheetAt(0)
方法获取第一个工作表,遍历每一行和每一个单元格,分别获取其值。最后关闭资源。
3. 使用POI写入Excel文件
除了读取Excel文件,POI还提供了写入Excel文件的功能。下面是一个使用POI写入Excel文件的例子:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelWriter {
public static void main(String[] args) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello, World!");
try {
FileOutputStream fos = new FileOutputStream("example.xlsx");
workbook.write(fos);
workbook.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码创建了一个工作簿、工作表、行和单元格,然后将值设置为"Hello, World!"。最后通过workbook.write(fos)
将工作簿写入到文件中。
4. 序列图
下面是使用POI读取Excel文件的序列图:
sequenceDiagram
participant Client
participant ExcelReader
participant POI
Client->>+ExcelReader: 调用main方法
ExcelReader->>+POI: 创建文件输入流
POI->>-ExcelReader: 返回文件输入流
ExcelReader->>+POI: 创建工作簿
POI->>-ExcelReader: 返回工作簿
ExcelReader->>+POI: 获取工作表
POI->>-ExcelReader: 返回工作表
ExcelReader->>+POI: 遍历行和单元格
POI->>-ExcelReader: 返回行和单元格的值
ExcelReader->>+POI: 关闭资源
POI->>-ExcelReader: 关闭资源
结论
通过POI,我们可以方便地读取和写入Excel文件,为Java开发者处理Office文件提供了便利。POI提供了丰富的API,可以满足大部分Excel文件处理的需求。希望本文对你理解和使用POI有所帮助。