2017-03-18 25 views
1

我正在學習如何使用Apache poi寫入xlsx文件,現在在下面的代碼中我使用了2個數組。 1.Month 2.Logging_Hours。使用Apache POI寫入xlsx文件,在文件的最後一列獲取預期的答案

我使用Month數組來指定第一行的列名,它對我來說工作正常。現在我想要我的代碼中的另一個數組Logging_Hours打印在每列中,但我沒有通過使用得到預期的答案下面的代碼。

For_Expected指屏幕: 「Expected_Xlsx」 For_Actual指屏幕: 「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指屏幕: 「Expected_Xlsx」

This is the expected screen after running the programm

For_Actual參考到屏幕:「Actual_Xlsx」

This is the actual screen i am getting

在此先感謝您,對不起,我只是處於學習階段。

回答

2

您將需要兩個for循環(嵌套)寫入數據,例如:

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

當前for循環只創建一個cell每行並寫入值到它,而我們需要寫的值每行4個單元格。

+0

,這是我想打印列A中每列的Logging_Hours的另一個答案:7,5,9,10 您的建議做了什麼:列A:7,7,7,7 –

+0

@balvinderdhillon this在你的問題中符合「預期答案」。 –

+0

請仔細看看它的不同.......我的預期代碼給列A/O:P:7,5,9,10 –

相關問題