gpt4 book ai didi

java - 使用 Apache POI 写入 xlsx 文件,在文件的最后一列中获得预期答案

转载 作者:行者123 更新时间:2023-11-30 02:36:38 24 4
gpt4 key购买 nike

我正在学习如何使用 Apache poi 在 xlsx 文件中写入,现在在下面的代码中我使用 2 个数组。1.月份 2.Logging_Hours。

我使用 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

预先感谢您,对于错误的代码,我深表歉意,我正处于学习阶段。

最佳答案

您将需要两个 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 个单元格中写入值。

关于java - 使用 Apache POI 写入 xlsx 文件,在文件的最后一列中获得预期答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42872974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com