您的位置:首页 > Web前端

java从前端获取excel表并进行解析,将数据保存数据库

2018-03-21 16:12 483 查看
前端一个简单的上传例子
<div class="actionItems">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="functop" id="defaultOption"><h3>上传考试结果</h3></td>
</tr>
<tr id="openclose">
<td class="func">
<form id="fileform" enctype="multipart/form-data" action="file_upload.do" method="post">
<input type="file" name="descore" value="请选择文件"/>
<input type="submit" value="上传" />
</form>
</td>
</tr>
</tbody>
</table>

</div>
后台获取excel表格,并对excel表格进行解析保存
@RequestMapping(value = "/shopadmin/designer_examine_upload.do", method = RequestMethod.POST, produces = "application/json")
public void designerexamineupload(WebRequest webRequest,
ModelMap model, HttpServletRequest request,HttpServletResponse response) {
   String savePath =  request.getSession().getServletContext().getRealPath("/upload");
   File file = new File(savePath);
   if(!file.exists()&&!file.isDirectory()){
       System.out.println("目录或文件不存在!");
       file.mkdir();
   }
   //消息提示
   String message = "";
   try {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> iter = multipartRequest.getFileNames();
while (iter.hasNext()) {
String filefiled = iter.next();
MultipartFile multipartFile = multipartRequest.getFile(filefiled);
BufferedInputStream in = new BufferedInputStream(multipartFile.getInputStream());//获得文件输入流
String srcName = multipartFile.getOriginalFilename();
String ext = getExtention(srcName);//获得后缀名
String filename = UUID.randomUUID() +"." + ext;//生成新的文件名
File f = new File(savePath);
if(!f.exists()){
f.mkdirs();
}
new File(savePath).mkdirs();//如果路径存在就使用,不存在就创建
String filelocation = savePath + "/" + filename;//文件存放的绝对路径
this.SaveInputToFile(in, filelocation);//文件上传
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filelocation));
   //按名引用excel工作表
   //也可以用以下方式来获取excel的工作表,采用工作表的索引值
   XSSFSheet sheet = workbook.getSheetAt(0);
   XSSFRow row ;
   XSSFCell cell1,cell2;
   int rows=sheet.getLastRowNum();
   List<Map<String, Object>> l=new ArrayList<Map<String, Object>>();
   System.out.println(rows);
   for(int icount=1;icount<=rows;icount++){
    //System.out.println(icount);
           row = sheet.getRow(icount);
           cell1= row.getCell(0);
           cell2=row.getCell(1);
           cell1.setCellType(HSSFCell.CELL_TYPE_STRING); 
           cell2.setCellType(HSSFCell.CELL_TYPE_STRING); 
           String     shopname=(cell1.getStringCellValue()).trim();
           String score=(cell2.getStringCellValue()).trim();
           long shopid=jdbc.queryForObject("select id from biz_shop where shopname =?",new Object[]{shopname},Long.class);
           long levelid=jdbc.queryForObject("select id from biz_designer_examine_level where ? between"
            + " minpoints and maxpoints",new Object[]{Float.valueOf(score)},Long.class);
           List<DesignerExamine> dl=dao.find("from DesignerExamine where shopId=?",shopid);
           if(dl.size()>0){
            DesignerExamine d=dl.get(0);
           d.setCreatetime(new Date());
           d.setExamineLevelId(levelid);
           d.setPoints(Float.valueOf(score));
           d.setShopId(shopid);
           d.setShopName(shopname);
           dao.merge(d);
           }else{
            DesignerExamine d=new DesignerExamine();
           d.setCreatetime(new Date());
           d.setExamineLevelId(levelid);
           d.setPoints(Float.valueOf(score));
           d.setShopId(shopid);
           d.setShopName(shopname);
           dao.merge(d);
           }
   }
}
   } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       message = "文件上传失败";
   }
   try {
response.sendRedirect("/shopadmin/designer_examine.do");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获得文件后缀名的方法
public static String getExtention(String filename){
       String ext = null;
       int index = filename.lastIndexOf(".");//检索'.'在文件名字符串中的位置
       if(index > 0){
           ext = filename.substring(index + 1).toLowerCase();//获得后缀并返回
       }
       return ext;
}
private boolean SaveInputToFile(BufferedInputStream inBuff,String targetpath){
boolean re=false;
BufferedOutputStream outBuff = null;
try{
outBuff = new BufferedOutputStream(new FileOutputStream(targetpath));//获得输出流
byte[] b = new byte[4096];
int len;
while((len = inBuff.read(b)) != -1){
outBuff.write(b, 0, len);
}
outBuff.flush();
re=true;
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(inBuff != null)
inBuff.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(outBuff != null)
outBuff.close();
}catch(Exception e){
e.printStackTrace();
}
}
return re;
}

用到的解析Excel的jar包:poi-3.9-20121203.jar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐