标签:mysql hibernate struts spring 项目实战
上次我们使用POI技术完成了用户列表的打印工作,下面我们来完成用户列表Excel文件的导入。<input type="button" value="导出" class="s_button" onclick="doExportExcel()"/> <input name="userExcel" type="file"/>我们为这个按钮设置一个点击事件,使用js让其链接到我们的导入路径,从而跳转相应的Action进行导入工作:
//导入列表
function doImportExcel(){
document.forms[0].action="${basePath}tax/user_importExcel.action";
document.forms[0].submit();
}//导入用户列表
public String importExcel(){
//1、获取excel文件
if(userExcel !=null){
//是否是excel
if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){
//2、导入
userService.importExcel(userExcel,userExcelFileName);
}
}
return "list";
}
//前面要加这三个属性,以及get和set方法
private File userExcel;
private String userExcelContantType;
private String userExcelFileName;
@Override
public void importExcel(File userExcel, String userExcelFileName) {
try {
FileInputStream fileInputStream = new FileInputStream(userExcel);
//判断是否是03版本的Excel(还是07的)
boolean is03Excel = userExcelFileName.matches("^.+\\.(?i)(xls)$");
//1、读取工作簿
Workbook workbook = is03Excel ? new HSSFWorkbook(fileInputStream)
: new XSSFWorkbook(fileInputStream);
//2、读取工作表
Sheet sheet=workbook.getSheetAt(0);
//3、读取行
if(sheet.getPhysicalNumberOfRows()>2){
User user=null;
for (int i = 2; i < sheet.getPhysicalNumberOfRows(); i++) {
//4、读取单元格
Row row=sheet.getRow(i);
user=new User();
//用户名
Cell cell1=row.getCell(0);
user.setName(cell1.getStringCellValue());
//账号
Cell cell2=row.getCell(1);
user.setAccount(cell2.getStringCellValue());
//所属部门
Cell cell3=row.getCell(2);
user.setDept(cell3.getStringCellValue());
//性别
Cell cell4=row.getCell(3);
user.setGender(cell4.getStringCellValue().equals("男"));
//电子邮箱
Cell cell5=row.getCell(4);
user.setEmail(cell5.getStringCellValue());
//导入用户的初始密码为123456
user.setPassword("123456");
//默认用户状态为有效
user.setState(User.USER_STATE_VALID);
//5、保存用户
userDao.save(user);
}
}
workbook.close();
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}我们重启服务器来测试一下:至此我们用户列表的“导入”和“导出”功能全部编写完毕!
转载请注明出处:http://blog.csdn.net/acmman/article/details/49401251
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:mysql hibernate struts spring 项目实战
原文地址:http://blog.csdn.net/acmman/article/details/49401251