要更改Apache POI中单元格的值,可以使用以下代码示例:
import org.apache.poi.ss.usermodel.*;
public class ChangeCellValueExample {
public static void main(String[] args) throws Exception {
// 加载Excel文件
Workbook workbook = WorkbookFactory.create(new File("path/to/excel.xlsx"));
// 获取工作表
Sheet sheet = workbook.getSheetAt(0);
// 获取要更改的单元格
Cell cell = sheet.getRow(0).getCell(0);
// 设置单元格的值
cell.setCellValue("New Value");
// 保存更改后的Excel文件
FileOutputStream fileOut = new FileOutputStream("path/to/excel.xlsx");
workbook.write(fileOut);
fileOut.close();
// 关闭工作簿
workbook.close();
}
}
请确保将path/to/excel.xlsx
替换为实际的Excel文件路径。这个示例将Excel文件的第一个工作表的第一个单元格的值更改为"New Value",然后保存更改后的Excel文件。
注意:在使用此代码示例之前,确保已添加Apache POI的相关依赖项到项目中。