基于struts2的导入excel文件到数据库操作

我们在做一些人员管理系统的时候,市场面临这样一个问题:信息量过大,一个一个的导入相当的费时、费力,直接选中要导入的人员信息的excel表显然是一个好方法。

addStudents.jsp

<p>请选择要导入的excel文件: </p>
<s:form action="student_addStudents.do" enctype="multipart/form-data" method="post">
 <s:file name="upload" label="上传文件" id="filePath"></s:file>
 <s:submit value="确定"></s:submit>
</s:form>

StudentAction

public String addStudents() throws Exception {
    // 获取request
HttpServletRequest request = ServletActionContext.getRequest();
FileInputStream fis = new FileInputStream(upload);
//获取服务器所在的磁盘绝对路径, 以便将上传文件保存到服务器所在的目录下, 这里是服务器应用所在的 upload目录下。
String destfile =ServletActionContext.getServletContext().getRealPath("/")+"upload/"+uploadFileName;
//System.out.println(destfile);
FileOutputStream fos = new FileOutputStream(destfile);
byte[] buffer = new byte[1024];
int len = 0;
while((len=fis.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
String filePath=destfile.replace('\\', '/');
//System.out.println(filePath);
try
{
Student s=new Student();  
InputStream in = new FileInputStream(filePath);
 POIFSFileSystem fs = new POIFSFileSystem(in);
 HSSFWorkbook wb = new HSSFWorkbook(fs);
 HSSFSheet sheet = wb.getSheetAt(0);
 in.close();
for(int i=1;i<=sheet.getLastRowNum();i++)
 {
   HSSFRow row=sheet.getRow(i) ; 
   HSSFCell cell0=row.getCell(0);
   HSSFCell cell1=row.getCell(1);
   HSSFCell cell2=row.getCell(2);
   HSSFCell cell3=row.getCell(3);
   String sid=cell0.getStringCellValue();
   s.setSid(sid);
   String sname=cell1.getStringCellValue();
   s.setSname(sname);
   String id=cell2.getStringCellValue();
   Classes classes=classesService.queryById(id);
   s.setClasses(classes);
   studentService.addStudent(s);
 }
}catch(Exception e)
{
e.printStackTrace();
}
return "addUI";
}

将需要导入的excel文件保存到服务器端,利用POI组件对excel文件进行逐行读取,每行读取完毕添加到数据库,继续下一行,直至所有数据完毕。

缺点:对excel文件的格式要进行提前规定,每一列的属性都必须和数据库对应。

  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值