poi版本为3.14
导入excel的方法,返回一个list集合:
public List<Employee> excelOutPut(String path){
List<Employee> list = new ArrayList<Employee>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
FileInputStream fis = new FileInputStream(path);
POIFSFileSystem fs = new POIFSFileSystem(fis);
HSSFWorkbook workbook = new HSSFWorkbook(fs);//创建工作簿
HSSFSheet sheet = workbook.getSheetAt(0);//获取第1个工作表
for(int i=1;i<=sheet.getLastRowNum();i++){//循环Excel文件的每一行
HSSFRow row = sheet.getRow(i);//获取第i行
HSSFCell cell1 = row.getCell(0);//获取第一个单元格
HSSFCell cell2 = row.getCell(1);
HSSFCell cell3 = row.getCell(2);
HSSFCell cell4 = row.getCell(3);
HSSFCell cell5 = row.getCell(4);
HSSFCell cell6 = row.getCell(5);
HSSFCell cell7 = row.getCell(6);
HSSFCell cell8 = row.getCell(7);
Employee emp = new Employee();
String name = cell1.getStringCellValue();//名字
String sex = cell2.getStringCellValue();//性别
int age = (int) cell3.getNumericCellValue();//年龄
String dept = cell4.getStringCellValue();//部门
String duty = cell5.getStringCellValue();//职务
System.out.println(cell6.getNumericCellValue());//这里用数字接收会出现数字变成科学计数法。
cell6.setCellType(1);//设置单元格数据类型,为字符串,如果不设置,这里就不能用字符串来接收,只能用数字,而数字太长,会导致导入的数据变成科学计数法
String telephone = cell6.getStringCellValue();//电话
Date dutyTime = cell7.getDateCellValue();//入职时间
double wage = cell8.getNumericCellValue();//工资
emp.setName(name);
emp.setSex(sex);
emp.setAge(age);
emp.setDept(dept);
emp.setDuty(duty);
emp.setTelephone(telephone);
emp.setDutyTime(sdf.format(dutyTime));
emp.setWage(wage);
list.add(emp);
}
fis.close();
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
ListMapUtil lm = new ListMapUtil();
String path = "D://3.xls";//exel文件路径
// path = "D://2.xlsx";
List<Employee> list = lm.excelOutPut(path);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName()+", ");
System.out.print(list.get(i).getDutyTime()+", ");
System.out.print(list.get(i).getWage());
System.out.println();
}
}
实体类:
public class Employee {
private int id;
private String name;//名字
private String sex;//性别
private int age;//年龄
private String dept;//部门
private String duty;//职务
private String telephone;//电话
private String dutyTime;//入职时间
private double wage;//工资
}
打印结果:
1.3E10
1.3000000001E10
1.3000000002E10
1.3000000003E10
1.3000000004E10
1.3000000005E10
1.3000000006E10
张三1, 2015-01-02, 123.5
张三2, 2015-01-03, 123.6
张三3, 2015-01-04, 124.6
张三4, 2015-01-05, 125.6
张三5, 2015-01-06, 126.6
张三6, 2015-01-07, 127.6
张三7, 2015-01-08, 128.6
导入的Excel表格数据: