我正在使用Apache POI读取Excel文件。我的Excel表格结构如下
|2000s| 2001, 2003, 2008, 2009|
所以对于右手边的数据,我要求它分配给2000年代的
到目前为止,我已经实现了这种方式:
List<Class> list = new ArrayList<Class>();
File file = new File(file_path);
FileInputStream fis = new FileInputStream(file);
//Create an instance of workbook which refers to an excel file
XSSFWorkbook wb = new XSSFWorkbook(fis);
//This selects the 1st sheet
XSSFSheet sheet = wb.getSheetAt(0);
//Iterate through each row one by one
Iterator<Row> itr = sheet.iterator();
String newName = null;
String oldName = null;
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();
newName = nextRow.getCell(0).toString();
if(nextRow.getCell(1).toString().contains(",")){
StringTokenizer st = new StringTokenizer(nextRow.getCell(1).toString(),",");
while(st.hasMoreTokens()){
oldName = st.nextToken();
}
}
else{
oldName = nextRow.getCell(1).toString();
}
}
System.out.println();
}
当我编译时,它在nextRow.getCell(1)
行向我抛出"空指针异常"。
我不明白如何将所有逗号值映射到2000年代。
这对于正常数据(没有逗号)来说非常好。
逗号值已被处理
我正在发布答案,以便有人可以从这里获得帮助。
我所做的是添加StringTokenizer类,如果单元格中有逗号,它会用逗号分隔符来分隔值。
让我们看看下面的代码
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();
newName = nextRow.getCell(0).toString();
if(nextRow.getCell(1).toString().contains(",")){
StringTokenizer st = new StringTokenizer(nextRow.getCell(1).toString(),",");
while(st.hasMoreTokens()){
oldName = st.nextToken();
}
}
else{
oldName = nextRow.getCell(1).toString();
}
}
System.out.println();
}
此处newName获取第1列的值。(2000年代)并且oldName基于","分隔符获取令牌-在本例中为2001、2003、2008、2009
对于oldName的所有这些值,newName2000s将被映射。
更新:我在那里得到"Null指针异常"的原因,因为第二列(nextRow.getCell(1))的一些单元格为Null。
因此,每当迭代器到达空单元格时,就会抛出空指针异常。您需要在此处分配丢失单元格策略
通过
Cell cell2 = row.getCell(j,org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK);
(它只是将空值视为空白)
通过这种方式,您还可以在Excel中解决Null指针异常,同时读取Null值