excel模板批量导入数据

来源:互联网 发布:mac磨皮插件怎么安装 编辑:程序博客网 时间:2024/05/18 02:14

ssh框架

前端 easyUI封装后的框架   

文件上传 ajaxfileupload框架

Dto和实体、Dao方法省略


前端页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="gk" uri="http://***/tags/core"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
</head>
<body>
<script src="/js/ajaxfileupload.js"></script>

<form method="post" enctype="multipart/form-data">
<div style="margin: 50px 50px 15px 180px">
<input id="uploadExcel" type="text" name="uploadExcel"
style="width: 50%">
</div>
<!-- ******  以下生成页面按钮  ****** -->

<button id="save" action="ajaxrequest"
onstart="beforeResourceSave()" value="导入" iconCls="gk-save"
validate="true" />

<script type="text/javascript">
jQuery("#uploadExcel").filebox({
buttonText: '选择文件', 
    buttonAlign: 'left' 
})
function beforeResourceSave(){
var fileName = jQuery("input[name=uploadExcel]")[0].files[0];
var fileid= jQuery("input[name='uploadExcel']").attr("id");
                 //进行基本校验  
                 if(fileName==undefined){     
                jQuery.messager.alert('提示','请选择上传文件!!','info');   
                 }else{  
                //对文件格式进行校验  
                var index = fileName.name.lastIndexOf(".");
                var ext = fileName.name.substring(index + 1,fileName.name.length);
                  //设置显示配置
                 var messageOpts = {
                  "closeButton" : true,//是否显示关闭按钮
                  "debug" : false,//是否使用debug模式
                  "positionClass" : "toast-center-center",//弹出窗的位置
                  "onclick" : null,
                  "showDuration" : "300",//显示的动画时间
                  "hideDuration" : "1000",//消失的动画时间
                  "timeOut" : "5000",//展现时间
                  "extendedTimeOut" : "1000",//加长展示时间
                  "showEasing" : "swing",//显示时的动画缓冲方式
                  "hideEasing" : "linear",//消失时的动画缓冲方式
                  "showMethod" : "fadeIn",//显示时的动画方式
                  "hideMethod" : "fadeOut" //消失时的动画方式
                  };
                  toastr.options = messageOpts;
                    if(ext=="xls"||ext=="xlsx"){ 
                    jQuery.ajaxFileUpload({  
                             url: "/contr/saveExcel.do",   
                             type: 'post',  
                             secureuri: false,   
                             fileElementId: fileid,  
                             dataType: 'json',   
                             success: function(date){    
                                 if(date.success){
                                toastr.success("保存成功");
                                 }else{
                                toastr.error("保存失败");
                                 }
                             }  
                         });  
                    }else{  
                    jQuery.messager.alert('提示','请选择Excel文件!','info');   
                    jQuery('#uploadExcel').filebox('setValue','');
                    }  
                 }    
}
</script>
</form>
</body>
</html>



Controller代码:


@Controller
@RequestMapping("contr")
public class Controller { 

@Autowired
private  ssService  ssService;


/**
* 导入Excel表格
*  @return
*/
@RequestMapping("saveExcel.do")
@ResponseBody
    public String saveExcel(final JsonModel jm,final MultipartHttpServletRequest request,final HttpServletResponse response)  { 

//获取上传的文件
MultipartFile multipartFile = request.getFile("uploadExcel");
String filename = multipartFile.getOriginalFilename();
System.out.println(filename);
long size=multipartFile.getSize();
        if(filename==null || ("").equals(filename) && size==0) { 
        throw new AppException("请选择excel文件"); 
        }
         //处理Excel读取数据         参数:文件名,Excel文件
        List<Dto> dtoList = this.ssService.excelService(filename,multipartFile); 
         if(DtoList!=null){
for(Dto dto:dtoList) {

this.ssService.save(dto);

}
         }else{
        JsonModel model = new JsonModel();
        model.setSuccess(false);
        model.setErrorMessage("excel数据保存失败");
        return model.toJSON();
         }
         System.out.println(jm.toJSON());
         return jm.toJSON();
}


Service接口:

public interface ssService extends BaseService{

/**
* 读取导入的excel文件
* @param filename
* @param multipartFile
* @return
*/
List<Dto> excelService(String filename,MultipartFile multipartFile);

/**保存

* @param

*/
void save(Dto  dto);


}


Service实现类

@Service
public class ssServiceImpl extends BaseServiceImpl implements ssService {

@Autowired
private DtoDao dtoDao;

public void save(Dto  dto){

dtoDao.save(dto);//调用Dao方法保存

}

public  List<Dto> excelService(String filename,MultipartFile multipartFile){

//创建处理EXCEL
        ReadExcel readExcel=new ReadExcel();
        //解析excel,获取信息集合        
        List<Dto>
dtoList;
try {
dtoList = readExcel.getExcelInfo(filename ,multipartFile);
} catch (Exception e) {
throw new AppException("导入excel失败");
}
        if(!DtoList.isEmpty()){
        return dtoList;
        }
        return null;

}

}



处理EXCEL类


public class ReadExcel {
//总行数
    private int totalRows = 0;  
    //总条数
    private int totalCells = 0; 
    //错误信息接收器
    private String errorMsg;
    //构造方法
    public ReadExcel(){}
    //获取总行数
    public int getTotalRows()  { return totalRows;} 
    //获取总列数
    public int getTotalCells() {  return totalCells;} 
    //获取错误信息
    public String getErrorInfo() { return errorMsg; }  
    
  /**
   * 验证EXCEL文件
   * @param filePath
   * @return
   */
  public boolean validateExcel(String filePath){
  if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){  
          throw new AppException("文件名不是Excel格式");  
      }  
      return true;
  }

  /**
   * 读EXCEL文件,获取信息集合
   * @param fielName
   * @return
   */
  public ListDto> getExcelInfo(String fileName,MultipartFile Mfile) throws Exception{
  //把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
      CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; 
      
      //获取本地存储路径
      String path="";
      String path1 = System.getProperties().getProperty("user.dir");//用户的当前工作目录
  String path2 = System.getProperties().getProperty("java.io.tmpdir");//默认的临时文件路径
  if(path2!=null) {
  path = path2;
  }else {
  path = path1;
  }
  System.out.println("path2::::"+path2);
      File file = new  File(path);
      //创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)
      if (!file.exists()) file.mkdirs();
      String name1 = path + new Date().getTime() + ".xlsx";
      System.out.println("name1:::"+name1);
      //新建一个文件
      File file1 = new File(name1); 
      //将上传的文件写入新建的文件中
      try {
          cf.getFileItem().write(file1); 
      } catch (Exception e) {
          e.printStackTrace();
      }
      //初始化信息的集合    
      List<Dto> dtoList=new ArrayList<Dto>();
      //初始化输入流
      InputStream is = null;  
      try{
         //验证文件名是否合格
         if(!validateExcel(fileName)){
             return null;
         }
         //根据文件名判断文件是2003版本还是2007版本
         boolean isExcel2003 = true; 
         if(isExcel2007(fileName)){
             isExcel2003 = false;  
         }
         //根据新建的文件实例化输入流
         is = new FileInputStream(file1);
         //根据excel里面的内容读取信息
         dtoList = getExcelInfo(is, isExcel2003); 
         is.close();
         
         // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
         if (file1.exists() && file1.isFile()) {
             if (file1.delete()) {
                 System.out.println("删除单个文件" + name1 + "成功!");
             } else {
                 System.out.println("删除单个文件" + name1 + "失败!");
             }
         } else {
             System.out.println("删除单个文件失败:" + name1 + "不存在!");
         }
     }catch(Exception e){
         e.printStackTrace();
     } finally{
         if(is !=null)
         {
             try{
                 is.close();
             }catch(IOException e){
                 is = null;    
                 e.printStackTrace();  
             }
         }
     } 
  
  return D104DtoList;
  }
  /**
   * 根据excel里面的内容读取客户信息
   * @param is 输入流
   * @param isExcel2003 excel是2003还是2007版本
   * @return
   * @throws IOException
   */
  public  List<Dto> getExcelInfo(InputStream is,boolean isExcel2003){
       List<Dto> dtoList=null;
       try{
           /** 根据版本选择创建Workbook的方式 */
           Workbook wb = null;
           //当excel是2003时
           if(isExcel2003){
               wb = new HSSFWorkbook(is); 
           }
           else{//当excel是2007时
               wb = new XSSFWorkbook(is); 
           }
           //读取Excel里面客户的信息
           dtoList=readExcelValue(wb);
       }
       catch (IOException e)  {  
           e.printStackTrace();  
       }  
       return dtoList;
  }   

  /**
   * 读取Excel里面客户的信息
   * @param wb
   * @return
   */
  private List<Dto> readExcelValue(Workbook wb){ 
      //得到第一个shell  
       Sheet sheet=wb.getSheetAt(0);
       
      //得到Excel的行数
       this.totalRows=sheet.getPhysicalNumberOfRows();
       
      //得到Excel的列数(前提是有行数)
       if(totalRows>=1 && sheet.getRow(0) != null){
            this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
       }
       
       List<Dto> dtoList=new ArrayList<Dto>();
       Dto dto;            
      //循环Excel行数,从第二行开始 标题不入库
       for(int r=1;r<totalRows;r++){
           Row row = sheet.getRow(r);
           if (row == null) 
           continue;
         dto = new Dto();
           //循环Excel的列
           for(int c = 0; c <this.totalCells; c++){    
               Cell cell = row.getCell(c);
               if (null != cell){
                   if(c==0){//读取格子
                   dto.setDto01(cell.getStringCellValue());//名称
                   }else if(c==1){
                   dto.setDto02(cell.getStringCellValue());//简称
                   }else if(c==2){
                   if(cell!=null) {
                   cell.setCellType(Cell.CELL_TYPE_STRING);   //Excel 中 number类型数据要先转为String类型在读取
                   dto.setDto03(cell.getStringCellValue());//编号
                   }
                   }else if(c==3){
                   dto.setDto04(cell.getStringCellValue());//地址
                   }else if(c==4){
                   dto.setDto05(cell.getStringCellValue());//负责人
                   }
                   }
               }
           }
            //添加
            dtoList.add(dto);
       }
       return dtoList;
  }
  
  
  
  
  
  


  // @描述:是否是2003的excel,返回true是2003 
  public static boolean isExcel2003(String filePath)  {  
       return filePath.matches("^.+\\.(?i)(xls)$");  
   }  
 
  //@描述:是否是2007的excel,返回true是2007 
  public static boolean isExcel2007(String filePath)  {  
       return filePath.matches("^.+\\.(?i)(xlsx)$");  
   } 
























原创粉丝点击