Java的Apache的POI(第一部分) [英] java apache poi (part 1)
问题描述
-
Excel文件(staff.xls)
ID          
1             阿里
2             
3             
excel file (staff.xls)
ID name
1 ali
2 abu
3 ahmad
Java的code
java code
FileInputStream inputFile = new FileInputStream("staff.xls");
XSSFWorkbook workbook = new XSSFWorkbook(inputFile);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
Cell cell;
Iterator<Row> rowIterator = spreadsheet.iterator();
while(rowIterator.hasNext()){
row = (XSSFRow)rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()){
cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
switch(cell.getCellType()){
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue()+"|");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue()+"|");
break;
}
}
System.out.println();
}
我的问题是:
(1)如何把记录插入到数组或数组列表?
(2)建立后,如何分割|?
My question is:
(1) How to put the record into the array or arraylist?
(2) After create, how to split the "|"?
推荐答案
就在创建列表变量列表中的第一的,而的,在每次迭代的开始创建一个新的列表,把元素该列表,在迭代的末尾添加此列表列出的主列表。你应该得到类似的东西:
Just create a List of List variable before the first while, in the beginning of every iteration create a new List, put the elements to this list and add this list to the main List of Lists at the end of the iteration. You should get something like that:
...
List<List<String>> records = new ArrayList<List<String>>();
while(rowIterator.hasNext()){
List<String> record = new ArrayList<String>();
row = (XSSFRow)rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()){
cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
switch(cell.getCellType()){
case Cell.CELL_TYPE_STRING:
record.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
record.add(Double.toString(cell.getNumericCellValue()));
break;
}
}
records.add(record);
}
for (List<String> record : records) {
for (String s : record) {
System.out.print(" " + s);
}
System.out.println();
}
...
另请注意,你不需要添加|符号了,所以没有必要最终分裂。但在一般分割字符串有一个方法字符串分割#(),它接受一个常规的前pression。你需要使用它像,通过拆分| (你需要之前把\\ |,因为它是一种特殊的正则表达式字符):
Also notice that you don't need to add | symbol anymore, so no need to split eventually. But in general to split the string there is a method String#split() which accepts a regular expression. You need to use it like that to split by "|" (you need to put \ before | as it is a special regexp character):
for (String record : records) {
System.out.println(record);
String[] elements = record.split("\\|");
for (String element : elements) {
System.out.println(" -> " + element);
}
}
这篇关于Java的Apache的POI(第一部分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!