使用Apache POI读取Excel文件

5
我已经使用Apache POI创建了这个代码来读取Excel文件的内容。我正在使用Eclipse作为编辑器,但是当我运行代码时,在粗体字中的那一行出现问题。问题在哪里?
Excel的内容如下:
Emp ID  Name    Salary

 1.0    john    2000000.0

 2.0    dean    4200000.0

 3.0    sam     2800000.0

 4.0    cass    600000.0

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;



public class ExcelRead {

public static void main(String[] args) throws Exception {
    File excel = new File ("C:\\Users\\Efi\\Documents\\test.xls");
    FileInputStream fis = new FileInputStream(excel);

    HSSFWorkbook wb = new HSSFWorkbook(fis);
    HSSFSheet ws = wb.getSheet("Input");

    int rowNum = ws.getLastRowNum()+1;
    int colNum = ws.getRow(0).getLastCellNum();
    String[][] data = new String[rowNum][colNum];


    for (int i=0; i<rowNum; i++){
        HSSFRow row = ws.getRow(i);
            for (int j=0; j<colNum; j++){
                HSSFCell cell = row.getCell(j);
                String value = cellToString(cell);
                data[i][j] = value;
                System.out.println("The value is" + value);

            }
       }
    }

public static String cellToString (HSSFCell cell){

int type;
Object result;
type = cell.getCellType();

    switch(type) {


    case 0://numeric value in excel
        result = cell.getNumericCellValue();
        break;
    case 1: //string value in excel
        result = cell.getStringCellValue();
        break;
    case 2: //boolean value in excel
        result = cell.getBooleanCellValue ();
        break;
    default:
        ***throw new RunTimeException("There are not support for this type of               
       cell");***
        }

return result.toString();
}

}

问题就在这里:throw new RunTimeException("不支持此类型的单元格"); - user2235454
你粗体标记的那一行在哪里?"throw new Exception..."?函数cellToString必须捕获你抛出的异常或在其后面添加"throws Exception"。 - user2235520
4个回答

3

请查看我为读取XLSX、XLS和CSV文件创建的这个库,使用起来相当容易。它使用Apache POI处理Excel文件,并根据您的配置将Excel行转换为Java bean列表。

这里有一个示例:

RowConverter<Country> converter = (row) -> new Country(row[0], row[1]);

ExcelReader<Country> reader = ExcelReader.builder(Country.class)
     .converter(converter)
     .withHeader()
     .csvDelimiter(';')
     .sheets(1)
     .build();

List<Country> list;
list = reader.read("src/test/resources/CountryCodes.xlsx");
list = reader.read("src/test/resources/CountryCodes.xls");
list = reader.read("src/test/resources/CountryCodes.csv");

有以下Excel和Bean文件:

public static class Country {
  public String shortCode;
  public String name;

  public Country(String shortCode, String name) {
    this.shortCode = shortCode;
    this.name = name;
  }
}

Excel:

    Code    Country
ad  Andorra
ae  United Arab Emirates
af  Afghanistan
ag  Antigua and Barbuda
...

3

除了您在switch语句中捕获的单元格类型之外,还有其他单元格类型。您有0CELL_TYPE_NUMERIC),1CELL_TYPE_STRING)和2的情况,但2CELL_TYPE_FORMULA。以下是其他可行的值:

  • 3:CELL_TYPE_BLANK
  • 4:CELL_TYPE_BOOLEAN
  • 5:CELL_TYPE_ERROR

在您的switch语句中使用Cell常量作为单元格类型,而不是整数文字,并使用所有6个常量来捕获所有可能的情况。

正如@Vash已经建议的那样,在RuntimeException消息中包含实际的单元格type


1
使用XSSFWorkbook和XSSFSheet无法帮助我读取.xls文件,但是我使用了这段代码,它可以帮助我读取.xls和.xlsx文件:
  public static void readExcelFile(File file) throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(file.toString()));
        Integer sheet = workbook.getNumberOfSheets();
        DataFormatter dataFormatter = new DataFormatter();
        for (int i = 0; i < sheet; i++) {
            Sheet s = workbook.getSheetAt(i);
            Iterator<Row> rowIterator = s.rowIterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    printCellValue(cell);
                    // both work perfect
                    // printCellValue(cell);
                    /*String cellValue = dataFormatter.formatCellValue(cell);
                    System.out.print(cellValue + "\t");*/
                }
                System.out.println();
            }

        }
    }

public static void printCellValue(Cell cell) {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.print(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getRichStringCellValue().getString());
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    System.out.print(cell.getDateCellValue());
                } else {
                    System.out.print(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_FORMULA:
                System.out.print(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK:
                System.out.print("  ");
                break;
            default:
                System.out.print("");
        }

        System.out.print("\t");
    }

0

你应该在RuntimeException中添加关于哪种类型不受switch语句支持的信息。然后你就能够为它添加支持,这样就不会抛出异常了。

所以,为了看到程序正在做什么,而不是

throw new RunTimeException("There are not support for this type of cell");

你应该添加

throw new RunTimeException("There are not support for type with id ["+type+"] of cell");

这将仅仅告诉你你错过了什么。如何处理这种情况取决于你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接