我正在尝试获取一个基本的Java程序,以从xlsx文件中读取内容并将每一行作为字符串放入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());
}


任何帮助,将不胜感激。

最佳答案

您没有在读取任何单元格。请参阅以下示例:

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();
}

10-08 20:28