使用Apache POI读取excel文件
我已创建此代码以使用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(); } }
除了在switch
语句中捕获的单元格类型之外,还有其他单元格类型 。 您的情况为0
( CELL_TYPE_NUMERIC
), 1
( CELL_TYPE_STRING
)和2
,但2
是CELL_TYPE_FORMULA
。 以下是其他可能的值:
- 3:
CELL_TYPE_BLANK
- 4:
CELL_TYPE_BOOLEAN
- 5:
CELL_TYPE_ERROR
在switch语句中使用Cell
常量作为单元格类型而不是整数文字,并使用它们中的所有6个来捕获所有可能的情况。
正如@Vash已经建议的那样,在RuntimeException
消息中包含实际的单元格type
。
检查我创建的库 ,以便使用内置Apache POI的Java8使用lambdas轻松读取XLSX,XLS和CSV文件。
这是一个例子:
RowConverter converter = (row) -> new Country(row[0], row[1]); ExcelReader reader = ExcelReader.builder(Country.class) .converter(converter) .withHeader() .csvDelimiter(';') .sheets(1) .build(); List 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 ...
您应该修改RuntimeException,并提供有关switch语句不支持的类型的信息。 然后您将能够添加对它的支持,因此不会抛出任何exception。
所以要看看你的程序正在做什么而不是
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");
这只会告诉你你错过了什么。 如何处理这种情况取决于你。