Java POI 导入Excel以及解析Excel

来源:互联网 发布:3g网络和4g网络的速度 编辑:程序博客网 时间:2024/05/16 14:44

用的SSM框架,所需要的jar包如图所示:,链接地址:jar包下载  ,下面直接上代码。

1、ExcelUtil工具类

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <span style="color:#993399;"><span style="font-size:18px;color:#993399;">import java.text.DecimalFormat;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.Calendar;  
  4. import java.util.Date;  
  5. import java.util.regex.Matcher;  
  6. import java.util.regex.Pattern;  
  7.   
  8. import org.apache.poi.hssf.usermodel.HSSFCell;  
  9. import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
  10. import org.apache.poi.ss.usermodel.Cell;  
  11. import org.apache.poi.ss.usermodel.DateUtil;  
  12. import org.apache.poi.xssf.usermodel.XSSFCell;  
  13.   
  14. /** 
  15.  * Excel工具类 
  16.  * @author lp 
  17.  * 
  18.  */  
  19. public class ExcelUtil {  
  20.     public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";  
  21.     public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";  
  22.     public static final String EMPTY = "";  
  23.     public static final String POINT = ".";  
  24.     public static SimpleDateFormat sdf =   new SimpleDateFormat("yyyy/MM/dd");  
  25.     /** 
  26.      * 获得path的后缀名 
  27.      * @param path 
  28.      * @return 
  29.      */  
  30.     public static String getPostfix(String path){  
  31.         if(path==null || EMPTY.equals(path.trim())){  
  32.             return EMPTY;  
  33.         }  
  34.         if(path.contains(POINT)){  
  35.             return path.substring(path.lastIndexOf(POINT)+1,path.length());  
  36.         }  
  37.         return EMPTY;  
  38.     }  
  39.     /** 
  40.      * 单元格格式 
  41.      * @param hssfCell 
  42.      * @return 
  43.      */  
  44.     @SuppressWarnings({ "static-access""deprecation" })  
  45.     public static String getHValue(HSSFCell hssfCell){  
  46.          if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {  
  47.              return String.valueOf(hssfCell.getBooleanCellValue());  
  48.          } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {  
  49.              String cellValue = "";  
  50.              if(HSSFDateUtil.isCellDateFormatted(hssfCell)){                  
  51.                  Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue());  
  52.                  cellValue = sdf.format(date);  
  53.              }else{  
  54.                  DecimalFormat df = new DecimalFormat("#.##");  
  55.                  cellValue = df.format(hssfCell.getNumericCellValue());  
  56.                  String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());  
  57.                  if(strArr.equals("00")){  
  58.                      cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));  
  59.                  }    
  60.              }  
  61.              return cellValue;  
  62.          } else {  
  63.             return String.valueOf(hssfCell.getStringCellValue());  
  64.          }  
  65.     }  
  66.     /** 
  67.      * 单元格格式 
  68.      * @param xssfCell 
  69.      * @return 
  70.      */  
  71.     public static String getXValue(XSSFCell xssfCell){  
  72.          if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {  
  73.              return String.valueOf(xssfCell.getBooleanCellValue());  
  74.          } else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {  
  75.              String cellValue = "";  
  76.              if(XSSFDateUtil.isCellDateFormatted(xssfCell)){  
  77.                  Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());  
  78.                  cellValue = sdf.format(date);  
  79.              }else{  
  80.                  DecimalFormat df = new DecimalFormat("#.##");  
  81.                  cellValue = df.format(xssfCell.getNumericCellValue());  
  82.                  String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());  
  83.                  if(strArr.equals("00")){  
  84.                      cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));  
  85.                  }    
  86.              }  
  87.              return cellValue;  
  88.          } else {  
  89.             return String.valueOf(xssfCell.getStringCellValue());  
  90.          }  
  91.     }     
  92. /** 
  93.  * 自定义xssf日期工具类 
  94.  * @author lp 
  95.  * 
  96.  */  
  97. class XSSFDateUtil extends DateUtil{  
  98.     protected static int absoluteDay(Calendar cal, boolean use1904windowing) {    
  99.         return DateUtil.absoluteDay(cal, use1904windowing);    
  100.     }   
  101. }</span></span>  
2、ExcelRead:读取Excel类

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package com.ssm.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import org.apache.poi.hssf.usermodel.HSSFCell;  
  9. import org.apache.poi.hssf.usermodel.HSSFRow;  
  10. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  11. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  12. import org.apache.poi.xssf.usermodel.XSSFCell;  
  13. import org.apache.poi.xssf.usermodel.XSSFRow;  
  14. import org.apache.poi.xssf.usermodel.XSSFSheet;  
  15. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  16. import org.springframework.web.multipart.MultipartFile;  
  17. /** 
  18.  * 读取Excel 
  19.  * @author lp 
  20.  * 
  21.  */  
  22. public class ExcelRead {      
  23.     public int totalRows; //sheet中总行数  
  24.     public static int totalCells; //每一行总单元格数  
  25.     /** 
  26.      * read the Excel .xlsx,.xls 
  27.      * @param file jsp中的上传文件 
  28.      * @return 
  29.      * @throws IOException  
  30.      */  
  31.     public List<ArrayList<String>> readExcel(MultipartFile file) throws IOException {  
  32.         if(file==null||ExcelUtil.EMPTY.equals(file.getOriginalFilename().trim())){  
  33.             return null;  
  34.         }else{  
  35.             String postfix = ExcelUtil.getPostfix(file.getOriginalFilename());  
  36.             if(!ExcelUtil.EMPTY.equals(postfix)){  
  37.                 if(ExcelUtil.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){  
  38.                     return readXls(file);  
  39.                 }else if(ExcelUtil.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){  
  40.                     return readXlsx(file);  
  41.                 }else{                    
  42.                     return null;  
  43.                 }  
  44.             }  
  45.         }  
  46.         return null;  
  47.     }  
  48.     /** 
  49.      * read the Excel 2010 .xlsx 
  50.      * @param file 
  51.      * @param beanclazz 
  52.      * @param titleExist 
  53.      * @return 
  54.      * @throws IOException  
  55.      */  
  56.     @SuppressWarnings("deprecation")  
  57.     public List<ArrayList<String>> readXlsx(MultipartFile file){  
  58.         List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();  
  59.         // IO流读取文件  
  60.         InputStream input = null;  
  61.         XSSFWorkbook wb = null;  
  62.         ArrayList<String> rowList = null;  
  63.         try {  
  64.             input = file.getInputStream();  
  65.             // 创建文档  
  66.             wb = new XSSFWorkbook(input);                         
  67.             //读取sheet(页)  
  68.             for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){  
  69.                 XSSFSheet xssfSheet = wb.getSheetAt(numSheet);  
  70.                 if(xssfSheet == null){  
  71.                     continue;  
  72.                 }  
  73.                 totalRows = xssfSheet.getLastRowNum();                
  74.                 //读取Row,从第二行开始  
  75.                 for(int rowNum = 1;rowNum <= totalRows;rowNum++){  
  76.                     XSSFRow xssfRow = xssfSheet.getRow(rowNum);  
  77.                     if(xssfRow!=null){  
  78.                         rowList = new ArrayList<String>();  
  79.                         totalCells = xssfRow.getLastCellNum();  
  80.                         //读取列,从第一列开始  
  81.                         for(int c=0;c<=totalCells+1;c++){  
  82.                             XSSFCell cell = xssfRow.getCell(c);  
  83.                             if(cell==null){  
  84.                                 rowList.add(ExcelUtil.EMPTY);  
  85.                                 continue;  
  86.                             }                             
  87.                             rowList.add(ExcelUtil.getXValue(cell).trim());  
  88.                         }                                                 
  89.                     }  
  90.                 }  
  91.             }  
  92.             return list;  
  93.         } catch (IOException e) {             
  94.             e.printStackTrace();  
  95.         } finally{  
  96.             try {  
  97.                 input.close();  
  98.             } catch (IOException e) {  
  99.                 e.printStackTrace();  
  100.             }  
  101.         }  
  102.         return null;  
  103.           
  104.     }  
  105.     /** 
  106.      * read the Excel 2003-2007 .xls 
  107.      * @param file 
  108.      * @param beanclazz 
  109.      * @param titleExist 
  110.      * @return 
  111.      * @throws IOException  
  112.      */  
  113.     public List<ArrayList<String>> readXls(MultipartFile file){   
  114.         List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();  
  115.         // IO流读取文件  
  116.         InputStream input = null;  
  117.         HSSFWorkbook wb = null;  
  118.         ArrayList<String> rowList = null;  
  119.         try {  
  120.             input = file.getInputStream();  
  121.             // 创建文档  
  122.             wb = new HSSFWorkbook(input);                         
  123.             //读取sheet(页)  
  124.             for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){  
  125.                 HSSFSheet hssfSheet = wb.getSheetAt(numSheet);  
  126.                 if(hssfSheet == null){  
  127.                     continue;  
  128.                 }  
  129.                 totalRows = hssfSheet.getLastRowNum();                
  130.                 //读取Row,从第二行开始  
  131.                 for(int rowNum = 1;rowNum <= totalRows;rowNum++){  
  132.                     HSSFRow hssfRow = hssfSheet.getRow(rowNum);  
  133.                     if(hssfRow!=null){  
  134.                         rowList = new ArrayList<String>();  
  135.                         totalCells = hssfRow.getLastCellNum();  
  136.                         //读取列,从第一列开始  
  137.                         for(short c=0;c<=totalCells+1;c++){  
  138.                             HSSFCell cell = hssfRow.getCell(c);  
  139.                             if(cell==null){  
  140.                                 rowList.add(ExcelUtil.EMPTY);  
  141.                                 continue;  
  142.                             }                             
  143.                             rowList.add(ExcelUtil.getHValue(cell).trim());  
  144.                         }          
  145.                         list.add(rowList);  
  146.                     }                     
  147.                 }  
  148.             }  
  149.             return list;  
  150.         } catch (IOException e) {             
  151.             e.printStackTrace();  
  152.         } finally{  
  153.             try {  
  154.                 input.close();  
  155.             } catch (IOException e) {  
  156.                 e.printStackTrace();  
  157.             }  
  158.         }  
  159.         return null;  
  160.     }  
  161. }  
3、Controller

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <span style="color:#993399;"><pre name="code" class="java"><span style="color:#993399;">/** 
  2.      * 转到Excel上传页面 
  3.      * @return 
  4.      * @author lp 
  5.      */  
  6.     @RequestMapping(value="/read")  
  7.     public String addExcel(){  
  8.         return "baseInfo/testExcel";  
  9.     }  
  10. /** 
  11.      * 读取Excel数据到数据库 
  12.      * @param file 
  13.      * @param request 
  14.      * @return 
  15.      * @throws IOException 
  16.      * @author lp 
  17.      */  
  18.     @RequestMapping(value="/readExcel")   
  19.     public ModelAndView readExcel(@RequestParam(value="excelFile") MultipartFile file,HttpServletRequest request,HttpSession session) throws IOException{  
  20.         ModelAndView mv = new ModelAndView();  
  21.         //判断文件是否为空  
  22.         if(file == null){  
  23.             mv.addObject("msg""failed");  
  24.             mv.setViewName("excel_result");  
  25.             return mv;  
  26.         }  
  27.                 String name = file.getOriginalFilename();  
  28.         long size = file.getSize();  
  29.         if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){  
  30.             mv.addObject("msg""failed");  
  31.             mv.setViewName("excel_result");  
  32.             return mv;  
  33.         }  
  34.         //读取Excel数据到List中  
  35.         List<ArrayList<String>> list = new ExcelRead().readExcel(file);  
  36.                 //list中存的就是excel中的数据,可以根据excel中每一列的值转换成你所需要的值(从0开始),如:  
  37.         User user = null;  
  38.         List<User> liseUser = new ArrayList<User>();  
  39.         for(ArrayList<String> arr:list){                        
  40.             user= new User();                         
  41.             user.setAuthor(list.get(0));//每一行的第一个单元格  
  42.             listUser.add(user);  
  43.         }  
  44.         if(userService.saveBatchInsert(listUser)){  
  45.             mv.addObject("msg""success");  
  46.         }else{  
  47.             mv.addObject("msg""failed");  
  48.         }                     
  49.         mv.setViewName("excel_result");  
  50.         return mv;  
  51.     }</span></span>  

4、jsp

(1)主页面添加“Excel导入”

<a href="JavaScript:addExcel();"><em>Excel导入</em></a>function addExcel(){ var dg = new $.dialog({title:'导入Excel',id:'excel',width:1000,height:400,iconTitle:false,cover:true,maxBtn:false,xButton:true,resize:false,page:'user/read.html',});dg.ShowDialog();}

(2)导入页面

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <body>  
  2.     <form action="readExcel.html" enctype="multipart/form-data" method="post" id="batchAdd" name="batchAdd" target="result" onsubmit="return check();>  
  3.         <div style="margin: 30px;">  
  4.         <div><input id="excel_file" type="file" name="excelFile" size="50"/>  
  5.     </form>  
  6.     <iframe name="result" id="result" src="about:blank" frameborder="0" width="0" height="0"></iframe>  
  7. </body>  
  8. </html>  
  9. <script type="text/javascript">  
  10.         var dg;  
  11.         $(document).ready(function(){             
  12.             dg = frameElement.lhgDG;  
  13.             dg.addBtn('ok','保存',function(){  
  14.             $("#batchAdd").submit();  
  15.             this.disabled=true;                       
  16.             });  
  17.         });  
  18.           
  19.         function success(){  
  20.             if(dg.curWin.document.forms[0]){  
  21.                 dg.curWin.document.forms[0].action = dg.curWin.location+"";  
  22.                 dg.curWin.document.forms[0].submit();  
  23.             }else{  
  24.                 dg.curWin.location.reload();  
  25.             }  
  26.             dg.cancel();  
  27.         }  
  28.           
  29.         function failed(){  
  30.             alert("上传失败!");  
  31.         }  
  32. </script>  
(3)提示页面

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <body>  
  2.     <script type="text/javascript">  
  3.         var msg = "${msg}";  
  4.         if(msg=="success" || msg==""){  
  5.             alert("保存成功");  
  6.             parent.success();  
  7.         }else{  
  8.             parent.failed();  
  9.         }  
  10.     </script>  
  11. </body>  
5、service层

service
boolean saveBatchInsert(List<User> listUser);

serviceimpl
@Transactional
public boolean saveBatchInsert(List<User> listUser){
boolean flag = false;
if(listBaseInfo != null){
userMapper.batchInsert(listUser);
flag = true;
}
return flag;
}

6、dao层

void batchInsert(List<User> list);

7、xml(oracle) 

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="false" keyProperty="Id">  
  2.         insert into baseinfo(ID,Name,Sex,Birth,IdCardNo,Address,Tel,Author,AddDate,Status)   
  3.         <foreach collection="list" item="item" index="index" separator="union all">  
  4.             (select  
  5.         <span style="white-space:pre">    </span>#{item.id,jdbcType=NUMERIC},  
  6.                #{item.name,jdbcType=VARCHAR},  
  7.                #{item.sex,jdbcType=CHAR},                
  8.                #{item.birth,jdbcType=DATE},  
  9.                #{item.idCardNo,jdbcType=CHAR},              
  10.                #{item.address,jdbcType=VARCHAR},                 
  11.                #{item.tel,jdbcType=VARCHAR},                
  12.                #{item.author,jdbcType=VARCHAR},  
  13.                #{item.addDate,jdbcType=DATE},  
  14.                #{item.status,jdbcType=CHAR}              
  15.             from dual)  
  16.         </foreach>              
  17.     </insert>  
 

Java POI 导入Excel并解析


导入Excel表的数据,主要包括web端上传部分和spring后端代码。

      1、Web页面代码

      <input type="file" name="uploadfile" id="uploadfile" >,注意form里需增加encType="multipart/form-data"

      2、spring后台接收

      参数接收中增加@RequestParam("excelFile")MultipartFile excelFile

      3、Excel文件解析

      核心代码如下:

     

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. try{  
  2.                     InputStream inputStream = excelFile.getInputStream();  
  3.                     POIFSFileSystem fs = new POIFSFileSystem(inputStream);  
  4.                     HSSFWorkbook workbook = new HSSFWorkbook(fs);  
  5.                     //XSSFWorkbook workbook = new XSSFWorkbook(fs);  
  6.                     
  7.   
  8.                     HSSFSheet sheet = workbook.getSheetAt(0);  
  9.                     int rowNum = sheet.getLastRowNum();// 行  
  10.                     int cellNum;  
  11.   
  12.                     HSSFRow row;  
  13.                     HSSFCell cell;  
  14.                     String value = "";  
  15.   
  16.                       
  17.                   for (int i = 1; i <= rowNum; i++) {  
  18.                       row = sheet.getRow(i);  
  19.                       cellNum = row.getLastCellNum();// 列  
  20.                       recStrb = new StringBuffer("");  
  21.   
  22.                       for (int j = 0; j < cellNum; j++) {//对一行的每个列进行解析  
  23.   
  24.                           cell = row.getCell((short) j);  
  25.                           cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  26.                           if(j == 0){  
  27.                               value = String.valueOf((int)cell.getNumericCellValue());//数字型的值  
  28.   
  29.                           }else if(j == 1){  
  30.                               value = String.valueOf((int)cell.getNumericCellValue());  
  31.   
  32.                           }else if(j == 2){//  
  33.                             value = cell.getStringCellValue();//字符型的值  
  34.   
  35.                           }else{  
  36.                                 
  37.                           }  
  38.   
  39.                         if (StringUtils.isEmpty(value)) {  
  40.                               recStrb.append("null, ");  
  41.                         } else {  
  42.                             recStrb.append("'" + value + "', ");//对取得的值进行处理  
  43.                         }  
  44.   
  45.                       }  
  46.   
  47.                       //数据的自定义处置  
  48.                       if (i > 0) {  
  49. //                        log.debug(recStrb.toString());  
  50.                           recStrb.append("'"+super_parts_code+"', ");  
  51.                           String strTemp = recStrb.toString();  
  52.                           strTemp = strTemp.substring(0,strTemp.lastIndexOf(","));  
  53.                           dataList.add(strTemp);  
  54.                       }  
  55.                   }