Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

java - Issue while writing cells in excel file using apache POI

I am facing issue while writing the data to excel file. I am using apache POI 4.1.2 version library. Below is the sample code.

    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();
    }

In this only last column cells is getting saved in excel file , previous cells are kept as blank. Kindly help and let me know if I am doing something wrong?

Please find attached snippet for more reference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not sure about the actual api but I think you inner loop should create columns and your outer one should create rows like this

  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");
     }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...