1.poi版本:3.14,其他版本在我开发的项目中会有问题,只有这一个版本可用。
2.poi引入方式:maven
3.maven引入语句:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
4.读取excle代码:
public static List<UserWaterCount> readXls(String path,String year) {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
InputStream is = null;
InputStream is2 = null;
try {
is = new FileInputStream(path);
is2 = new FileInputStream(path);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
//HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
//Workbook hssfWorkbook = WorkbookFactory.create(is);
Workbook hssfWorkbook = null;
try {
hssfWorkbook = new XSSFWorkbook(is);
} catch (java.lang.Exception e) {
e.printStackTrace();
try {
hssfWorkbook = new HSSFWorkbook(is2);
} catch (java.lang.Exception e1) {
e1.printStackTrace();
}
}
UserWaterCount xlsDto = null;
List<UserWaterCount> list = new ArrayList<UserWaterCount>();
// 循环工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
//HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行Row
for (int rowNum = 2; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
//HSSFRow hssfRow = hssfSheet.getRow(rowNum);
Row hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow == null) {
continue;
}
//保存值
xlsDto = new UserWaterCount();
xlsDto.setGuid(UUID.randomUUID().toString().replace("-",""));
xlsDto.setYr(year);
xlsDto.setTs(f.format(new Date()));
int index=0;
xlsDto.setUserIndex(getInteger(getValue(hssfRow.getCell(index++))));//序号
String username = getValue(hssfRow.getCell(index++));
if(username==null || username.trim().equals("")){//没有用户则放弃该条记录
continue;
}
xlsDto.setUserwName(username!=null?username.trim():username);//用户名
xlsDto.setPwaterJan(getInteger(getValue(hssfRow.getCell(index++))));//一月计划
xlsDto.setAwaterJan(getInteger(getValue(hssfRow.getCell(index++))));//一月实际
list.add(xlsDto);
}
break;//只循环第一个sheet,然后直接退出
}
return list;
}
private static String getValue(Cell hssfCell) {
if (hssfCell == null) {
return null;
}
if (hssfCell.getCellType() == 0) {
// 返回数值类型的值
return String.valueOf(hssfCell.getNumericCellValue());
} else {
// 返回字符串类型的值
return String.valueOf(hssfCell.getStringCellValue());
}
}
public static Double getDouble (String a){
if(a==null||a.trim().equals("")||a.equals("null")){
return null;
}else{
Double b =null;
try {
b=Double.valueOf(a);
return b;
} catch (NumberFormatException e) {
e.printStackTrace();
return null;
}
}
}
public static Integer getInteger (String a){
if(a==null||a.trim().equals("")||a.equals("null")){
return null;
}else{
try {
return Double.valueOf(a).intValue();
} catch (NumberFormatException e) {
e.printStackTrace();
return null;
}
}
}