首页 > 学院 > 开发设计 > 正文

使用POI解析Excel

2019-11-06 07:29:56
字体:
来源:转载
供稿:网友

  最近在写项目,涉及到批量添加学生信息,通过网上查了众多资料,终于通过上传一个Excel文件的方式加以解决,现特此记录下来,以备以后查看。

  涉及到的技术点是POI,该APIl隶属于Apache,官网http://poi.apache.org/。涉及到的相关jar如图:

 解析的核心代码

 @SupPRessWarnings("static-access")public static List<Student> readXls(InputStream inputStream){List<Student> studentList=new ArrayList<Student>();try {//1.得到工作薄HSSFWorkbook workbook=new HSSFWorkbook(inputStream);//2.得到第一张表 索引是从0开始的 sheet0,一个HSSFSheet对象代表着一页HSSFSheet hssfSheet=workbook.getSheetAt(0);//3.遍历读出每一行,从0开始....int minRow=hssfSheet.getFirstRowNum();  int maxRow=hssfSheet.getLastRowNum();            //System.out.println(minRow+"**********"+maxRow);HSSFRow titleHssfRow=hssfSheet.getRow(0);//System.out.println("*********标题************");//System.out.println(titleHssfRow.getCell(0).getStringCellValue()+"          "+titleHssfRow.getCell(1).getStringCellValue()+"  "+titleHssfRow.getCell(2).getStringCellValue());for (int i = 1; i <=maxRow; i++) {                  //首行为标题,略过HSSFRow hssfRow=hssfSheet.getRow(i);    if (hssfRow!=null) {Student student=new Student();try {HSSFCell cell0=hssfRow.getCell(0);HSSFCell cell1=hssfRow.getCell(1);HSSFCell cell2=hssfRow.getCell(2);HSSFCell cell3=hssfRow.getCell(3);HSSFCell cell4=hssfRow.getCell(4);HSSFCell cell5=hssfRow.getCell(5);HSSFCell cell6=hssfRow.getCell(6);if (cell0!=null){             //0 number    1 Stringdouble studentId=cell0.getNumericCellValue();String tem=studentId+"";String sid=tem.substring(0,tem.indexOf("."));student.setStudentId(sid);}if (cell1!=null) {student.setName(cell1.getStringCellValue());}if (cell2!=null) {student.setGender(cell2.getStringCellValue());}if (cell3!=null) {student.setDepartmentName(cell3.getStringCellValue());}if (cell4!=null) {student.setMajor(cell4.getStringCellValue());}if (cell5!=null) {double phone=cell5.getNumericCellValue();String tem=phone+"";String phoneString=tem.substring(0,tem.indexOf("."));student.setPhone(phoneString);}if (cell6!=null) {student.setEmail(cell6.getStringCellValue());}studentList.add(student); } catch (IllegalStateException e) {// TODO Auto-generated catch blocklogger.error("Excle中数据格式不符合要求");}}                           }} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return studentList;}

     这样通过解析Excel文件对应的输入流,成功解析了Excel,并将信息封装到List返回

    在main中调用测试:

public static void main(String[] args) {try {/*InputStream inputStream=new FileInputStream("D:/student.xls");readXls(inputStream);*/InputStream inputStream=new FileInputStream("D:/aaa.xlsx");List<Student> studentList=readXlsx(inputStream);System.out.println(studentList);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

    另外,对于低版本的Excel,文件格式为xls,需要用到HSSFRow等相关对象,解析逻辑是一样的,只不过换了几个对象而已。


上一篇:volatile

下一篇:获取当前时间

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表