Excel文件的版本不同,后缀也不同,使用的jar包也不同,97-2003版本的Excel后缀是 ".xls" ,而2007版本后面的版本后缀是".xlsx".
HSSFWorkbook()这个对象只能操作2003以下版本,XSSFWorkbook()这个对象只能操作2007以上版本。
这里以2003以下版本为例,解析Excel内容。
就解析图中的内容,
public static void main(String[] args) throws IOException {
String path = "C:/Users/xxxxx/Desktop/test3.xls";
List<Map<String,Object>> data = readExcel(path);
for(int i = 0;i<data.size();i++){
System.out.print("第"+i+"行第一列:"+data.get(i).get("第一列")+"||");
System.out.print("第"+i+"行第二列:"+data.get(i).get("第二列")+"||");
System.out.print("第"+i+"行第三列:"+data.get(i).get("第三列")+"||");
System.out.println();
}
}
@SuppressWarnings("resource")
private static List<Map<String,Object>> readExcel(String path) throws IOException{
List<Map<String,Object>> recordList = new ArrayList<Map<String,Object>>();
File file = new File(path);
HSSFWorkbook hs = null;
InputStream fileInput = null;
fileInput = new FileInputStream(file);
hs = new HSSFWorkbook(fileInput);
//获取excell的第一个sheet页
HSSFSheet sheet = hs.getSheetAt(0);
//获取第一行,一般为标题行
HSSFRow row = sheet.getRow(1);
//获取第一行有几列
int cols = row.getPhysicalNumberOfCells();
//获取文件总行数
int totalRows = sheet.getLastRowNum();
//遍历每一行
for(int i = 1; i<=totalRows;i++){
HSSFRow recordRow = sheet.getRow(i);
Map<String,Object> resMap = getRecordMap(recordRow,i);
recordList.add(resMap);
}
fileInput.close();
return recordList;
}
private static Map<String, Object> getRecordMap(HSSFRow recordRow, int i) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("第一列", getCellContent(recordRow,0).trim());
map.put("第二列", getCellContent(recordRow,1).trim());
map.put("第三列", getCellContent(recordRow,2).trim());
return map;
}
private static String getCellContent(HSSFRow recordRow, int i) {
HSSFCell hsCell = recordRow.getCell((short)i);
return hsCell.getStringCellValue().trim();
}
运行结果:
解析完毕。