以下代码演示如何使用数据创建新的XLSX文件,将其写入磁盘以及从文件中读取数据.它是使用Java 9和
Apache POI 3.17构建的.
该示例使用包含String,LocalDate和Int的简单Person类来生成测试数据.
在我们将测试数据写入之后,这是使用LibreOffice查看的创建的XLSX文件:
在编写文件之后,我们重新读取其内容并创建Person对象:
Could not parse row 0 to person
Person from file: Khaled, born 1988-03-26, pets: 1
Person from file: Hans, born 1998-09-20, pets: 2
Person from file: Alena, born 1977-01-12, pets: 0
第一行中出现警告,因为我们无法将标题行Name of Birth Nr of Pets转换为Person对象.
这是代码:
/**
* Writes person data to an XLSX file and reads it back out.
*
* Created by Matthias Braun on 2018-07-10.
*/
public class ReadWriteTests {
public static void main(String... args) {
List people = List.of(
new Person("Khaled", LocalDate.of(1988, 3, 26), 1),
new Person("Hans", LocalDate.of(1998, 9, 20), 2),
new Person("Alena", LocalDate.of(1977, 1, 12), 0)
);
String xlsxFileName = System.getenv("HOME") + "/people.xlsx";
writeToXlsxFile(people, xlsxFileName);
List peopleFromFile = readFromXlsxFile(xlsxFileName);
peopleFromFile.forEach(person ->
System.out.println("Person from file: " + person));
}
private static List readFromXlsxFile(String xlsx