SpringMVC+POI上传Excel2003/2007/2010文件并导入数据库

POI需要的jar包:

 <!-- poi3.9.jar -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <version>3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlbeans</groupId>
      <artifactId>xmlbeans</artifactId>
      <version>2.3.0</version>
    </dependency>

 

index.jsp

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>Insert title here</title> 
</head>
<script type="text/javascript">
    function uploadfile(){
     var pageForm=document.getElementById("pageForm");
     var upload=document.getElementById("upload").value;
     var st=upload.substring(1,2);
     if(upload==""){
         alert('文件路径不能为空');
     }else if(st!=":"){
        alert('文件路径不对');
        
     }else{
         pageForm.action="${pageContext.request.contextPath}/wenwu/path.action";
   pageForm.submit();  
    
     }
   
    }
</script>
<body>  

          
批量上传文件:  <br> 
请输入文件路径:<form id="pageForm"  method="post"> 
            <input type="text" name="upload"  id="upload"  />
            <input type="button"  value="多文件导入"  οnclick="uploadfile()"/>
           </form>          
</body> 
</html>  

 

WenwuController.java 

package com.lxtech.ssh.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.lxtech.ssh.entity.Wenwu;
import com.lxtech.ssh.service.WenwuService;


@Controller
@RequestMapping("/wenwu")
public class WenwuController {
 
 @Autowired 
 private WenwuService wenwuService; 
    /*
     * 提交文件路径
     */
    @RequestMapping(value = "/path")
    public String path(HttpServletRequest request) throws Exception{
     //程序开始时间
     long startTime = System.currentTimeMillis();
     //上传的文件夹路径
     String path = request.getParameter("upload");
     System.out.println(path);
     
        File file = new File(path);//File类型可以是文件也可以是文件夹
     File[] fileList = file.listFiles();//将该目录下的所有文件放置在一个File类型的数组中
     List<File> fileListNew = new ArrayList<File>();//新建一个文件集合
     for (int i = 0; i < fileList.length; i++) {
        if (fileList[i].isFile()) {//判断是否为文件
         fileListNew.add(fileList[i]);
        }
     }
     
     //遍历文件
     for(int i=0;i<fileListNew.size();i++){
      wenwuService.importExcel(fileListNew.get(i).getAbsolutePath());
  
           
     }
   
     long endTime = System.currentTimeMillis();    //获取结束时间

     System.out.println("程序运行时间:" + (endTime - startTime) + "ms");    //输出程序运行时间
     
  return "success";
  
    }
  
   
}

 

WenwuServiceImpl.java

 

package com.lxtech.ssh.service.impl;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

 

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

 

import com.lxtech.ssh.dao.WenwuDao;
import com.lxtech.ssh.entity.Wenwu;
import com.lxtech.ssh.service.WenwuService;
import com.lxtech.ssh.util.ExcelUtil;

 


@Service("wenwuService")
public class WenwuServiceImpl extends BaseServiceImpl<Integer, Wenwu> implements WenwuService {

 

 @Autowired
 private WenwuDao wenwuDao;
 /*
  * 同时支持Excel 2003、2007 
  */
 @Override
 public void importExcel(String path) {  
  //定义集合批量处理数据
  List<Wenwu> list=new ArrayList<Wenwu>();
  
        try {
           FileInputStream fis=new FileInputStream(new File(path));//文件流
             Workbook book=(Workbook) WorkbookFactory.create(fis);//这种方式 Excel 2003/2007/2010 都是可以处理的
            
            //遍历每个Sheet 
   for(int s=0;s<book.getNumberOfSheets();s++){
    Sheet sheet=book.getSheetAt(s);                       
                       
    //遍历每一行
    for(int r=1;r<=sheet.getLastRowNum();r++){
     Row row=sheet.getRow(r);
                       
     //获取第一行第一列的单元格的值
        Row row1=sheet.getRow(0);
        Cell cell1=row1.getCell(0);
       
        //实体属性初始化        
              String type=book.getSheetAt(s).getSheetName();
              String name = null;
        String property = null;
        String data = null;
        
        if(row!=null){
         if("名称".equals(ExcelUtil.getValue(cell1))){
       name = ExcelUtil.getValue(row.getCell(0));
             property = ExcelUtil.getValue(row.getCell(1));
             data = ExcelUtil.getValue(row.getCell(2));                          
             
      }else{          
       name = ExcelUtil.getValue(row.getCell(1));
             property = ExcelUtil.getValue(row.getCell(2));
             data = ExcelUtil.getValue(row.getCell(3));                 
      }
        }
       
        Wenwu wenwu =new Wenwu();
        wenwu.setType(type);
      wenwu.setName(name);
      wenwu.setProperty(property);
      wenwu.setData(data);
      
      if(property!=null && property!=""){ 
                list.add(wenwu);              
           }      
    }
   }
                        
        }catch (Exception e) {
   e.printStackTrace();
  }
        wenwuDao.saveAll(list);
  
 }
}

 

ExcelUtil.java

package com.lxtech.ssh.util;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;

public class ExcelUtil {
 public static String getValue(Cell cell) {
  String value = "";
        if(cell==null){
         value = "";
        }else{
         
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING://文本 
                value = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC://数字、日期  
                if (DateUtil.isCellDateFormatted(cell)) {//日期型  
                    Date date = cell.getDateCellValue();
                    if (date != null) {
                        value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                    } else {
                        value = "";
                    }
                } else {//数字型
                    value =new DecimalFormat("0").format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_FORMULA: //导入时如果为公式生成的数据则无值
                if (!cell.getStringCellValue().equals("")) {
                    value = cell.getStringCellValue();
                } else {
                    value = cell.getNumericCellValue() + "";
                }
                break;
            case Cell.CELL_TYPE_BLANK://空白
             value ="";
                break;
            case Cell.CELL_TYPE_ERROR://错误
                value = "";
                break;
            case Cell.CELL_TYPE_BOOLEAN://布尔型  
                value = (cell.getBooleanCellValue() == true ? "Y" : "N");
                break;
            default:
                value = "";
            }   
        }
        return value;
    }

}

 

 

 

 

 

 

 

 

 

 

  

转载于:https://www.cnblogs.com/qianxun-2017/p/7873501.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值