打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
poi批量实现导入功能,jxl实现导入预览功能
  1. ////////////总结:  
  2.         导入流程:先下载导入模板,根据导入模板填写内容,填写完保存到本地,  
  3.         点击批量数据导入弹出导入文件选择界面,点击预览数据弹出表格,  
  4.         点击导入数据,开始导入。  
  5.         其中技术点有:io实现下载,poi实现导入,jxl实现导入预览。  
  6.         需要的jar:  
  7.         poi-3.14-20160307.jar  
  8.         poi-extend4.0-20150421.jar  
  9.         jxl.jar  
  10.         commons-fileupload-1.3.1.jar  
  11.         commons-io-2.4.jar  
  12. <a href="javascript:void(0)" class="easyui-linkbutton" id="docpath" iconCls="icon-excel" plain="true" onclick="DownLoad()">批量数据导入模版</a>  
  13.         
  14. 点击批量数据导入模版的时候执行  
  15. function DownLoad(){  
  16.         $('#fpForm').submit();  
  17. }  
  18.   
  19. //这个是对应的下载导入模板  
  20. <div id="fpForm1" style="float:left;margin-left:25px;">  
  21.     <form id="fpForm" action="${request.contextPath}/TdLawTask/download"  method="post"><!--action对应的是controle路径-->  
  22.         <label style="width:60px"></label><input id="fp" name="filepath" value="WEB-INF/upload/files/import/单位导入数据模板.xls" type="hidden"  /><!--value是模板路径值-->  
  23.     </form>  
  24. </div>  
  25.   
  26. 提交到后台controle的路径(action="${request.contextPath}/TdLawTask/download")  
  27. /** 
  28.  * @Description下载选中行的附件 
  29.  */  
  30. @ResponseBody  
  31. @RequestMapping("download")  
  32. public void download(@RequestParam String filepath,  
  33.         HttpServletRequest request, HttpServletResponse response) {  
  34.     filepath = filepath.replace("/", "\\");  
  35.     FileUtil.downloadfile(filepath, request, response);  
  36. }  
  37.       
  38. 下载工具类FileUtil  
  39. /** 
  40.  * 下载文件(不需要修改,直接使用) 
  41.  *  
  42.  * @param file 
  43.  * @param request 
  44.  * @param isPic 
  45.  * @return 
  46.  */  
  47. public static String downloadfile(String filepath,  
  48.         HttpServletRequest request, HttpServletResponse response) {  
  49.     String filename = "";  
  50.     //windows 中和liunx中路径格式不一致  
  51.     if (File.separator.equals("\\")) {  
  52.         filepath = filepath.replace("/", "\\");  
  53.         filename = filepath.substring(filepath.lastIndexOf("\\") + 1);  
  54.     } else {  
  55.         filepath = filepath.replace("\\", "/");  
  56.         filename = filepath.substring(filepath.lastIndexOf("/") + 1);  
  57.     }  
  58.     //设置响应编码格式  
  59.     response.setCharacterEncoding("utf-8");  
  60.     //设置文件ContentType类型,这样设置,会自动判断下载文件类型   
  61.     response.setContentType("multipart/form-data");  
  62.     // response.setHeader("Content-Disposition", "attachment;fileName="  
  63.     // + filename);  
  64.     String path = "";  
  65.     try {  
  66.         //设置文件头:最后一个参数是设置下载文件名  
  67.         response.addHeader("Content-Disposition", "attachment;filename="  
  68.                 + new String(filename.getBytes("gbk"), "iso-8859-1")); // 转码之后下载的文件不会出现中文乱码  
  69.         //获取Web项目的全路径   
  70.         path = request.getSession().getServletContext().getRealPath("/")  
  71.                 + filepath;  
  72.         File file = new File(path);  
  73.         if (!file.exists())  
  74.             return path;  
  75.         // System.out.println(path);  
  76.         response.addHeader("Content-Length", "" + file.length());  
  77.         InputStream inputStream = new FileInputStream(file);  
  78.         OutputStream os = response.getOutputStream();  
  79.         byte[] b = new byte[2048];  
  80.         int length;  
  81.         while ((length = inputStream.read(b)) > 0) {  
  82.             os.write(b, 0, length);  
  83.         }  
  84.         os.close();  
  85.         inputStream.close();  
  86.     } catch (FileNotFoundException e) {  
  87.         e.printStackTrace();  
  88.     } catch (IOException e) {  
  89.         e.printStackTrace();  
  90.     }  
  91.     return path;  
  92. }  
  93.   
  94.   
  95. <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-excel" plain="true" onclick="implexll();">批量数据导入</a>  
  96.   
  97. //点击批量数据导入时,打开批量导入数据表单  
  98. function implexll(){  
  99.     $('#dlgup').dialog('open').dialog('setTitle','导入excel');  
  100.     $('#impsearchfm').form('clear');   
  101. }  
  102.   
  103. <!--批量导入数据表单-->  
  104. <div id="dlgup" class="easyui-dialog"  style="padding:10px 20px;" closed="true" buttons="#dlg-buttons-up">  
  105.     <form id="impsearchfm"  novalidate  method="post"  enctype="multipart/form-data" style="float:left">  
  106.             <div class="fitem">     
  107.                 <label style="width:90px">文件路径:</label>  
  108.                 <input  name="file" id="file" class="easyui-filebox" style="width:240px" data-options="buttonText:'选择文件',buttonIcon:'icon-search',prompt:'文件路径...'" value="选择文件">  
  109.             </div>  
  110.     </form>  
  111. </div>  
  112. <div id="dlg-buttons-up">  
  113.     <a href="javascript:void(0)" onclick="preview();" class="easyui-linkbutton" iconCls="icon-search">预览数据</a>  
  114.     <a href="javascript:void(0)" onclick="implexl();" class="easyui-linkbutton" iconCls="icon-excel">导入数据</a>  
  115. </div>  
  116.   
  117. <!--导入时预览表单-->  
  118. <div id="ppreview" class="easyui-dialog" closed="true" buttons="#dlg-buttons-up-ppreview" style="width:800px;height:500px;"  >  
  119. <table id="dgpreview"  class="easyui-datagrid"  style="width:auto;height:100%;overflow:hidden;"  
  120.        striped="true" fit="true" fitColumns="true"  scrollbarSize=0  
  121.         pagination="false"  rownumbers="true" singleSelect="true"  
  122.        data-options="fit:true,border:false,pagesize:2000,pageList:[20000]"  >     
  123.   <thead>  
  124.     <tr>  
  125.         <th data-options="field:'userId',align:'left',halign:'center',width:'12%'">测试</th>  
  126.         <th data-options="field:'corpname',align:'left',halign:'center',width:'36%'" formatter=namecolor>测试1</th>  
  127.     </tr>  
  128.   </thead>  
  129. </table>  
  130. </div>  
  131. <div id="dlg-buttons-up-ppreview">  
  132.     <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#ppreview').dialog('close')" style="width:90px">取消</a>  
  133. </div>      
  134.   
  135. //点击预览数据  
  136. function preview(){  
  137.     $('#ppreview').dialog('open').dialog('setTitle','信息预览');  
  138.       
  139.     var filename=$('#file').filebox('getValue');  
  140.             if(filename==null || filename=='')  
  141.             {  
  142.                 showMsg('提示','请选择文件!');  
  143.                 return;  
  144.             }  
  145.     $('#impsearchfm').form('submit',{  
  146.             url: '${request.contextPath}/business/getfilename',//请求后台  
  147.             onSubmit: function(){  
  148.             $.messager.progress({  
  149.                 title : '提示',  
  150.                 text : '数据处理中,请稍后....'  
  151.                });  
  152.                return true;  
  153.             },  
  154.             success: function(data){  
  155.               
  156.             //上传文件并得到文件名  
  157.             loadPriview(data);  
  158.             }  
  159.     });  
  160.       
  161.     function loadPriview(filename){  
  162.         $.ajax({  
  163.             type : 'get',  
  164.             url : '${request.contextPath}/business/preview',  
  165.             dataType : 'json',  
  166.             data : {data :filename},  
  167.             cache :false,  
  168.             success : function(data) {  
  169.                 $.messager.progress('close');  
  170.                 $('#dgpreview').datagrid({     
  171.                     data:data  
  172.                 });              
  173.             }  
  174.         });  
  175.     }     
  176. }  
  177. //${request.contextPath}/business/getfilename',//后台代码  
  178. /** 
  179.  *  
  180.  * @Method_Name: getfilename 
  181.  * @Description: 上传文件并返回文件名 
  182.  */  
  183. @ResponseBody  
  184. @RequestMapping("getfilename")  
  185. public String getFileName(DicInputPrd dicinputprd,@RequestParam("file") MultipartFile file, HttpServletRequest request,HttpSession session) {  
  186.     String filePath="";  
  187.     String fileName="";  
  188.       
  189.     if(file!=null){  
  190.         if(file.getSize()>0)  
  191.             filePath=FileUtil.upload(file, request, true);//调用下面的上传文件  
  192.         fileName=request.getSession().getServletContext()  
  193.                 .getRealPath("/")+filePath;  
  194.     }  
  195.     return fileName;  
  196. }  
  197.   
  198. 上传下载工具类FileUtil  
  199. /** 
  200.  * 上传文件 
  201.  *  
  202.  * @param file 
  203.  * @param request 
  204.  * @param isPic 
  205.  * @return 
  206.  */  
  207. public static String upload(MultipartFile file, HttpServletRequest request,  
  208.         Boolean isPic) {  
  209.     SimpleDateFormat dateformat = new SimpleDateFormat("yyyy_MM_dd/HHMMSS");  
  210.     //文件夹名字  
  211.     String pathDir = "upload" + File.separator + "imgs" + File.separator  
  212.             + dateformat.format(new Date()) + (int) Math.random() * 1000  
  213.             + File.separator;  
  214.     if (File.separator.equals("\\")) {  
  215.         pathDir = pathDir.replace("/", "\\");  
  216.     }  
  217.   
  218.     if (isPic == false) {  
  219.         pathDir = pathDir.replace("imgs", "files");  
  220.     }  
  221.   
  222.     String filename = file.getOriginalFilename();//获取文件名  
  223.     String extName = "";  
  224.     if (StrUtil.isNotBlank(filename)) {//判断是否为空,不为空走if  
  225.         int t = filename.lastIndexOf(".");  
  226.         if (t > 0) {  
  227.             extName = filename.substring(t).toLowerCase();//获取文件的后缀名字  
  228.         }  
  229.     }  
  230.     filename = sdf.format(new Date());//时间格式化  
  231.     // File file2 = new File(request.getSession().getServletContext()  
  232.     // .getRealPath(pathDir));  
  233.     pathDir += filename + extName;//上传的路径完整名  
  234.     String realPathDir = request.getSession().getServletContext()  
  235.             .getRealPath(pathDir);//项目的完整路径名  
  236.     // if(!file2.exists())  
  237.     // file2.mkdir();  
  238.     try {  
  239.         FileUtils.copyInputStreamToFile(file.getInputStream(), new File(  
  240.                 realPathDir));  
  241.     } catch (IOException e) {  
  242.         e.printStackTrace();  
  243.     }  
  244.     return pathDir;  
  245. }  
  246. ${request.contextPath}/business/preview',后台代码,获取excel表格中数据,并按照指定格式返回  
  247.   
  248. //导入时预览  
  249. @ResponseBody  
  250. @RequestMapping("preview")  
  251. public JqueryUiJson preview(String data, HttpServletRequest request,HttpSession session) {    
  252.     List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  253.     try {  
  254.             InputStream is = new FileInputStream(data);      
  255.             jxl.Workbook rwb = Workbook.getWorkbook(is);//得到工作薄  
  256.             Sheet[] rslist=rwb.getSheets();//工作薄(Workbook)中工作表(Sheet)对象数组   
  257.             //循环读取sheet工作表  
  258.             for(int i=0;i<rslist.length;i++){  
  259.                 //获取Sheet表中所包含的总行数:getRows()  
  260.                 for(int j=1;j<rslist[i].getRows();j++){  
  261.                     Map<String, Object> map = new HashMap<String,Object>();  
  262.                     int length = rslist[i].getColumns();//获取Sheet表中所包含的总列数:getColumns()  
  263.                     String[] content=new String[length];//内容数组content  
  264.                     //如果一行没有任何内容,则跳过  
  265.                     int flag = 0;  
  266.                     for( int t=0;t<length;t++){//取到某行某列的内容  
  267.                         content[t]=rslist[i].getCell(t,j).getContents().trim();  
  268.                         if(!"".equals(content[t])&&content[t] != null){  
  269.                             flag=1;  
  270.                         }  
  271.                     }  
  272.                     if(flag==0){  
  273.                         continue;  
  274.                     }  
  275.                     map.clear();  
  276.                       
  277.                     //这里可以对某一列进行处理(这里可以修改start)  
  278.                     String industry="";  
  279.                     String [] stringArr = content[7].split(";");  
  280.                     for(int t = 0;t<stringArr.length;t++){                         
  281.                         String sql6 = "SELECT VALUE as industry FROM sys_aaaa WHERE id = 'dic' AND item = '"+stringArr[t]+"'";  
  282.                         Map map6 = sqlMapper.selectOne(sql6,new Object[]{"industry"});  
  283.                         if(map6!=null){  
  284.                             industry += map6.get("industry").toString()+",";  
  285.                         }  
  286.                     }  
  287.                     industry=industry.substring(0,industry.length()-1);  
  288.                    //这里可以对某一列进行处理(这里可以修改end)  
  289.                     map.put("ceshi1", content[0]);  
  290.                     map.put("ceshi2", content[1]);  
  291.                     map.put("ceshi3", content[2]);  
  292.                     map.put("ceshi4", content[3]);  
  293.                     map.put("ceshi5", content[4]);  
  294.                     map.put("ceshi6", content[5]);  
  295.                     map.put("ceshi7", industry);  
  296.                     map.put("ceshi8", content[6]);  
  297.                     list.add(map);  
  298.                 }  
  299.             }     
  300.             rwb.close();//关闭工作薄  
  301.             //返回结果//返回(总条数(total),数据(rows))的格式。(这里根据自己需要的格式进行返回)  
  302.             JqueryUiJson jqueryUiJson = new JqueryUiJson(ExampleUtil.getPageInfo(list).getTotal(), list);  
  303.             return jqueryUiJson;  
  304.         }catch(Exception e){  
  305.                 e.printStackTrace();  
  306.                 return null;  
  307.         }     
  308.     }  
  309.       
  310. 这个是分页数据格式化,包名:(import com.github.pagehelper.PageInfo)     
  311. public static <T> PageInfo<T> getPageInfo(List<T> tlist) {  
  312.         PageInfo<T> pageinfo = new PageInfo<T>(tlist);  
  313.         return pageinfo;  
  314.     }  
  315.   
  316.   
  317. //点击导入数据  
  318. function implexl(){  
  319.     var filename=$('#file').filebox('getValue');//获取文件名  
  320.     if(filename==null || filename=='')  
  321.     {  
  322.         showMsg('提示','请选择文件!');  
  323.         return;  
  324.     }  
  325.     $('#impsearchfm').form('submit',{  
  326.             url: '${request.contextPath}/business/importExl',  
  327.             onSubmit: function(){  
  328.             $.messager.progress({//提示信息  
  329.                 title : '提示',  
  330.                 text : '数据处理中,请稍后....'  
  331.                });  
  332.                return true;  
  333.             },  
  334.             success: function(result){  
  335.             $.messager.progress('close');//成功关闭提示信息  
  336.             var rtnMsg="";  
  337.                 if (result!="0"){  
  338.                     showMsg('错误提示','上传数据不规范');  
  339.                 } else {  
  340.                     showMsg('提示','数据导入成功');  
  341.                     //刷新列表   
  342.                     //关闭提示框  
  343.                 }  
  344.             }  
  345.         });  
  346. }   
  347.   
  348. //导入时请求后台  
  349. '${request.contextPath}/business/importExl',请求对应的后台  
  350.   
  351. /** 
  352.  * @Method_Name: importExl 
  353.  * @Description: 批量导入 
  354.  */  
  355. @ResponseBody  
  356. @RequestMapping("importExl")  
  357. public String importExl(@RequestParam("file") MultipartFile file, HttpServletRequest request,HttpSession session){  
  358.     try {  
  359.         String str = tdLawTaskService.importExl(file,session,type);  
  360.         return str;  
  361.     } catch (Exception e) {  
  362.         e.printStackTrace();  
  363.         return e.getMessage();  
  364.     }  
  365. }  
  366. service  
  367. public String importExl(MultipartFile file,HttpSession session,String type);  
  368.   
  369. /** 
  370.  * @Method_Name: importExl 
  371.  * @Description: 导入 
  372.  */  
  373. public String importExl(MultipartFile file,HttpSession session,String type){  
  374.     String str = "";  
  375.     if(file!=null){  
  376.         ImportExcel impexc = new ImportExcel();  
  377.         //创建时间  
  378.         String createdate = DateTimeUtil.getDateTime();  
  379.         try {  
  380.             List<String> list = impexc.readExcelContent(file.getInputStream());//读取Excel数据内容  
  381.             String sql_head ="INSERT into td_law_sss (ceshi1,ceshi2,ceshi3)VALUES ";  
  382.             for (int i = 0; i < list.size(); i++) {  
  383.                 String[] sourceStrArray = list.get(i).split(",",-1);     
  384.               //判断 空行 跳过  
  385.                 if(StrUtil.konghang(sourceStrArray)){  
  386.                     continue;  
  387.                 }  
  388.                 str =str+ "('"+sourceStrArray[0]+"'," +"'"+sourceStrArray[1]+"','"+sourceStrArray[2]+"'), ";  
  389.             }  
  390.             sqlMapper.insert(sql_head+str.substring(0, str.length()-2)+";");  
  391.         } catch (IOException e) {  
  392.             e.printStackTrace();  
  393.         }  
  394.     }  
  395.     return "0";  
  396. }  
  397.   
  398. ImportExcel.java类Start  
  399. /** 
  400.  * 读取Excel数据内容 
  401.  * @param InputStream 
  402.  * @return Map 包含单元格数据内容的Map对象 
  403.  */  
  404. public List<String> readExcelContent(InputStream is) {  
  405. //  Map<Integer, String> content = new HashMap<Integer, String>();  
  406.     List<String> content = new ArrayList<String>();  
  407.     String str = "";  
  408.     try {  
  409.         fs = new POIFSFileSystem(is);  
  410.         wb = new HSSFWorkbook(fs);  
  411.     } catch (IOException e) {  
  412.         e.printStackTrace();  
  413.     }  
  414.     sheet = wb.getSheetAt(0);  
  415.     // 得到总行数  
  416.     int rowNum = sheet.getLastRowNum();  
  417.     row = sheet.getRow(0);  
  418.     //获取不为空的列个数  
  419.     int colNum = row.getPhysicalNumberOfCells();  
  420.     // 正文内容应该从第二行开始,第一行为表头的标题  
  421.     for (int i = 1; i <= rowNum; i++) {  
  422.         row = sheet.getRow(i);  
  423.       //防止中间某行没有内容  
  424.         int flag = 0;  
  425.         if(null!=row){  
  426.             flag = 1;  
  427.         }  
  428.         if(flag == 0){  
  429.             continue;  
  430.         }  
  431.         int j = 0;  
  432.         while (j < colNum) {  
  433.             // 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据  
  434.             // 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean  
  435.             // str += getStringCellValue(row.getCell((short) j)).trim() +  
  436.             // "-";  
  437.             //得到Excel工作表指定行的单元格:row.getCell((short) j  
  438.             str += getCellFormatValue(row.getCell((short) j)).trim() + ","; //格式化数据  
  439.             j++;  
  440.         }  
  441.         content.add(str);  
  442.         str = "";  
  443.     }  
  444.     return content;  
  445. }  
  446.   
  447. /** 
  448.  * 根据HSSFCell类型设置数据 
  449.  * @param cell 
  450.  * @return 
  451.  */  
  452. private String getCellFormatValue(HSSFCell cell) {  
  453.     String cellvalue = "";  
  454.     if (cell != null) {  
  455.         // 判断当前Cell(单元格)的Type  
  456.         switch (cell.getCellType()) {  
  457.         // 如果当前Cell的Type为NUMERIC  
  458.         case HSSFCell.CELL_TYPE_NUMERIC:  
  459.         case HSSFCell.CELL_TYPE_FORMULA: {  
  460.             // 判断当前的cell是否为Date  
  461.             if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  462.                 // 如果是Date类型则,转化为Data格式  
  463.                   
  464.                 //方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00  
  465.                 //cellvalue = cell.getDateCellValue().toLocaleString();  
  466.                   
  467.                 //方法2:这样子的data格式是不带带时分秒的:2011-10-12  
  468.                 Date date = cell.getDateCellValue();  
  469.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  470.                 cellvalue = sdf.format(date);  
  471.                   
  472.             }  
  473.             // 如果是纯数字  
  474.             else {  
  475.                 // 取得当前Cell的数值  
  476.                 //cellvalue = String.valueOf(cell.getNumericCellValue());  
  477.                 DecimalFormat df = new DecimalFormat("0");    
  478.                 cellvalue = df.format(cell.getNumericCellValue());   
  479.             }  
  480.             break;  
  481.         }  
  482.         // 如果当前Cell的Type为STRIN  
  483.         case HSSFCell.CELL_TYPE_STRING:  
  484.             // 取得当前的Cell字符串  
  485.             cellvalue = cell.getRichStringCellValue().getString();  
  486.             break;  
  487.         // 默认的Cell值  
  488.         default:  
  489.             cellvalue = " ";  
  490.         }  
  491.     } else {  
  492.         cellvalue = "";  
  493.     }  
  494.     return cellvalue;  
  495. }  
  496. ImportExcel.java类end  
  497.   
  498. //StrUtil类中导入时判断空行  
  499. public static boolean konghang(String[] content){    
  500.     int flag = 0;  
  501.     for( int t=0;t<content.length;t++){  
  502.         if(!"".equals(content[t])&&content[t] != null){  
  503.             flag=1;  
  504.             break;  
  505.         }  
  506.     }  
  507.     if(flag==0){  
  508.         return true;  
  509.     }  
  510.     return false;  
  511. }  


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java创建、重命名、删除文件和文件夹
SpringMVC 文件上传配置,多文件上传,使用的MultipartFile
关于Java文件路径问题
开发|Springboot简单实现文件上传
Jsp页面实现文件上传下载 -下载
ASP.NET上传文件的几种方法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服