java如何更新excel
更新Excel文件的方法
在Java中更新Excel文件通常使用Apache POI库,它支持读写Microsoft Office格式文件。以下是几种常见操作:
添加依赖
Maven项目中需添加以下依赖:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
修改单元格内容
FileInputStream file = new FileInputStream("existing.xlsx");
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
// 修改第一行第一列的值
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
cell.setCellValue("新值");
FileOutputStream out = new FileOutputStream("updated.xlsx");
workbook.write(out);
workbook.close();
添加新行
Sheet sheet = workbook.getSheetAt(0);
Row newRow = sheet.createRow(sheet.getLastRowNum() + 1);
newRow.createCell(0).setCellValue("A列数据");
newRow.createCell(1).setCellValue("B列数据");
使用模板更新
InputStream is = new FileInputStream("template.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(is);
XSSFSheet sheet = workbook.getSheetAt(0);
// 填充模板占位符
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getStringCellValue().equals("${placeholder}")) {
cell.setCellValue("实际值");
}
}
}
批量更新数据
Map<String, String> data = new HashMap<>();
data.put("A1", "值1");
data.put("B2", "值2");
for (Entry<String, String> entry : data.entrySet()) {
CellReference ref = new CellReference(entry.getKey());
Row row = sheet.getRow(ref.getRow());
Cell cell = row.getCell(ref.getCol());
cell.setCellValue(entry.getValue());
}
注意事项
- 处理大文件时考虑使用SXSSFWorkbook以优化内存
- 操作完成后必须关闭Workbook和流对象
- 对xls和xlsx格式需要使用不同的实现类(HSSF/XSSF)
- 异常处理应包含IOException和InvalidFormatException
以上方法涵盖了从简单修改到批量更新的常见场景,可根据实际需求选择合适的方式。






