簡體   English   中英

使用 apache POI 在 excel 文件中寫入單元格時出現問題

[英]Issue while writing cells in excel file using apache POI

我在將數據寫入 excel 文件時遇到問題。 我正在使用 apache POI 4.1.2 版本庫。 下面是示例代碼。

    try {
        outputStream = new FileOutputStream(EXCEL_FILE_PATH);
    } catch (Exception e) {
        System.out.println("Exception While writing excel file " + e.getMessage());
    }

    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet("FileCompare");

    Row row = sheet.createRow(0);

    Cell cellfilename = row.createCell(0);
    cellfilename.setCellValue("File Name");

    Cell cellfilename1 = row.createCell(1);
    cellfilename1.setCellValue("Difference in File 1");

    Cell cellfilenam2 = row.createCell(2);
    cellfilenam2.setCellValue("Difference in File 2");

    for (int diffcol = 1; diffcol < 3; diffcol++) {
        for (int i = 1; i < 57; i++) {

            Row rows = sheet.createRow(i);
            // System.out.println("Difference Coln number " + diffcol);
            Cell diffcell = rows.createCell(diffcol);
            diffcell.setCellValue("abacds");

            /*
             * Cell diffcell2 = row.createCell(2); diffcell2.setCellValue("abacds");
             */

        }
        
    }


    try {
        workbook.write(outputStream);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        outputStream.flush();
        outputStream.close();
        workbook.close();
    }

在這最后一列單元格被保存在 excel 文件中,以前的單元格保留為空白。 請幫助並讓我知道我是否做錯了什么?

請找到附加的片段以獲取更多參考

不確定實際的 api 但我認為你的內部循環應該創建列,而你的外部循環應該創建這樣的行

  for (int row=1:row<57;row++)
  {
     Row rows = sheet.createRow(row);
     for (int diffCol = 1; diffCol < 3; difCol++) 
     {
        Cell diffcell = rows.createCell(diffcol);
        diffcell.setCellValue("abacds");
     }
  }

問題是在你的循環中你總是使用sheet.createRow(i)來檢索你需要的行,但是正如文檔所說(實際上寫得不太清楚的文檔)這種方法總是重新創建一個全新的 &空行,刪除現有行(如果該 i 位置的行已經存在)。

這意味着 yuor 循環的每次迭代實際上都是在刪除以前的行來創建全新的行:最后只有最后一次迭代創建的行才能幸存!

要解決您的問題,請僅使用sheet.createRow(i)一次以在 i 位置創建行,然后僅使用sheet.getRow(i)檢索它。

所以替換(在您的代碼中)以下錯誤

Row rows = sheet.createRow(i);

使用以下代碼

Row row = sheet.getRow(i);
if (row == null) row = sheet.createRow(i);

僅當新行不存在時才創建新行!

你就完成了,它就像一個魅力!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM