通过Excel读取数据,并将数据存至数据库

通过读取Excel内容,将内容先存至list集合,再将list集合内容循环遍历存至数据库。
在这里插入图片描述
具体实现如下:

  /**
     * 查询指定目录中电子表格中所有的数据
     * @param file 文件完整路径
     * @return
     * @throws IOException 
     * @throws BiffException 
     */
    public  List<KnowledgeBase> getAllByExcel(File file) throws BiffException, IOException{
        List<KnowledgeBase> list=new ArrayList<KnowledgeBase>();
            Workbook rwb=Workbook.getWorkbook(file);
            Sheet rs=rwb.getSheet(0);//或者rwb.getSheet(0)
            int clos=rs.getColumns();//得到所有的列
            int rows=rs.getRows();//得到所有的行
            
            System.out.println(clos+" rows:"+rows);
            for (int i = 1; i < rows; i++) {
                for (int j = 0; j < clos; j++) {
                    //第一个是列数,第二个是行数
                  //  String id=rs.getCell(j++, i).getContents();//默认最左边编号也算一列 所以这里得j++
                    String name=rs.getCell(j++, i).getContents();
                    String patternId=rs.getCell(j++, i).getContents();
                    KnowledgePattern knowledgePattern=  knowledgePatternService.findById(patternId);//我的表里有外键 所以有这一步  没有外键不用考虑这一行
                    String author=rs.getCell(j++, i).getContents();
                    String content=rs.getCell(j++, i).getContents();
                    String problemDescribe=rs.getCell(j++, i).getContents();
                    String Time=rs.getCell(j++, i).getContents();
                   
                    Date date = new Date();
                    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    //Date createTime = sdf.parse(Time);//Thu Sep 20 10:25:21 CST 2018
                    
                    Timestamp createTime = Timestamp.valueOf(Time);//因为实体类的Time在数据库是Date类型的 所以这里需要转化一下
                    
                   // System.out.println(" name:"+name+" patternId:"+patternId+" author:"+author+"content:"+content+"problemDescribe:"+problemDescribe+"createTime:"+createTime);
                    list.add(new KnowledgeBase(name, knowledgePattern, author,content,problemDescribe,createTime));
                }
            }
        
        return list;
        
    }

这样就能获得存储Excel数据的List集合
下面进行调用,并进行存储至数据库就可以了

@ResponseBody
    @RequestMapping(value="/knowledgeExcelInput" )
    public String knowledgeExcelInput( HttpServletRequest request){
    	String flag;
    	try {
    	List<MultipartFile> implementFile = ((MultipartHttpServletRequest)request).getFiles("file");
    	if (implementFile.size()==0) {
    		flag = "-1";
    	}else{
    	MultipartFile mFile =  implementFile.get(0);
    	File f = null;//MultipartFile转File  因为knowledgeBaseService.getAllByExcel方法需要File类型文件
    	   InputStream ins = mFile.getInputStream();  
           f=new File(mFile.getOriginalFilename());  
           try {  
               OutputStream os = new FileOutputStream(f);  
               int bytesRead = 0;  
               byte[] buffer = new byte[8192];  
               while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {  
                os.write(buffer, 0, bytesRead);  
               }  
               os.close();  
               ins.close();  
              } catch (Exception e) {  
               e.printStackTrace();  
              }  
           
		 //得到表格中所有的数据
        List<KnowledgeBase> listExcel=knowledgeBaseService.getAllByExcel(f);
        
        for (KnowledgeBase knowledgeBase : listExcel) {
        	  UUID uuid =UUID.randomUUID();   
    	      String id = uuid.toString();  
    	     // 去掉"-"符号   
    	    //  String id = str.substring(0, 8) +str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) +str.substring(24);   
                String sql="insert into knowledge_base (id,name,pattern_id,author,content,problem_describe,create_time) values("+"'"+id+"','"+knowledgeBase.getName()+"','"+knowledgeBase.getKnowledgePattern().getId()+"','"+knowledgeBase.getAuthor()+"','"+knowledgeBase.getContent()+"','"+knowledgeBase.getProblemDescribe()+"','"+knowledgeBase.getCreateTime()+"')";
      		    System.out.println(sql);
                int i = jdbcTemplate.update(sql);
        }
        File del = new File(f.toURI()); //删除项目产生的临时文件
        del.delete();  
        flag="1";
    	}
    	} catch (Exception e) {
    		e.printStackTrace();
			flag="0";
		}
		return flag;
    }

但是这种方法操作的Excel最好是后缀.xls的,对于.xlsx格式支持不是很友好。还有发现的一个小问题是在编辑Excel数据时,清空某一行不要使用Del直接删除,这样会造成读取空行的问题,删除的话直接选中行,右键–> 删除,这样就没有读取空行的问题了。剩下的小问题,复现再来添加。

猜你喜欢

转载自blog.csdn.net/qq_43137849/article/details/88304121
今日推荐