Java开发过程中,有些需求需要实现Excel导入功能,具体就是Excel导入数据直接操作数据库,先将Excel导入实现方法贴出。实现过程如下。
1、xml配置,本人使用较为成熟流行的ssm框架,即spring、springMvc、mybiats整合而成框架。所以需要在springMvc的xml配置中加入如下代码配置。这里非常重要
2、jsp页面配置,上传必须使用from表单,且表单必须添加属性enctype="multipart/form-data" οnsubmit="return check();"并在上传input中添加accept="xls/xlsx" size="50"。用于限制上传文件格式。
--%>
3、xml配置和jsp配置已经完成,现在就是后台代码(@RequestParam("filename") MultipartFile file这里的filename需与from表单中的input的name一致。MultipartFile 就是刚刚xml配置启动的。所以xml配置不可或缺。
/**
* excel批量导入
* @param file
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = "batchimport.do", method = RequestMethod.POST)
public String batchimport(@RequestParam("filename") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception{
// String a = "C:\Users\lg\Desktop\1.xlsx";
//获取路径
if(file==null) return null;
//文件名
String name=file.getOriginalFilename();
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload"+"\\"
+ file.getOriginalFilename();
long size=file.getSize();
if(name==null || ("").equals(name) && size==0) return null;
try {
InputStream in = file.getInputStream();
//调用Service,将数据插入Excel
int i=poiService.batchImport(filePath,file);
if(i>0){
String Msg ="导入成功";
avg();
request.getSession().setAttribute("msg",Msg);
}else{
String Msg ="导入失败";
request.getSession().setAttribute("msg",Msg);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
excel();
}
// return null;
return "forward:/jsp/excel/excel.jsp";
}
Service实现,将调用实现类。
/**
* excel倒库
* @param name
* @param file
* @return
*/
public int batchImport(String name,MultipartFile file);
Service实现类,调动实现方法。
/**
*批量导入
*/
public int batchImport(String name,MultipartFile file) {
//这个是Excel导入的实现工具类。但不是直接导入数据库
//是将Excel数据分解成能够导入数据库的数据。