java poi读取excel文件

来源:互联网 发布:手机淘宝小二怎么联系 编辑:程序博客网 时间:2024/04/30 08:29
/**
* 读取excel文件
* @param filePath 文件相对路径
* @return
*/
public static Map<String, String> readExcelToMap(String filePath){
Map<String, String> keyMap = new HashMap<String, String>();
File file = null;
FileInputStream is = null;

filePath = CommonUtil.class.getResource("/").getPath() + filePath;
try {
file = new File(filePath);
is = new FileInputStream(file);
Workbook workbook = WorkbookFactory.create(is);
if(workbook.getNumberOfSheets() < 1){
return null;
}
Sheet sheet = workbook.getSheetAt(0);
int rowCount = sheet.getPhysicalNumberOfRows();
for(int i = 0; i < rowCount; i++){
Row row = sheet.getRow(i);
Cell keyCell = row.getCell(0);
String value = null;
if(keyCell != null && keyCell.getCellType() == Cell.CELL_TYPE_STRING){
value = keyCell.getStringCellValue();
Cell valueCell = row.getCell(1);
if(valueCell.getCellType() == Cell.CELL_TYPE_STRING){
String key = valueCell.getStringCellValue();
key = key.trim();
value = value.trim();
keyMap.put(key, value);
}
}
}
} catch (Exception e) {
throw new RuntimeException("打开 " + filePath + " 时出错!", e);
} finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
//
}
}
}
return keyMap;

}


主要代码就是这样

0 0
原创粉丝点击