如何将数据从excel存储到ArrayList<ArrayList<String>> [英] How to store data from excel to ArrayList<ArrayList<String>>
问题描述
我有这样的 excel 数据
I have data from excel like this
111 | 222 | 333 | 444 | 555 | 666
11 | 12 | 13 | 14 | 15 | 16
1 | 2 | 3 | 4 | 5 | 6
a | b | c | d | e | f
我的代码是这样的
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("xxx"));
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet = wb.getSheetAt(0);
DataFormatter formatter = new DataFormatter();
ArrayList<ArrayList<String>> mainArrayList = new ArrayList<ArrayList<String>>();
ArrayList<String> al = new ArrayList<String>();
for (int rowNum = 0; rowNum < sheet.getLastRowNum() + 1; rowNum++) {
String val = null;
Row r = sheet.getRow(rowNum);
for (int i = 0; i < r.getLastCellNum() + 1; i++) {
Cell cell = r.getCell(i);
val = formatter.formatCellValue(cell);
}
al.add(val);
mainArrayList.add(al);
}
System.out.print(mainArrayList);
} catch (
Exception e) {
e.printStackTrace();
}
}
输出:[[, , , ], [, , , ], [, , , ], [, , , ]]
我想要的结果是这样的
[[111, 222, 333, 444, 555, 666, ],[11, 12, 13, 14, 15, 16, ],[1, 2, 3, 4, 5, 6, ],[a, s, d, f, g, h, ]]
我相信这是因为al.add(val);
是 null
但我不知道该怎么做才能将 val 添加到 arraylist阿尔.帮助?
I believe it is becauseal.add(val);
is null
but I don't know how to do in order for me to add the val into arraylist al. help?
推荐答案
首先你需要移动 ArrayList
转化为 for (int rowNum = 0; rowNum
al
现在需要在每个循环中都是新的.
First you need move ArrayList<String> al = new ArrayList<String>();
into for (int rowNum = 0; rowNum < sheet.getLastRowNum() + 1; rowNum++) {}
. al
needs to be new in each loop now.
其次,您需要将 al.add(val);
移动到 for (int i = 0; i < r.getLastCellNum() + 1; i++) {}代码>.因为在循环中,
val
是正确的值.
Second, you need move al.add(val);
into for (int i = 0; i < r.getLastCellNum() + 1; i++) {}
. Because in the loop, the val
is the right value.
ArrayList<String> al = new ArrayList<String>();
for (int rowNum = 0; rowNum < sheet.getLastRowNum() + 1; rowNum++) {
String val = null;
Row r = sheet.getRow(rowNum);
for (int i = 0; i < r.getLastCellNum() + 1; i++) {
Cell cell = r.getCell(i);
val = formatter.formatCellValue(cell);
}
al.add(val);
mainArrayList.add(al);
}
改成这个
for (int rowNum = 0; rowNum < sheet.getLastRowNum() + 1; rowNum++) {
ArrayList<String> al = new ArrayList<String>();
String val = null;
Row r = sheet.getRow(rowNum);
for (int i = 0; i < r.getLastCellNum() + 1; i++) {
Cell cell = r.getCell(i);
val = formatter.formatCellValue(cell);
al.add(val);
}
mainArrayList.add(al);
}
这篇关于如何将数据从excel存储到ArrayList<ArrayList<String>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!