日期:2014-05-16  浏览次数:20461 次

不懂就贴,知识积累。excel导入服务器以及导入到数据库 .
    最近项目有个需求把原来的数据(原来数据可导出excel)批量导入到新系统中,

我用了两种方法

1 servlet---->servletfileupload

      需要 commons-fileupload.jar 上传,commons-io.jar,jxl.jar  解析excel,mysql-connector-java-5.1.6-bin.jar,数据库

string uploadpath=this.getservletcontext().getrealpath("/");  //获取服务器根目录

matcher m = p.matcher(name);
       boolean result = m.find();
       if (result) {
        string filetype=m.group(1);
         if (m.group(1).endswith(".xls")==false) {
          throw new ioexception(name + ": wrong type");
         }
        }

我只是针对.xls文件类型



2 struts1   servletfileupload或者formbean

struts1 中  获取path  request.getsession().getservletcontext().getrealpath("/") ;或者 servlet.getservletcontext().getrealpath("/");





workbook workbook = workbook.getworkbook(new file(path));
     sheet sheet = workbook.getsheet(0);
     client user = new client();
    for(int j=2; j<sheet.getrows()-1; j++)
    {
      cell cell = sheet.getcell(13,j);
      user.setpassword(cell.getcontents());
      cell = sheet.getcell(31,j);
      user.setclientname(cell.getcontents());
      cell = sheet.getcell(28,j);
      user.setsex(cell.getcontents());
    }
   
    this.service.insertclient(user);



页面设置

formbean



<html:form action="file.do" enctype="multipart/form-data" >
        <table height="52" border="0" align="center" cellpadding="0" cellspacing="0">
          <tr align="center">
            <td width="160">excel路径:</td>
            <td width="198"> <html:file property="file"/> </td>
          </tr>
          <tr align="right">
            <td height="26" colspan="4"> <html:submit>导入到数据库</html:submit> </td>
          </tr>
        </table>
   </html:form>



<form name="filedo" id="filedo" method="post" enctype="multipart/form-data" action="insert.do">
   <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td>
            选择excel文件:<input name="x" size="40" type="file"/>&amp;nbsp;&amp;nbsp;&amp;nbsp;<input name="upload" type="submit" value="导入到数据库"/>
      </td>
       </tr>
   </table>  
   </form>



struts的拦截器机制requestproccessor自己处理了文件上传,
如果是struts1,去掉formbean中的file对应属性,
如果是struts2,把
<filter>
<filter