简体   繁体   中英

Using Apache POI to write in xlsx file, Getting expected answer in the last column of the file

I am learning how to write in the xlsx file using Apache poi,Now in the below code i am using 2 array. 1.Month 2.Logging_Hours.

I am using Month array to assign the column name in the first row and it work fine for me.Now what i want the another Array in my code Logging_Hours print in each column but i am not getting the expected answer by using the below code.

For_Expected refer to the screen :"Expected_Xlsx" For_Actual refer to the screen :"Actual_Xlsx"

public class Writing_xlsx {

  public static void main(String[] args) throws IOException {

    Workbook wb = new XSSFWorkbook();

    Sheet sheet1=wb.createSheet("SheetOne");

    String [] Month={"January" , "Feb", "March","Apr"};
    int [] Logging_Hours={ 7 ,5, 9,10};
    int f=0;
    System.out.println(Month[0]);

    Row r=sheet1.createRow(f);

    for(int i=0;i<4;i++){

    r.createCell(i).setCellValue(Month[i]);   

    }

    for(int c=0;c<4;c++){}
        int d=0;
        while(d<4){

        for(int rn=1;rn<=4;rn++)    {

            r=sheet1.createRow(rn);
            r.createCell(d).setCellValue(Logging_Hours[rn-1]);
            System.out.println(Logging_Hours[rn-1]);

        }
        d++;
        }

        FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");

    wb.write(fileOut);
    fileOut.close();    
    wb.close();

}

}

For_Expected refer to the screen :"Expected_Xlsx"

这是运行程序后的预期屏幕

For_Actual refer to the screen :"Actual_Xlsx"

这是我得到的实际屏幕

Thank You in advance ,Sorry for the bad code i am just in a learning phase.

You will need two for loops (nested) to write the data, eg:

for (int rn = 1; rn <= 4; rn++) {
    Row row = sheet1.createRow(rn);
    for (int i = 0; i < 4; i++) {
        row.createCell(i).setCellValue(Month[rn-1]);
    }
}

Current for loop creates only one cell per row and writes the value into it whereas we need to write the values in all 4 cells per row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM