读取单列中包含多个值的Excel文件-Java
我正在使用ApachePOI读取Excel文件。 我的Excel表格结构是这样的读取单列中包含多个值的Excel文件-Java,java,excel,apache-poi,Java,Excel,Apache Poi,我正在使用ApachePOI读取Excel文件。 我的Excel表格结构是这样的 |2000s| 2001, 2003, 2008, 2009| 因此,对于右侧数据,我要求将其分配到2000s 到目前为止,我一直以这种方式实施: List<Class> list = new ArrayList<Class>(); File file = new File(file_path); FileInputStream fis = new File
|2000s| 2001, 2003, 2008, 2009|
因此,对于右侧数据,我要求将其分配到2000s
到目前为止,我一直以这种方式实施:
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();
}
List List=new ArrayList();
文件=新文件(文件路径);
FileInputStream fis=新的FileInputStream(文件);
//创建引用excel文件的工作簿实例
XSSF工作簿wb=新XSSF工作簿(fis);
//这将选择第一张图纸
XSSFSheet-sheet=wb.getSheetAt(0);
//逐个遍历每一行
迭代器itr=sheet.Iterator();
字符串newName=null;
字符串oldName=null;
while(itr.hasNext()){
行nextRow=itr.next();
//对于每一行,遍历所有列
迭代器cellIterator=nextRow.cellIterator();
while(cellIterator.hasNext())
{
Cell=cellIterator.next();
newName=nextRow.getCell(0.toString();
if(nextRow.getCell(1).toString()包含(“,”){
StringTokenizer st=新的StringTokenizer(nextRow.getCell(1.toString(),“,”);
而(st.hasMoreTokens()){
oldName=st.nextToken();
}
}
否则{
oldName=nextRow.getCell(1.toString();
}
}
System.out.println();
}
当我编译时,它在nextRow.getCell(1)
行抛出“空指针异常”
我不明白如何将所有逗号值映射到2000
这对于正常数据(没有逗号)非常有效。逗号值已被处理 我正在发布答案,以便有人能从这里得到帮助 我所做的是添加了字符串标记器类,如果单元格中有逗号,它会用逗号分隔符分隔值 让我们看看下面的代码
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();
}
(它只将空值视为空白)
通过这种方式,您还可以在读取空值时解决Excel中的空指针异常
Cell cell2 = row.getCell(j,org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK);