Apache POI 操作 Excel 表格
这里简单记录下使用 POI 向 Excel 中写入 和 从Excel 中读取内容的过程,方便后续回忆。
public class TestPoi {
private static void write() throws Exception{
// 在内存中创建一个 Excel 文件
XSSFWorkbook excel = new XSSFWorkbook();
// 在 Excel 文件中创建一个 Sheet 页
XSSFSheet sheet = excel.createSheet("info");
// 在 Sheet 中创建行对象, 编号从0开始
XSSFRow row = sheet.createRow(1);
// 创建单元格并且写入文件内容
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue("年龄");
// 创建一个新行
row = sheet.createRow(2);
row.createCell(1).setCellValue("冯明凯");
row.createCell(2).setCellValue("28");
FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\test.xls"));
excel.write(fileOutputStream);
fileOutputStream.close();
excel.close();
}
private static void read() throws Exception{
FileInputStream fileInputStream = new FileInputStream(new File("D:\\test.xls"));
// 读取磁盘上已经存在的 Excel 文件
XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
// 读取 Excel 文件中的第一个 Sheet 页
XSSFSheet sheet = excel.getSheetAt(0);
// 读取 Sheet 中最后一行的行号(行号从0开始计算)
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
// 获取某一行
XSSFRow row = sheet.getRow(i);
// 获取单元格对象
String name = row.getCell(1).getStringCellValue();
String age = row.getCell(2).getStringCellValue();
System.out.println("name = " + name + " age = " + age);
}
// 关闭资源
fileInputStream.close();
excel.close();
}
public static void main(String[] args) throws Exception {
write();
read();
}
}