【发布时间】:2019-05-08 18:26:56
【问题描述】:
我有一个字符串数组列表名称,代码如下:
[a,b,c,d]
和另一个字符串数组列表,其中包含类似此名称的数据作为 DWS:
[a11,a22,a33,a44,a55,a66,a77,b11,b22,b33,b44,b55,b66,b77,c11,c22,c33,c44,c55,c66,c77,d11,d22,d33,d44,d55,d66,d77]
我想要做的是我想将 DWS 数组列表写入 excel 文件,如下所示:
我试过这种方式:
FileInputStream file1 = new FileInputStream(new File(namefile));
XSSFWorkbook wb1 = new XSSFWorkbook(file1);
XSSFSheet sheet1 = wb1.getSheetAt(0);
int limit = 7;
for (int m = 0; m < code.size(); m++) {
for (int x = 0; x < DWS.size(); x++) {
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
Cell cell = row2.createCell(m * 3 + 4);
cell.setCellValue(DWS.get(x));
}
}
}
知道如何解决这个问题吗?
更新
我按照建议更改我的代码:
int limit = 7;
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
for (int m = 0; m < code.size(); m++) {
Cell cell = row2.createCell(m * 3 + 4);
cell.setCellValue(DWS.get(i));
}
}
结果是这样的:
它只循环前 7 个数据。我需要它继续数组列表的其余部分。就像第一张图片一样。
更新
让我再解释一下我的代码流程
1) 它将 DWS 数组列表循环到第一个单元格 5 号单元格并循环到最后一行第 7 行,
2) 然后,在它到达第 7 行后,它应该创建一个新单元格,该单元格在 Cell cell = row2.createCell(m * 3 + 4); 行中,然后再次从 DWS 数组列表数据继续循环。
3)这个步骤会一直持续到到达DWS的最后一个arraylist数据
有可能做到吗?
更新 2.0
我改成这样:
int cellValueIndex = 0;
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
for (int m = 0; m < code.size(); m++) {
Cell cell = row2.createCell(m * 3 + 4);
cell.setCellValue(DWS.get(cellValueIndex));
cellValueIndex++;
}
}
但我得到了这样的错误:
java.lang.IndexOutOfBoundsException
更新 3.0
我改成这个了,结果还是错了
int cellValueIndex = 0;
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
for (int m = 0; m < code.size(); m++) {
Cell cell = row2.createCell(m * 3 + 4);
cell.setCellValue(DWS.get(cellValueIndex));
}
cellValueIndex = cellValueIndex + 1;
}
更新 4.0
我对此进行了更改:
int cellValueIndex = 0;
int counter = 0;
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
Cell cell = row2.createCell(4);
cell.setCellValue(DWS.get(cellValueIndex));
cellValueIndex++;
int x = row2.getRowNum();
if (x == limit) {
for (int m = 1; m < code.size(); m++) {
Cell cell1 = row2.createCell(m * 3 + 4);
cell1.setCellValue(DWS.get(cellValueIndex + 1));
cellValueIndex++;
}
}
}
结果是这样的:
但是当我尝试设置 i=0; 时,像这样:
int cellValueIndex = 0;
for (int i = 0; i < total1; i++) {
Row row2 = sheet1.getRow(i + 2);
Cell cell = row2.createCell(4);
cell.setCellValue(DWS.get(cellValueIndex));
cellValueIndex++;
int x = row2.getRowNum();
if (x == total1) {
i = 0;
for (int m = 1; m < shiftcode.size(); m++) {
Cell cell1 = row2.createCell(m * 3 + 4);
cell1.setCellValue(DWS.get(cellValueIndex));
cellValueIndex++;
i++;
}
}
}
我收到这样的错误:
java.lang.IndexOutOfBoundsException
【问题讨论】:
-
在您的更新版本上:您仍然没有像我在下面的回答中建议的那样使用 cellValueIndex。如果您使用它,您的数据将正确显示。
-
@Ketan 我收到错误
java.lang.IndexOutOfBoundsException: -
@Ketan 查看我的最新更新
-
你的限制是 7,代码的大小是 4。所以你需要 28 个元素......并且 cellValueIndex 应该去的最大值是 27(这是数组或列表中的第 28 个元素)。如果 DWS 中的元素较少,那么您一定会遇到该异常。否则我看不出理由。使用 IntelliJ 或 Eclipse 等 IDE 的调试功能,您应该可以做到
-
@Ketan 查看我的最新更新
标签: java excel loops apache-poi indexoutofboundsexception