文章框架
一、Apache POI 概述
定义:Java API操作Microsoft Office格式文件
核心功能:
读写Excel(.xls, .xlsx)
操作Word、PowerPoint等文档
优势:开源免费、跨平台、功能全面
二、环境准备
Maven依赖配置:
<!-- poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> </dependency>
三、案例代码
1.Excel写入实战(代码解析)
public static void POITestWrite()throws Exception{
//在内存中创建Excel文件
XSSFWorkbook excel=new XSSFWorkbook();
//在Excel文件创建一个sheet页
XSSFSheet sheet=excel.createSheet("sheet1");
//在sheet对象页中创建行 从0开始为第一行
XSSFRow row1 = sheet.createRow(0);
//在行上创建单元格,并写入单元格内容 单元格也是从0开始 所以1是第二个单元格
row1.createCell(1).setCellValue("姓名");
row1.createCell(2).setCellValue("城市");
//创建第二行
XSSFRow row2 = sheet.createRow(1);
row2.createCell(1).setCellValue("张三");
row2.createCell(2).setCellValue("北京");
//创建第三行
XSSFRow row3 = sheet.createRow(2);
row3.createCell(1).setCellValue("李四");
row3.createCell(2).setCellValue("湖北");
//创建输出流
FileOutputStream out = new FileOutputStream(new File("D:\\sheet1.xlsx"));
//写入数据
excel.write(out);
//关闭输出流文件和excel文件
excel.close();
out.close();
}
关键点说明:
createRow()
/createCell()
创建行列单元格索引从0开始(A列=0, B列=1)
2.Excel读取实战(代码解析)
public static void POITaskRead() throws Exception{
FileInputStream in = new FileInputStream(new File("D:\\sheet1.xlsx"));
//读取磁盘上的excel文件
XSSFWorkbook excel = new XSSFWorkbook(in);
//读取excel中第一个sheet页
XSSFSheet sheet = excel.getSheetAt(0);
//获取sheet中创建最后一行的行号
int lastRowNum = sheet.getLastRowNum();
//遍历行
for (int i=0;i<=lastRowNum;i++){
//获取对应行
XSSFRow row = sheet.getRow(i);
if(row!=null){
//获取单元格内容
String cellValue1 = row.getCell(1).getStringCellValue();
String cellValue2 = row.getCell(2).getStringCellValue();
System.out.println(cellValue1+" "+cellValue2);
}
}
//关闭输入流
in.close();
//关闭excel
excel.close();
}
关键点说明:
getLastRowNum()
获取最后一行索引单元格类型处理:
getStringCellValue()
/getNumericCellValue()
空值处理建议:添加
if (row != null)
判断
三、应用场景
报表导出
数据批量导入
自动化测试数据生成
财务数据分析
四、总结
Apache POI是Java操作Excel的首选方案
提供从基础读写到高级功能的完整API
注意资源管理和异常处理确保稳定性