是的,Apache POI 4.0.x 支持 Java 11。以下是一个代码示例,演示如何使用 Apache POI 4.0.x 来读取和写入 Excel 文件。
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ApachePOIExample {
public static void main(String[] args) {
String filePath = "path_to_excel_file.xlsx";
try {
// 读取 Excel 文件
FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
// 读取单元格数据
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println("Cell Value: " + cell.getStringCellValue());
// 写入 Excel 文件
FileOutputStream fos = new FileOutputStream(filePath);
cell.setCellValue("Hello, World!");
workbook.write(fos);
// 关闭文件流
fos.close();
fis.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我们使用 Apache POI 4.0.x 的 XSSFWorkbook 类来创建一个新的 Excel 工作簿,并使用 getSheetAt() 方法获取第一个工作表。然后,我们读取第一个单元格的值,并在写入之前将其更改为 "Hello, World!"。最后,我们将更改后的工作簿写回到 Excel 文件中。
请注意,你需要将 path_to_excel_file.xlsx
替换为实际的 Excel 文件路径。