在springmvc项目中使用poi导入导出excel

转载:http://blog.csdn.net/kingson_wu/article/details/38942967

首先要导入spring相关包,poi,和fileupload包,我是使用maven构建的。


一.导入excel

(1)使用spring上传文件

a.前台页面提交
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <form name="excelImportForm" action="${pageContext.request.contextPath}/brand/importBrandSort" method="post" onsubmit="return checkImportPath();" enctype="multipart/form-data" id="excelImportForm">  
  2.                <input  type="hidden" name="ids" id="ids">  
  3.                <div class="modal-body">  
  4.                    <div class="row gap">  
  5.                        <label class="col-sm-7 control-label"><input class="btn btn-default" id="excel_file" type="file" name="filename"  accept="xls"/></label>  
  6.                        <div class="col-sm-3">  
  7.                              
  8.                         <input class="btn btn-primary" id="excel_button" type="submit" value="导入Excel"/>  
  9.                        </div>  
  10.                    </div>  
  11.                      
  12.                </div>  
  13.                 
  14.                <div class="modal-footer">  
  15.                     <button type="button" class="btn btn-default" data-dismiss="modal" onClick="uncheckBoxes();">取消</button>  
  16.             </div>  


在提交前可进行一些判断,可查看:

b.后台spring的controller进行相关操作,这里主要讲的是使用spring上传文件,和读取文件信息,可以参考这两篇文章:


使用spring上传文件之前,需要配置bean
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @RequestMapping(value = "/importBrandSort", method = RequestMethod.POST)  
  2.     public ModelAndView importBrandSort(@RequestParam("filename") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception {  
  3.         /*String temp = request.getSession().getServletContext() 
  4.                 .getRealPath(File.separator) 
  5.                 + "temp"; // 临时目录 
  6.         File tempFile = new File(temp); 
  7.         if (!tempFile.exists()) { 
  8.             tempFile.mkdirs(); 
  9.         } 
  10.         DiskFileUpload fu = new DiskFileUpload(); 
  11.         fu.setSizeMax(10 * 1024 * 1024); // 设置允许用户上传文件大小,单位:位 
  12.         fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:位 
  13.         fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 
  14.         // 开始读取上传信息 
  15.         // int index = 0; 
  16.         List fileItems = null; 
  17.         try { 
  18.             fileItems = fu.parseRequest(request); 
  19.         } catch (Exception e) { 
  20.             e.printStackTrace(); 
  21.         } 
  22.         Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件 
  23.         FileItem fileItem = null; 
  24.         while (iter.hasNext()) { 
  25.             FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息 
  26.             if (!item.isFormField()) { 
  27.                 fileItem = item; 
  28.                 // index++; 
  29.             } 
  30.         } 
  31.          
  32.         if (fileItem == null) 
  33.             return null; 
  34.             */  
  35.         if (file == null)  
  36.             return null;  
  37.         logger.info(file.getOriginalFilename());  
  38.   
  39.         String name = file.getOriginalFilename();// 获取上传文件名,包括路径  
  40.         //name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名  
  41.         long size = file.getSize();  
  42.         if ((name == null || name.equals("")) && size == 0)  
  43.             return null;  
  44.         InputStream in = file.getInputStream();  
  45.         int count = brandService.importBrandPeriodSort(in);  
  46.   
  47.         // 改为人工刷新缓存KeyContextManager.clearPeriodCacheData(new  
  48.         // PeriodDimensions());// 清理所有缓存  
  49.         //int count = BrandMobileInfos.size();  
  50.         String strAlertMsg ="";  
  51.           
  52.             strAlertMsg= "成功更新" + count + "条!";  
  53.           
  54.         logger.info(strAlertMsg);  
  55.         //request.setAttribute("brandPeriodSortList", BrandMobileInfos);  
  56.         //request.setAttribute("strAlertMsg", strAlertMsg);  
  57.       
  58.         request.getSession().setAttribute("msg",strAlertMsg);  
  59.         return get(request, response);  
  60.         //return null;  
  61.     }  



代码中的注释部分是如果不使用spring的方式,如何拿到提交过来的文件名(需要是要apache的一些工具包),其实使用spring的也是一样,只是已经做好了封装,方便我们写代码。

代码中的后半部分是读取完上传文文件的信息和对数据库进行更新之后,输出到前台页面的信息。

这里给页面设置session信息,前台检测session提示是否导入成功。具体可参考:
上述代码中:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. InputStream in = file.getInputStream();  
  2.         List<BrandMobileInfoEntity> BrandMobileInfos = brandService  
  3.                 .importBrandPeriodSort(in);  
读取excel的信息。

(2)使用poi读取excel

a.更新数据库
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     public List<BrandMobileInfoEntity> importBrandPeriodSort(InputStream in) throws Exception  {  
  3.           
  4.         List<BrandMobileInfoEntity> brandMobileInfos = readBrandPeriodSorXls(in);  
  5.         for (BrandMobileInfoEntity brandMobileInfo : brandMobileInfos) {  
  6.             mapper.updateByConditions(brandMobileInfo);  
  7.         }  
  8.         return brandMobileInfos;  
  9.     }  

这部分是sevice层的代码,用于读取excel信息之后更新数据库数据,我这里是使用mybatis。定义一个类BrandMobileInfoEntity,用与保存excel表每一行的信息,而List< BrandMobileInfoEntity>则保存了全部信息,利用这些信息对数据库进行更新。

b.读取excel信息

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private List<BrandMobileInfoEntity> readBrandPeriodSorXls(InputStream is)  
  2.             throws IOException, ParseException {  
  3.         HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);  
  4.         List<BrandMobileInfoEntity> brandMobileInfos = new ArrayList<BrandMobileInfoEntity>();  
  5.         BrandMobileInfoEntity brandMobileInfo;  
  6.         // 循环工作表Sheet  
  7.         for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {  
  8.             HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);  
  9.             if (hssfSheet == null) {  
  10.                 continue;  
  11.             }  
  12.             // 循环行Row  
  13.             for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {  
  14.                 brandMobileInfo = new BrandMobileInfoEntity();  
  15.                 HSSFRow hssfRow = hssfSheet.getRow(rowNum);  
  16.                 for (int i = 0; i < hssfRow.getLastCellNum(); i++) {  
  17.                     HSSFCell brandIdHSSFCell = hssfRow.getCell(i);  
  18.                     if (i == 0) {  
  19.                         brandMobileInfo.setBrandId(Integer  
  20.                                 .parseInt(getCellValue(brandIdHSSFCell)));  
  21.                     } else if (i == 1) {  
  22.                         continue;  
  23.                     } else if (i == 2) {  
  24.                         brandMobileInfo.setMobileShowFrom(Integer.parseInt(getCellValue(brandIdHSSFCell)));  
  25.                     } else if (i == 3) {  
  26.                         brandMobileInfo.setMobileShowTo(Integer.parseInt(getCellValue(brandIdHSSFCell)));  
  27.                     } else if (i == 4) {  
  28.                         brandMobileInfo.setSellMarkValue(getCellValue(brandIdHSSFCell));  
  29.                     } else if (i == 5) {  
  30.                         brandMobileInfo.setWarehouse(getCellValue(brandIdHSSFCell));  
  31.                     } else if (i == 6) {  
  32.                         brandMobileInfo.setSortA1(Integer.parseInt(getCellValue(brandIdHSSFCell)));  
  33.                     } else if (i == 7) {  
  34.                         brandMobileInfo.setSortA2(Integer.parseInt(getCellValue(brandIdHSSFCell)));  
  35.                     } else if (i == 8) {  
  36.                         brandMobileInfo.setSortB(Integer.parseInt(getCellValue(brandIdHSSFCell)));  
  37.                     } else if (i == 9) {  
  38.                         brandMobileInfo.setSortC10(Integer.parseInt(getCellValue(brandIdHSSFCell)));  
  39.                     } else if (i == 10) {  
  40.                         brandMobileInfo.setSortC(Integer.parseInt(getCellValue(brandIdHSSFCell)));  
  41.                     } else if (i == 11) {  
  42.                         brandMobileInfo.setHitA(getCellValue(brandIdHSSFCell));  
  43.                     } else if (i == 12) {  
  44.                         brandMobileInfo.setHitB(getCellValue(brandIdHSSFCell));  
  45.                     } else if (i == 13) {  
  46.                         brandMobileInfo.setHitC(getCellValue(brandIdHSSFCell));  
  47.                     } else if (i == 14) {  
  48.                         brandMobileInfo.setCustomSellType(getCellValue(brandIdHSSFCell));  
  49.                     }else if (i == 15) {  
  50.                       continue;  
  51.                     }else if (i == 16) {  
  52.                         brandMobileInfo.setChannelId(Integer.parseInt(getCellValue(brandIdHSSFCell)));  
  53.                     }  
  54.                 }  
  55.                 brandMobileInfos.add(brandMobileInfo);  
  56.   
  57.             }  
  58.         }  
  59.         return brandMobileInfos;  
  60.     }  

这种代码有点搓,还没有优化,可以大概看到是怎么读取信息的。

(3)使用mybatis更新数据


二.导出excel

(1)
前台页面使用一个按钮,定义js事件:
[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. $(".exportBrandSort").on('click'function() {  
  2.           
  3.          var url = contextPath+"/brand/exportBrandSort";  
  4.          $('#searchform').attr('action', url);  
  5.          $('#searchform').submit();  
  6.          //还原action值  
  7.          url = contextPath+"/brand/getBrand";  
  8.          $('#searchform').attr('action', url);}  

这里使用查询功能的form的表单,则导出的就是查询之后的信息的excel表格。

(2)后台controller处理
a.后端controller处理并输出到前台
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @RequestMapping(value = "/exportBrandSort", method = RequestMethod.GET)  
  2.     public void exportBrandSort(HttpServletRequest request,  
  3.             HttpServletResponse response) throws Exception {  
  4.   
  5.         try {  
  6.             Map<String, Object> params = new HashMap<>();  
  7.             // start time of selling  
  8.             String startTimeStr = RequestUtil.getStringParameter(request,  
  9.                     "startTimeStr"null);  
  10.             if (StringUtils.isNotBlank(startTimeStr)) {  
  11.                 params.put("startTimeStr", startTimeStr);  
  12.                 params.put("startTime", df.parse(startTimeStr).getTime() / 1000);  
  13.             }  
  14.   
  15.             // end time of selling  
  16.             String endTimeStr = RequestUtil.getStringParameter(request,  
  17.                     "endTimeStr"null);  
  18.             if (StringUtils.isNotBlank(endTimeStr)) {  
  19.                 params.put("endTimeStr", endTimeStr);  
  20.                 params.put("endTime", df.parse(endTimeStr).getTime() / 1000);  
  21.             }  
  22.   
  23.             // warehouse  
  24.             String warehouse = RequestUtil.getStringParameter(request,  
  25.                     "warehouse");  
  26.             if (StringUtils.isNotBlank(warehouse)) {  
  27.                 params.put("warehouse", warehouse);  
  28.             }  
  29.   
  30.             // channel  
  31.             String channel4ui = BrandConstants.CHANNEL_ID_SEARCH_DEFAULT;  
  32.   
  33.             String[] channel = request.getParameterValues("channel");  
  34.             if (channel != null && channel.length > 0) {  
  35.                 channel4ui = stringArrayToString(channel);  
  36.             }  
  37.             params.put("channel", channel4ui);  
  38.   
  39.             String orderType = request.getParameter("orderType");  
  40.             if (orderType == null || "".equals(orderType)) {  
  41.                 orderType = "C";  
  42.             }  
  43.             params.put("orderType", orderType);  
  44.   
  45.             // brand id  
  46.             if (RequestUtil.getIntParameter(request, "brandId") > 0)  
  47.                 params.put("brandId",  
  48.                         (RequestUtil.getIntParameter(request, "brandId")));  
  49.             // brand name  
  50.             if (RequestUtil.getStringParameter(request, "brandName") != null  
  51.                     && !"".equals(RequestUtil.getStringParameter(request,  
  52.                             "brandName").trim()))  
  53.                 // params.put("brandName", new  
  54.                 // String(RequestUtil.getStringParameter(request,  
  55.                 // "brandName").getBytes("ISO-8859-1"),"UTF-8"));  
  56.                 params.put("brandName",  
  57.                         RequestUtil.getStringParameter(request, "brandName"));  
  58.   
  59.             int count = brandService.countByConditions(params);  
  60.   
  61.             List<BrandCompleteInfoEntity> list = brandService  
  62.                     .queryBrands(params);  
  63.   
  64.             // --------  
  65.   
  66.             byte[] fileNameByte = ("kxw.xls").getBytes("GBK");  
  67.             String filename = new String(fileNameByte, "ISO8859-1");  
  68.   
  69.             byte[] bytes = brandService.exportBrandPeriodSort(list);  
  70.         //  logger.info("------------------------"+bytes.length);  
  71.             response.setContentType("application/x-msdownload");  
  72.             //response.setContentType("application/x-excel");    
  73.             response.setContentLength(bytes.length);  
  74.             response.setHeader("Content-Disposition""attachment;filename="  
  75.                     + filename);  
  76.             response.getOutputStream().write(bytes);  
  77.             //response.getOutputStream().flush();  
  78.               
  79.              
  80.         } catch (Exception ex) {  
  81.             logger.debug(ex.getMessage());  
  82.         }  
  83.     }  

代码中前半部分只是根据表单信息去后台那数据并保存在List<BrandCompleteInfoEntity>中,可忽略细节。
关键是把 List<BrandCompleteInfoEntity>拼接成excel并输出到网页中。

这里注意该方法的返回值是void,否则如果是ModelAndView或者String等类型,提交之后会发生跳转,返回null则是跳转到空白页面。

代码中:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. byte[] fileNameByte = ("档期列表.xls").getBytes("GBK");  
  2.             String filename = new String(fileNameByte, "ISO8859-1");  
  3.   
  4.             byte[] bytes = brandService.exportBrandPeriodSort(list);  
若乱码:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. response.setHeader("Content-Disposition""attachment;filename="  
  2.                     + java.net.URLEncoder.encode("档期列表.xls""UTF-8") );  
  3.             response.getOutputStream().write(bytes);  


是拼接excel。

b.拼接excel(service层)
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     public byte[] exportBrandPeriodSort(List<BrandCompleteInfoEntity>  list) throws Exception {  
  3.           
  4.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  5.         // 第一步,创建一个webbook,对应一个Excel文件  
  6.         HSSFWorkbook wb = new HSSFWorkbook();  
  7.         // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
  8.         HSSFSheet sheet = wb.createSheet("档期排序表");  
  9.         // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
  10.         HSSFRow row = sheet.createRow((int0);  
  11.         // 第四步,创建单元格,并设置值表头 设置表头居中  
  12.         HSSFCellStyle style = wb.createCellStyle();  
  13.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  
  14.   
  15.         //设置表头  
  16.         List<String> excelHead = getExcelHead();  
  17.           
  18.         HSSFCell cell = null;  
  19.         // excel头  
  20.         for (int i = 0; i < excelHead.size(); i++) {  
  21.             cell = row.createCell(i);  
  22.             cell.setCellValue(excelHead.get(i));  
  23.             cell.setCellStyle(style);  
  24.         }  
  25.   
  26.         // 第五步,写入实体数据 实际应用中这些数据从数据库得到  
  27.         //List<BrandPeriodSortEntity> list = getBrandPeriodSortDynamicOrder(entity, orderType);  
  28.   
  29.         BrandCompleteInfoEntity brandCompleteInfo = null// 拼装excel内容  
  30.         for (int i = 0; i < list.size(); i++) {  
  31.             row = sheet.createRow((int) i + 1);  
  32.             brandCompleteInfo = list.get(i);  
  33.             // 创建单元格,并设置值  
  34.           
  35.               
  36.             int j=0;  
  37.             insertCell(row, j++, brandCompleteInfo.getBrandId());  
  38.             insertCell(row, j++, brandCompleteInfo.getBrandName());  
  39.             insertCell(row, j++, brandCompleteInfo.getMobileShowFrom());  
  40.             insertCell(row, j++, brandCompleteInfo.getMobileShowTo());  
  41.             insertCell(row, j++, brandCompleteInfo.getSellMarkValue());  
  42.             insertCell(row, j++, brandCompleteInfo.getWarehouse());  
  43.             insertCell(row, j++, brandCompleteInfo.getSortA1());  
  44.             insertCell(row, j++, brandCompleteInfo.getSortA2());  
  45.             insertCell(row, j++, brandCompleteInfo.getSortB());  
  46.             insertCell(row, j++, brandCompleteInfo.getSortC10());  
  47.             insertCell(row, j++, brandCompleteInfo.getSortC());  
  48.             insertCell(row, j++, brandCompleteInfo.getHitA());  
  49.             insertCell(row, j++, brandCompleteInfo.getHitB());  
  50.             insertCell(row, j++, brandCompleteInfo.getHitC());  
  51.             insertCell(row, j++, brandCompleteInfo.getCustomSellType());  
  52.             insertCell(row, j++, channelInfoMapper.loadChannelNameById(brandCompleteInfo.getChannelId()));  
  53.             insertCell(row, j++, brandCompleteInfo.getChannelId());  
  54.               
  55.         }  
  56.         wb.write(out);  
  57.         return out.toByteArray();  
  58.     }  
  59.       
  60.     /** 
  61.      * 获取excel表头 
  62.      *  
  63.      * @return 
  64.      */  
  65.     private List<String> getExcelHead() {  
  66.         List<String> result = new ArrayList<String>(17);  
  67.         result.add("XXXXX");  
  68.         result.add("XXXXX");  
  69.         result.add("XXXXX");  
  70.         result.add("XXXXX");  
  71.         result.add("XXXXX");  
  72.         result.add("XXXXX");  
  73.         result.add("XXXXX");  
  74.         result.add("XXXXX");  
  75.         result.add("XXXXX");  
  76.         result.add("XXXXX");  
  77.   
  78.         //。。。。  
  79.         return result;  
  80. }  
  81.     private void insertCell(HSSFRow row,int i,Object object){  
  82.           
  83.         if(object==null){  
  84.             row.createCell(i).setCellValue("");  
  85.         }else{  
  86.             row.createCell(i).setCellValue(object.toString());  
  87.         }  
  88.           
  89.     }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值