Reputation: 109
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.
Upvotes: 1
Views: 93
Reputation: 30809
You will need two for
loops (nested) to write the data, e.g.:
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.
Upvotes: 2