使用成员类variables来读取Apache POI Java

嗨如何创build一个循环中的dynamic对象来存储对象中的多个值。 然后访问这些对象进行操作。

是否有可能给对象创builddynamicvariables名称。 我可以给赋值的左侧的variables的dynamic值吗? 如果问题不清楚,请问我编辑,如果解决scheme已经可用,请指出。

package poi; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ExcelRead_UsingMember { public static int C, R, i; public static double ID; private static final String FILE_READ = "C:/Users/m93162/ApachePOI_Excel_Workspace/MyFirstExcel.xlsx"; //private static final String FILE_WRITE = "C:/Users/m93162/ApachePOI_Excel_Workspace/WriteExcel.xlsx"; public static void main(String[] args) { List<Member> listOfMembers = new ArrayList<Member>(); try { FileInputStream excelFile = new FileInputStream(new File(FILE_READ)); Workbook workbook = new XSSFWorkbook(excelFile); Sheet datatypeSheet = workbook.getSheetAt(0); Iterator<Row> iterator = datatypeSheet.iterator(); while (iterator.hasNext()) { Row currentRow = iterator.next(); Iterator<Cell> cellIterator = currentRow.iterator(); int i=0; while (cellIterator.hasNext()) { Member [member+i] = new Member(); QUESTION: I want to create dynamic objects here and store the values below dynamically. How to approach this. Cell currentCell = cellIterator.next(); if (currentCell.getCellTypeEnum() == CellType.STRING) { System.out.print(currentCell.getStringCellValue() + "--"); } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) { System.out.print(currentCell.getNumericCellValue() + "--"); } } System.out.println(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 

你可以使用地图。

DynamicObject

 DynamicObject { prvate Map<String, Object> map = new HashMap(); public void addPropery(String key, Object value) { map.put(key, value); } } 

Your code

 private void processRow(Row row) { while (cellIterator.hasNext()) { dynamicObjects[member+i] = new DynamicObject(); DynamicObject dynamicObject = dynamicObjects[member+i]; Cell currentCell = cellIterator.next(); if (currentCell.getCellTypeEnum() == CellType.STRING) { System.out.print(currentCell.getStringCellValue() + "--"); dynamicObject.addProperty("stringField", currentCell.getStringCellValue()); } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) { System.out.print(currentCell.getNumericCellValue() + "--"); dynamicObject.addProperty("numericField", currentCell.getNumericCellValue()); } } } 

然后你可以遍历地图的键来获得所有可能的值。 您还可以将其他对象(例如嵌套地图)作为值存储在地图中。