我正在尝试从xlsx文件中读取一个基本的java程序,并将每一行放入一个arrayList作为字符串,稍后我会将该行的String拆分。
下面是我的代码,但是我正在试图找出我出错的地方,因为它似乎没有做任何事情。
List<String> text = new ArrayList<String>();
Workbook wb = WorkbookFactory.create(new File("input.xlsx"));
DataFormatter fmt = new DataFormatter();
Sheet s = wb.getSheetAt(0);
for (Row r : s) {
StringBuffer sb = new StringBuffer();
for (Cell c : r) {
if (sb.length() > 0) sb.append(" - ");
sb.append(fmt.formatCell(c));
}
text.append(sb.toString());
}
任何帮助将不胜感激。
答案 0 :(得分:0)
你没有阅读任何细胞。见这个例子:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xlsx"));
//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook (file);
//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}