1. 添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
如果zhi 只添加poi会报错,需要再添加poi-ooml
2. POI对Excel的支持需要根据不同的Excel版本使用不同的包
org.apache.poi.hssf:2003(xls后缀)
org.apache.poi.xssf.:2007+(xlsx后缀)
其中多数方法命名也类似,下面的总结都使用的是“xssf”
(1) 读文件:
File fi=new File(resExcelPath);
InputStream in = new FileInputStream(fi);
XSSFWorkbook wb = new XSSFWorkbook(in);
//读取所有内容
XSSFSheet sheet = wb.getSheetAt(0);
//保存原有公式
sheet.setForceFormulaRecalculation(true);
(2) 写文件
//写入已有单元格
sheet.getRow(1).getCell(2).setCellValue(*****);
//创建单元格
//行和列都不存在时
cell = sheet.createRow(row).createCell(col);
//行存在,列不存在时
cell = sheet.getRow(row).createCell(col);
//合并单元格
sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
如果行已存在,再用createRow(row).createCell(col)就会把原有的内容删除
(3) 设置格式
CellStyle style = wb.createCellStyle();
//对齐方式
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setAlignment(HorizontalAlignment.LEFT);
//边框
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
cell.setCellStyle(style);
(4)保存
//保存到新的路径下
FileOutputStream out = new FileOutputStream(desExcelPath);
wb.write(out);
out.close();