gpt4 book ai didi

Java:在 ArrayList 的 ArrayList 中存储来自 Excel 的数据时出现问题

转载 作者:行者123 更新时间:2023-11-29 05:13:06 24 4
gpt4 key购买 nike

我正在尝试将来自 excel 的数据存储在 ArrayList 中,然后将其存储在主 ArrayList 中。原因是 Excel 工作表的每一行都有特定于该行的数据。我一直有问题,因为我相信当我在循环返回之前删除内部 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;

}
}

最佳答案

你可能想试试:

shapes.add(new ArrayList<String>(innerMembers)); // shallow copy 
innerMembers.clear();

关于Java:在 ArrayList 的 ArrayList 中存储来自 Excel 的数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27596464/

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