[英]Java: Issue With Storing Data from Excel in an ArrayList of ArrayLists
I'm trying to store data from excel in ArrayLists, which will then be stored in a main ArrayList. 我正在尝试将来自Excel的数据存储在ArrayLists中,然后将其存储在主ArrayList中。 The reason being that each row of the excel sheet has data that is particular to that row. 原因是excel表的每一行都有特定于该行的数据。 I keep having an issue because I believe when I erase the inner ArrayList before looping back, it deletes the data in the master ArrayList as well. 我一直有问题,因为我相信当我在循环返回之前擦除内部ArrayList时,它也会删除主ArrayList中的数据。
import java.io.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.util.ArrayList;
public class StoreData {
ArrayList<ArrayList<String>> shapes;
ArrayList<String> innerMembers;
ArrayList<String> test;
int start;
int end;
public StoreData(){
this.shapes = new ArrayList<>();
this.innerMembers = new ArrayList<>();
this.test = new ArrayList<>();
start = 0;
end = 0;
}
public ArrayList<ArrayList<String>> storeValues(String shapeType){
//get the shape
switch(shapeType){
case "A":
start = 1;
end = 273;
break;
case "B":
start = 274;
end = 291;
break;
case "C":
start = 292;
end = 319;
break;
case "D":
start = 320;
end = 340;
break;
case "E":
start = 341;
end = 372;
break;
case "F":
start = 373;
end = 412;
break;
case "G":
start = 413;
end = 539;
break;
case "H":
start = 540;
end = 814;
break;
case "I":
start = 1464;
end = 1958;
}
try
{
FileInputStream x = new FileInputStream(new File("/Users/JohnDoe/Documents/File.xls"));
//Create Workbook instance
Workbook workbook = new HSSFWorkbook(x);
//Get first/desired sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
for (int i = start; i <= end; i ++){
Row row = sheet.getRow(i++);
//iterate through each cell in row: max number of cells is 76
for (int j = 0; j < 77; j++) {
Cell cell = row.getCell(j);
cell.setCellType(1);
innerMembers.add(cell.getStringCellValue());
}
/*******************/
//Add to master ArrayList and clear inner ArrayList to get repopulated
/*******************/
shapes.add(innerMembers);
innerMembers.clear();
}
x.close();
}
catch (Exception e)
{
e.printStackTrace();
}
/***TEST STATEMENT***/
System.out.println(shapes.get(8).get(20));
/***TEST STATEMENT***/
return shapes;
}
}
You might want to try: 您可能想尝试:
shapes.add(new ArrayList<String>(innerMembers)); // shallow copy
innerMembers.clear();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.