分享

java使用POI实现excel文件的读取,兼容后缀名xls和xlsx

 青_春 2017-09-18

首先,引入所需的jar包:


如果是maven管理项目的jar包,只需在pom.xml中加上:

[html] view plain copy
  1. <!-- https:///artifact/org.apache.poi/poi -->  
  2. <dependency>  
  3.     <groupId>org.apache.poi</groupId>  
  4.     <artifactId>poi</artifactId>  
  5.     <version>3.14</version>  
  6. </dependency>  
  7. <!-- https:///artifact/org.apache.poi/poi-ooxml -->  
  8. <dependency>  
  9.     <groupId>org.apache.poi</groupId>  
  10.     <artifactId>poi-ooxml</artifactId>  
  11.     <version>3.14</version>  
  12. </dependency>  

POIUtil工具类的代码:

[java] view plain copy
  1. package com.cn.util;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import org.apache.log4j.Logger;  
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  11. import org.apache.poi.ss.usermodel.Cell;  
  12. import org.apache.poi.ss.usermodel.Row;  
  13. import org.apache.poi.ss.usermodel.Sheet;  
  14. import org.apache.poi.ss.usermodel.Workbook;  
  15. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  16. import org.springframework.web.multipart.MultipartFile;  
  17. /** 
  18.  * excel读写工具类 
  19.  * @author sun.kai 
  20.  * 2016年8月21日 
  21.  */  
  22. public class POIUtil {  
  23.     private static Logger logger  = Logger.getLogger(POIUtil.class);  
  24.     private final static String xls = "xls";  
  25.     private final static String xlsx = "xlsx";  
  26.       
  27.     /** 
  28.      * 读入excel文件,解析后返回 
  29.      * @param file 
  30.      * @throws IOException  
  31.      */  
  32.     public static List<String[]> readExcel(MultipartFile file) throws IOException{  
  33.         //检查文件  
  34.         checkFile(file);  
  35.         //获得Workbook工作薄对象  
  36.         Workbook workbook = getWorkBook(file);  
  37.         //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回  
  38.         List<String[]> list = new ArrayList<String[]>();  
  39.         if(workbook != null){  
  40.             for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
  41.                 //获得当前sheet工作表  
  42.                 Sheet sheet = workbook.getSheetAt(sheetNum);  
  43.                 if(sheet == null){  
  44.                     continue;  
  45.                 }  
  46.                 //获得当前sheet的开始行  
  47.                 int firstRowNum  = sheet.getFirstRowNum();  
  48.                 //获得当前sheet的结束行  
  49.                 int lastRowNum = sheet.getLastRowNum();  
  50.                 //循环除了第一行的所有行  
  51.                 for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){  
  52.                     //获得当前行  
  53.                     Row row = sheet.getRow(rowNum);  
  54.                     if(row == null){  
  55.                         continue;  
  56.                     }  
  57.                     //获得当前行的开始列  
  58.                     int firstCellNum = row.getFirstCellNum();  
  59.                     //获得当前行的列数  
  60.                     int lastCellNum = row.getPhysicalNumberOfCells();  
  61.                     String[] cells = new String[row.getPhysicalNumberOfCells()];  
  62.                     //循环当前行  
  63.                     for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
  64.                         Cell cell = row.getCell(cellNum);  
  65.                         cells[cellNum] = getCellValue(cell);  
  66.                     }  
  67.                     list.add(cells);  
  68.                 }  
  69.             }  
  70.             workbook.close();  
  71.         }  
  72.         return list;  
  73.     }  
  74.     public static void checkFile(MultipartFile file) throws IOException{  
  75.         //判断文件是否存在  
  76.         if(null == file){  
  77.             logger.error("文件不存在!");  
  78.             throw new FileNotFoundException("文件不存在!");  
  79.         }  
  80.         //获得文件名  
  81.         String fileName = file.getOriginalFilename();  
  82.         //判断文件是否是excel文件  
  83.         if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){  
  84.             logger.error(fileName + "不是excel文件");  
  85.             throw new IOException(fileName + "不是excel文件");  
  86.         }  
  87.     }  
  88.     public static Workbook getWorkBook(MultipartFile file) {  
  89.         //获得文件名  
  90.         String fileName = file.getOriginalFilename();  
  91.         //创建Workbook工作薄对象,表示整个excel  
  92.         Workbook workbook = null;  
  93.         try {  
  94.             //获取excel文件的io流  
  95.             InputStream is = file.getInputStream();  
  96.             //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象  
  97.             if(fileName.endsWith(xls)){  
  98.                 //2003  
  99.                 workbook = new HSSFWorkbook(is);  
  100.             }else if(fileName.endsWith(xlsx)){  
  101.                 //2007  
  102.                 workbook = new XSSFWorkbook(is);  
  103.             }  
  104.         } catch (IOException e) {  
  105.             logger.info(e.getMessage());  
  106.         }  
  107.         return workbook;  
  108.     }  
  109.     public static String getCellValue(Cell cell){  
  110.         String cellValue = "";  
  111.         if(cell == null){  
  112.             return cellValue;  
  113.         }  
  114.         //把数字当成String来读,避免出现1读成1.0的情况  
  115.         if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){  
  116.             cell.setCellType(Cell.CELL_TYPE_STRING);  
  117.         }  
  118.         //判断数据的类型  
  119.         switch (cell.getCellType()){  
  120.             case Cell.CELL_TYPE_NUMERIC: //数字  
  121.                 cellValue = String.valueOf(cell.getNumericCellValue());  
  122.                 break;  
  123.             case Cell.CELL_TYPE_STRING: //字符串  
  124.                 cellValue = String.valueOf(cell.getStringCellValue());  
  125.                 break;  
  126.             case Cell.CELL_TYPE_BOOLEAN: //Boolean  
  127.                 cellValue = String.valueOf(cell.getBooleanCellValue());  
  128.                 break;  
  129.             case Cell.CELL_TYPE_FORMULA: //公式  
  130.                 cellValue = String.valueOf(cell.getCellFormula());  
  131.                 break;  
  132.             case Cell.CELL_TYPE_BLANK: //空值   
  133.                 cellValue = "";  
  134.                 break;  
  135.             case Cell.CELL_TYPE_ERROR: //故障  
  136.                 cellValue = "非法字符";  
  137.                 break;  
  138.             default:  
  139.                 cellValue = "未知类型";  
  140.                 break;  
  141.         }  
  142.         return cellValue;  
  143.     }  
  144. }  

POIUtil.readExcel方法读取excel文件后,把一行中的值按先后顺序组成一个数组,所有的行作为一个集合返回。我们可以在代码中循环这个集合,把数组赋值到实体类对象中。

我在前台用form表单提交file文件,因为用的SpringMVC框架,后台用MultipartFile接收,代码如下:

[java] view plain copy
  1. /** 
  2.  * 读取excel文件中的用户信息,保存在数据库中 
  3.  * @param excelFile 
  4.  */  
  5. @RequestMapping("/readExcel")  
  6. public void readExcel(@RequestParam(value = "excelFile") MultipartFile excelFile,HttpServletRequest req,HttpServletResponse resp){  
  7.     Map<String, Object> param = new HashMap<String, Object>();  
  8.     List<User> allUsers = new ArrayList<User>();  
  9.     try {  
  10.         List<String[]> userList = POIUtil.readExcel(excelFile);  
  11.         for(int i = 0;i<userList.size();i++){  
  12.           String[] users = userList.get(i);  
  13.           User user = new User();  
  14.           user.setUserName(users[0]);  
  15.           user.setPassword(users[1]);  
  16.           user.setAge(Integer.parseInt(users[2]));  
  17.           allUsers.add(user);  
  18.          }  
  19.        } catch (IOException e) {  
  20.         logger.info("读取excel文件失败", e);  
  21.        }  
  22.      param.put("allUsers", allUsers);  
  23.      this.userService.insertUsers(param);  
  24. }  

调用的service层方法就不贴代码了,下面就是往数据库插入数据了。

excel文件内容:

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多