不懂就贴,知识积累。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"/>   <input name="upload" type="submit" value="导入到数据库"/>
</td>
</tr>
</table>
</form>



struts的拦截器机制RequestProccessor自己处理了文件上传,
如果是struts1,去掉formbean中的file对应属性,
如果是struts2,把
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
里面的/*改成/*.action然后用普通的servlet代替action做上传处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值