【发布时间】:2016-05-05 14:30:46
【问题描述】:
我想从 Excel 文件中读取数据,并希望将诸如 HashMap 之类的东西存储到 Java 集合中。
我已经通过 Apache POI 实现了 Excel 读取——这部分工作得很好。 现在我想知道如何将这些数据存储到 HashMap 中。
我创建了 1 个具有 Excel 数据值的 POJO 类。
Class EmpXcel
private String emp_name;
private String emp_job;
// parameterised constructor
// getter-setter
现在如果我创建这个特定 POJO 类的类型的 HashMap。
例如。 Map<String, EmpXcel> map = new HashMap<String, EmpXcel>();
这是我从 Excel 读取数据的代码。
while(itr.hasNext()){
Row nextRow = itr.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch (cell.getCellType())
{
// if cell is numeric format
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue()+",");
break;
// if cell is string format
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + ",");
break;
}
}
System.out.println();
}
我不确定如何将此数据存储到 POJO 类(此处为 EmpXcel)类型的 HashMap 中。
编辑:Excel 表格:
Emp_Name | Emp_Job
Travis | Technical Assistant
John | Professor
我还想让它更通用-想为不同的 Excel 文件创建单个 Java 类(不考虑行数/列数)
请与我分享你的一些见解,以便我可以按照这种方式进行操作。
谢谢。
【问题讨论】:
-
excel中的数据是什么类型的?
-
为什么要使用HashMap?顺序不可预测。
-
@java8.being。字符串类型...用 Excel 表格示例更新问题
-
查看数据似乎根本不需要地图。这也可以提取到列表中
-
目前没有大约 10k 条记录。如果我按照您的建议实现 ArrayList,我将如何将每列的记录添加到其中。例如。 _我从 Excel Emp_Name 和 Emp_Job 读取-我应该如何添加并在稍后的时间点检索?_>
标签: java excel collections hashmap apache-poi