使用Java更新excel

问题描述 投票:1回答:2

我正在尝试更新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();
    }

}
java
2个回答
1
投票

行和列均以'i'键,因此您将沿对角线遍历图纸。

但是当然也请其他人推荐,这些都是很好的建议。

[通常,在处理二维信息块时,我发现对行使用一个循环,然后在其中对列进行嵌套(反之亦然)则很有用

例如

for (y = startRow; y <= maxRow; y++) {

  ....

  for (x = startCol; x <= maxCol; x++) {


     .... // do something to each column in the current row

     cell = sheet1.getRow(y).getCell(x);

     .....

1
投票

我认为将Cell引用移入for循环应该可以为您解决。

[cell cell = null;

另外,如果在else块中遇到NullPointerException,您可能还需要移到if块之外

单元格= sheet1.getRow(i + 1).getCell(i + 2)

这样的事情...

for (int i = 0; i < TCID.size(); i++) {
            HSSFSheet sheet1 = workSheet.getSheetAt(0);
            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);                 
                workSheet.write(output_file);
            }else {
                cell.setCellValue(NO);
                workSheet.write(output_file);
            }
       }
© www.soinside.com 2019 - 2024. All rights reserved.