我们在做一些人员管理系统的时候,市场面临这样一个问题:信息量过大,一个一个的导入相当的费时、费力,直接选中要导入的人员信息的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文件的格式要进行提前规定,每一列的属性都必须和数据库对应。