欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java解析Excel文件并把数据存入数据库

程序员文章站 2024-02-21 16:35:10
前段时间做一个小项目,为了同时存储多条数据,其中有一个功能是解析excel并把其中的数据存入对应数据库中。花了两天时间,不过一天多是因为用了"upload"关键字作为url...

前段时间做一个小项目,为了同时存储多条数据,其中有一个功能是解析excel并把其中的数据存入对应数据库中。花了两天时间,不过一天多是因为用了"upload"关键字作为url从而导致总报同一个错,最后在同学的帮助下顺利解决,下面我把自己用"poi"解析的方法总结出来供大家参考(我用的是spingmvc和hibernate框架)。

1.web.xml中的配置文件

web.xml中的配置文件就按照这种方式写,只需要把"application.xml"换成你的配置文件名即可

<!--文件上传对应的配置文件-->
  <listener> 
    <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> 
  </listener>
  <context-param> 
    <param-name>contextconfiglocation</param-name> 
    <param-value>classpath:application.xml</param-value> 
  </context-param>

2.application.xml的配置文件(固定写发)

在这个配置文件中你还可以规定上传文件的格式以及大小等多种属性限制

<!-- 定义文件上传解析器 --> 
  <bean id="multipartresolver" 
    class="org.springframework.web.multipart.commons.commonsmultipartresolver">   
   </bean>

3.文件上传的前端html

注意:

1.enctype="multipart/form-data" 必须写,封装表单

2.method="post",提交方式必须为"post"提交

3.action="${text}/uploadfile", "uploadfile"切记不要写成"upload",否则你找到世界末日也不会找到哪里有问题(本人因为这个折腾了一天多时间)。

<form name="fileupload" enctype="multipart/form-data" action="${text}/uploadfile" method="post">
<p style="font-size:16px;">请选择正确的excel文件上传</p>
<input id="txt" class="input" type="text" disabled="disabled" value="文件域" name="txt">
 <input class="liulan" type="button" onclick="file.click()" size="30" value="上传文件" onmousemove="file.style.pixelleft=event.x-60;file.style.pixeltop=this.offsettop;">
<input id="file1" class="files" type="file" hidefocus="" size="1" style="height:26px;" name="file" onchange="txt.value=this.value">
<br/><input type="button" onclick="checksuffix();" value="提交上传" style="height:26px;width:100px">
 <p style="color:red;">支持的excel格式为:xls、xlsx、xlsb、xlsm、xlst!</p>
</form>

4.验证上传文件的格式

//用于验证文件扩展名的正则表达式
function checksuffix(){
 var name = document.getelementbyid("txt").value;
 var strregex = "(.xls|.xlsx|.xlsb|.xlsm|.xlst)$"; 
 var re=new regexp(strregex);
 if (re.test(name.tolowercase())){
  alert("上传成功");
  document.fileupload.submit();
 } else{
  alert("文件名不合法"); 
 }
}

5.dao层的接口和实现类

package com.gxxy.team1.yyd.dao;
public interface ifileuploaddao {
   public void save(object o);
 }
package com.gxxy.team1.yyd.dao.impl;

import org.hibernate.session;
import org.hibernate.sessionfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.repository;

import com.gxxy.team1.yyd.dao.ifileuploaddao;
@repository
public class fileuploaddaoimpl implements ifileuploaddao {
  @autowired
  private sessionfactory sessionfactory;
  private session getsession() {
    session session = sessionfactory.getcurrentsession();
    return session;
  }
  @override
  public void save(object o) {
    
    getsession().save(o);
  }

}

6.service层的接口和实现类

package com.gxxy.team1.yyd.service;

import java.util.list;

public interface ifileuploadservice {
  public list<string[]> readexcel(string path);
  public void save(object o);
}

package com.gxxy.team1.yyd.service.impl;

import java.io.file;
import java.io.fileinputstream;
import java.text.simpledateformat;
import java.util.arraylist;
import java.util.list;

import org.apache.poi.ss.usermodel.cell;
import org.apache.poi.ss.usermodel.dateutil;
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.gxxy.team1.yyd.dao.ifileuploaddao;
import com.gxxy.team1.yyd.service.ifileuploadservice;
@service
public class fileuploadserviceimpl implements ifileuploadservice {
  @autowired
  private ifileuploaddao filedao;
  @override
  public list<string[]> readexcel(string path) { 
      simpledateformat fmt = new simpledateformat("yyyy-mm-dd"); 
      list<string[]> list = null;
      try { 
        //同时支持excel 2003、2007 
        file excelfile = new file(path); //创建文件对象 
        fileinputstream is = new fileinputstream(excelfile); //文件流 
        workbook workbook = workbookfactory.create(is); //这种方式 excel 2003/2007/2010 都是可以处理的 
        int sheetcount = workbook.getnumberofsheets(); //sheet的数量
       //存储数据容器 
        list = new arraylist<string[]>();
        //遍历每个sheet 
        for (int s = 0; s < sheetcount; s++) { 
          sheet sheet = workbook.getsheetat(s); 
          int rowcount = sheet.getphysicalnumberofrows(); //获取总行数      
          //遍历每一行 
          for (int r = 0; r < rowcount; r++) { 
            row row = sheet.getrow(r); 
            int cellcount = row.getphysicalnumberofcells(); //获取总列数 
           //用来存储每行数据的容器 
            string[] model = new string[cellcount-1];
            //遍历每一列 
            for (int c = 0; c < cellcount; c++) { 
              cell cell = row.getcell(c); 
              int celltype = cell.getcelltype();
              
              if(c == 0) continue;//第一列id为标志列,不解析
              
              string cellvalue = null; 
              switch(celltype) { 
                case cell.cell_type_string: //文本 
                  cellvalue = cell.getstringcellvalue(); 
                  //model[c-1] = cellvalue;
                  break; 
                case cell.cell_type_numeric: //数字、日期 
                  if(dateutil.iscelldateformatted(cell)) { 
                    cellvalue = fmt.format(cell.getdatecellvalue()); //日期型 
                    //model[c-1] = cellvalue;
                  } 
                  else { 
                    
                    cellvalue = string.valueof(cell.getnumericcellvalue()); //数字 
                    //model[c-1] = cellvalue;                  
                  } 
                  break; 
                case cell.cell_type_boolean: //布尔型 
                  cellvalue = string.valueof(cell.getbooleancellvalue()); 
                  break; 
                case cell.cell_type_blank: //空白 
                  cellvalue = cell.getstringcellvalue(); 
                  break; 
                case cell.cell_type_error: //错误 
                  cellvalue = "错误"; 
                  break; 
                case cell.cell_type_formula: //公式 
                  cellvalue = "错误"; 
                  break; 
                default: 
                  cellvalue = "错误"; 
                  
              } 
              system.out.print(cellvalue + "  "); 
              
              model[c-1] = cellvalue;
            } 
            //model放入list容器中 
            list.add(model);
            system.out.println(); 
          } 
        } 
        is.close();     
      } 
      catch (exception e) { 
        e.printstacktrace(); 
      }
      
      return list;  
    }
  @override
  public void save(object o) {
    filedao.save(o);
  } 
  }

7.controller层实现

//文件上传方法
  @requestmapping("/uploadfile")
  public string upload(@requestparam(value = "file", required = false) multipartfile file, httpservletrequest request, modelmap model,model mod) throws exception {
    string path = request.getsession().getservletcontext().getrealpath("upload");
    system.out.println("文件路径:"+path);
    string originalfilename = file.getoriginalfilename();
    string type = file.getcontenttype();
    //originalfilename = uuid.randomuuid().tostring()+originalfilename;
    system.out.println("目标文件名称:"+originalfilename+",目标文件类型:"+type);
    file targetfile = new file(path,originalfilename );
    if (!targetfile.getparentfile().exists()) {
      targetfile.getparentfile().mkdirs();
    }else if (!targetfile.exists()) {
      targetfile.mkdirs();
    }
    // 获得上传文件的文件扩展名
    string subname = originalfilename.substring(originalfilename.lastindexof(".")+1);
    system.out.println("文件的扩展名:"+subname);
    
    try {
      file.transferto(targetfile);  
    } catch (exception e) {
      e.printstacktrace();
    }
    fileuploadserviceimpl fileup = new fileuploadserviceimpl();
    string rootpath = path + file.separator + originalfilename;
    list<string[]> excellist = fileup.readexcel(rootpath);
    int len = excellist.size();
    system.out.println("集合的长度为:"+len);
    for (int i = 0; i < len; i++) {
      string[] fields = excellist.get(i);
      simpledateformat format = new simpledateformat("yyyy-mm-dd");
      string sampleno = fields[0];
  
      double valueof = double.valueof(fields[1]);
      int sampletype = valueof.intvalue(); //double转int
      
      string createtime = fields[2];
      date createtime1 = format.parse(createtime);  
      string name = fields[3];
      string pid = fields[4];
      string hospitalname = fields[5];
      string cellphone = fields[6];
      sample sample = new sample(sampleno, sampletype, createtime1, name, pid);
      patient patient = new patient(hospitalname, cellphone);
      fileservice.save(sample);
      fileservice.save(patient);    
    }  
    //model.addattribute("fileurl", request.getcontextpath()+"/upload/"+originalfilename);
    
    string username = (string) request.getsession().getattribute("username");
    list<list<menu>> power = powerservice.power(username);
    mod.addattribute("list", power);
    return "redirect:/ yyd";
  }

以上这7个部分就是我实现解析excel文件并存入数据库的全部代码。希望对大家的学习有所帮助,也希望大家多多支持。