java - 使用 Java 更新 excel
问题描述
我正在尝试更新 excel 工作表中的一列,但只有第一行正在更新。第二次迭代不起作用。有人可以帮我吗?下面是我正在尝试的代码。
String excelPath = "path";
String YES = "Updated YES";
String NO = "Updated NO";
try {
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
Cell cell = null;
FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
HSSFSheet sheet1 = workSheet.getSheetAt(0);
String data = sheet1.getRow(i+1).getCell(i).toString();
if(data.equals(TCID.get(i))){
cell = sheet1.getRow(i+1).getCell(i+2);
cell.setCellValue(YES);
workSheet.write(output_file);
}else {
cell.setCellValue(NO);
workSheet.write(output_file);
}
}
fis.close();
output_file.close();
workSheet.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我的最新代码如下。现在它正在更新列,但最后一行没有更新。我错过了什么。
FileInputStream fis=new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
HSSFSheet sheet1 = workSheet.getSheetAt(0);
//FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
}
fis.close();
//output_file.close();
//workSheet.close();
FileOutputStream output_file =new FileOutputStream(excelPath);
workSheet.write(output_file);
output_file.close();
解决方案
好的,所以有几件事。
HSSFSheet sheet1 = workSheet.getSheetAt(0);
在循环之外声明。您在 for 循环的每次迭代中都使用同一张表,因此只需调用一次。- 您获取单元格数据 (
String data = sheet1.getRow(i+1).getCell(i).toString();
) 的逻辑不会返回相同的列。在您的第一次迭代中,您将获得 (R)ow 1 : (C)olumn 0。下一次迭代将返回 R2 : C1,然后是 R2:C2,然后是 R3:C3,等等。注意您正在对角线的模式在列下,而不是垂直。 - 行从 0 开始。
- 您只需要在
workSheet.write(output_file);
完成所有处理后进行。 - 如果该行不存在,您将获得一个
NullPointerException
- 当您每次迭代都使用一个唯一的Cell时,您只需在循环中声明它(因此不需要在
Cell cell = null;
循环之外)。
这是一个例子:
try {
FileInputStream fis = new FileInputStream(excelPath);
Workbook workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (int i = 0; i < 5; i++) {
Row row = sheet.getRow(i);
if (row != null) {
Cell cell = row.getCell(0);
cell.setCellValue("Updated cell.");
}
}
FileOutputStream output_file = new FileOutputStream(excelPath);
workbook.write(output_file);
output_file.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
推荐阅读
- css - Boostrap 4:使 textarea 匹配列高
- node.js - 无法使用“google-admin-sdk”查看管理员用户目录
- java - 如何使用 iText 保存 .pdf 文件?
- node.js - 我们如何在 koa 应用模型中使用 aws x-ray 跟踪 axios http 请求
- junit - 运行 JUnit 时记录配置错误
- c# - Unity Fix NavMeshAgent 自动旋转 90 度
- python - 计算 numpy 数组之间的 MSE
- flutter - 如何删除文本字段的标签?
- vue.js - 离开页面时,我得到:未处理的 GraphQL 订阅错误错误:GraphQL 错误:未提供所需类型 xxx 的变量 xx
- android - 谷歌通过条纹支付