不管是xml的导入和导出还是Excel的导入和导出,对应的无非都是文件的解析和下载,下面来讲解的主要是导出(下载)
导入:上传---》解析并组装javaBean(javaBeanList)--》插入数据库(多数为数据库)
导出:查询需要下载的数据--》将JavaBean生成对应的文件(eg:xml、poi、json等)--》下载
- poi导出--即下载poi
- 前台:
- 下载form表单提交(下载不可以采用ajax提交)(form表单提交查看常识题中form表单的几种提交方式,即给form标签一个id,根据id获取的对象值.action属性或者是采用.attr(“action”,url路径的方式),注意,提交方式为post,不然会发生汉字乱码的问题)
===============form表单提交的几种方式===========
。。。。。。。。。。。第一种方法。。。。。。。。。。。。。。。。。。
1.给form定义一个id,通过jquery获取对应的form表单的数据
2.通过jquery中的一个attr("属性",属性值)给action属性赋值,同理,即可以对method属性赋值
3.通过jquery的一个submit()方法提交
$(function(){ $('#exportId').bind('click', function(){ $.messager.confirm('您正在操作导出poi','您确定继续执行该操作吗?',function(r){ if(r){ $("#userInfoId").attr("action","<%=request.getContextPath()%>/user/exportUser.action"); $("#userInfoId").submit(); }else{ $.messager.alert('提示','您取消了该操作!') } }) }); });
。。。。。。。。。。第一种方法结束。。。。。。。。。。。。。。。。。。。
。。。。。。。。。。。第二种方法开始。。。。。。。。。。。。。。。。。。
1.通过原生js获取数据值
2.给action赋值
3.给method赋值
4.submit提交
function poiExcel_() { $.messager.confirm("提示","确认要下载吗?",function(r){ if(r){ $.messager.alert('提示','下载成功!'); var v_productForm = document.getElementById("esayui_poi_list_id"); v_productForm.action = "<%=request.getContextPath()%>/esayui/poiExcel.jhtml"; v_productForm.submit(); }else { $.messager.alter('提示','下载失败!'); } }); }
。。。。。。。。。。。第二种方法结束。。。。。。。。。。。。。。。。。。
- 下载按钮,下载的合理提示,查看,需要下载成的样式,及需要的条件
- 下载form表单提交(下载不可以采用ajax提交)(form表单提交查看常识题中form表单的几种提交方式,即给form标签一个id,根据id获取的对象值.action属性或者是采用.attr(“action”,url路径的方式),注意,提交方式为post,不然会发生汉字乱码的问题)
- 前台:
- 后台:
- 根据条件查询集合数据
- 创建webwork工作薄对象
- 通过工作薄对象创建sheet
- 通过sheet创建row
- 通过row创建cell
- 列的赋值及样式的设置
- 合并单元格(开始行,结束行,开始列,结束列)
- 图片的设置
- 文本样式
- 下载
- 通过response进行相依下载
- 项目结合,本项目的需求主要是,两张表的联查(产品表与品牌表),要求每个sheet对应的是品牌,excel中的内容标题是XX品牌展示,内容是拥有该品牌的所有产品,要求样式的设置及图片的设置
- 案例
- poi导出excel,三大步骤
1.根据需求查询
2.创建workbook
3.下载
@RequestMapping(value="/downloadXLS",method=RequestMethod.POST) public void downloadXLS(Product product,HttpServletRequest request,HttpServletResponse response) { //根据查询条件查询产品表集合 List<Product> productList=productService.findProductList(product); //根据查询条件查询品牌表集合 List<Brand> brandList=brandService.findBrandList(); //3.创建workbook HSSFWorkbook workBook =new HSSFWorkbook(); //下载 createExcelPoi(productList,brandList, workBook,request, response); }
创建excel
1.循环获取对应的需求条件
2.根据workBook创建sheet
3.createTitle(sheet, brand.getBrandName());根据sheet创建row,根据row创建cell
4.标题头的样式设置
5.内容标题头的创建
6.根据行创建表头(主体内容),并赋值
7.导出下载
private void createExcelPoi(List<Product> productList, List<Brand> brandList, HSSFWorkbook workBook,HttpServletRequest request,HttpServletResponse response) { for (int i=0;i<brandList.size();i++) { Brand brand = brandList.get(i); List<Product> eligibilityBrand = returnStudentList(productList,brand); if(eligibilityBrand.size()>0) { //根据workBook创建sheet HSSFSheet sheet = workBook.createSheet(brand.getBrandName()+"("+eligibilityBrand.size()+"个)"); createTitle(sheet, brand.getBrandName()); //标题头的样式设置 HSSFCellStyle style=buildStyleTitle(workBook, sheet); //标题头 HSSFCell titleCell = buildTitleLike(brandList,i,sheet); titleCell.setCellStyle(style); //根据行创建表头,并赋值 buildHeadRow(sheet,workBook); //根据行创建表头,并赋值 buildHeadRow(sheet,workBook); //表头创建后,在表头后创建获值值对应的行列及赋值 for (int j = 0; j < eligibilityBrand.size(); j++) { Integer id = eligibilityBrand.get(j).getId(); Long totalCount=productService.findBrandCountByProductId(id); buildMainbody(eligibilityBrand,totalCount,request, workBook, sheet, j); } } } //导出Excel SimpleDateFormat sim=new SimpleDateFormat("yyyyMMddhhmmss"); String strDate = sim.format(new Date()); //随机数 RandomStringUtils randomStringUtils=new RandomStringUtils(); //生成指定长度的字母和数字的随机组合字符串 String randomStr = randomStringUtils.randomAlphanumeric(5); String xlsName= strDate+randomStr+"产品信息表.xls" ; FileUtil.downloadXLSFile(request, response, workBook, xlsName); }
- poi导出excel,三大步骤
- 下载调用的封装方法FileUtil中的downloadXLSFile()
public static void downloadXLSFile(HttpServletRequest request, HttpServletResponse response, HSSFWorkbook workbook, String fileName) { OutputStream os = null; BufferedOutputStream bos = null; try { os = response.getOutputStream(); //重点突出(特别注意),通过response获取的输出流,作为服务端往客户端浏览器输出内容的一个通道 bos = new BufferedOutputStream(os); // 处理下载文件名的乱码问题(根据浏览器的不同进行处理) if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) { fileName = new String(fileName.getBytes("GB2312"),"ISO-8859-1"); } else { // 对文件名进行编码处理中文问题 fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题 fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题 } response.reset(); // 重点突出 空白行的出现原因,jsp代码编译后产生。就是有jsp生成html文件的时候,html文件内部会出现很多空白行。下载后的文件内的空白行也是这样产生的。 //因此,需要 response.reset() 来清除首部的空白行 response.setCharacterEncoding("UTF-8"); // 重点突出 response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出 // inline在浏览器中直接显示,不提示用户下载 // attachment弹出对话框,提示用户进行下载保存本地 // 默认为inline方式 response.setHeader("Content-Disposition", "attachment;filename="+ fileName); // response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出 workbook.write(bos); } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } finally { // 特别重要 // 1. 进行关闭是为了释放资源 // 2. 进行关闭会自动执行flush方法清空缓冲区内容 try { if (null != bos) { bos.close(); bos = null; } if (null != os) { os.close(); os = null; } } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } }
对应的是创建excel中的循环获取对应的需求条件
public List<Product> returnStudentList(List<Product> productList, Brand brand) { //3.循环品牌集合,产品集合对比,当存在时就定义一个解释集合接收 List eligibilityList=new ArrayList(); for (Product product : productList) { int id = product.getBrand().getId(); System.out.println(id); int id2 = brand.getId(); if(id == id2) { eligibilityList.add(product); } } return eligibilityList; }
对应的是创建excel中的创建表头,根据sheet创建row,根据row创建cell
private void createTitle(HSSFSheet sheet, String brandName) { HSSFRow row = sheet.createRow(1); HSSFRow row_9 = sheet.createRow(3); HSSFCell titalCell = row.createCell(5); titalCell.setCellValue(brandName+"列表信息"); }
对应的是创建excel中的标题头的样式设置
private HSSFCellStyle buildStyleTitle(HSSFWorkbook workBook, HSSFSheet sheet) { //设置样式 HSSFCellStyle style = workBook.createCellStyle(); HSSFFont font = workBook.createFont(); font.setFontHeightInPoints((short) 28);//字号 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗 font.setColor(HSSFColor.BLACK.index);//设置字体颜色 font.setFontName("黑体"); // 将“黑体”字体应用到当前单元格上 style.setFont(font); style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//内容左右居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//内容上下居中 //背景信息 style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); //合并单元格 sheet.addMergedRegion(new CellRangeAddress(1, 3, 5, 13)); //设置列宽(给时间的单元格的宽度给大点,防止时间显示格式错误!) sheet.setColumnWidth(5, 20*256); sheet.setColumnWidth(6, 20*256); sheet.setColumnWidth(7, 20*256); sheet.setColumnWidth(8, 20*256); sheet.setColumnWidth(9, 20*256); sheet.setColumnWidth(10, 20*256); sheet.setColumnWidth(11, 20*256); return style; }
对应的是创建excel中的内容标题头的创建
private void buildHeadRow(HSSFSheet sheet,HSSFWorkbook workBook) { //根据sheet创建行 HSSFRow rowHead = sheet.createRow(4); //根据row创建cll HSSFCell idCell = rowHead.createCell(6); idCell.setCellValue("产品编号"); HSSFCell nameCell = rowHead.createCell(7); nameCell.setCellValue("产品名称"); HSSFCell priceCell = rowHead.createCell(8); priceCell.setCellValue("产品价格"); HSSFCell brandCell = rowHead.createCell(9); brandCell.setCellValue("品牌名"); HSSFCell imgCell = rowHead.createCell(10); imgCell.setCellValue("产品主图"); HSSFCell pictureNumCell = rowHead.createCell(11); pictureNumCell.setCellValue("产品子图个数"); HSSFCellStyle fontStyle = bulidFontStyleHead(workBook); idCell.setCellStyle(fontStyle); nameCell.setCellStyle(fontStyle); brandCell.setCellStyle(fontStyle); imgCell.setCellStyle(fontStyle); priceCell.setCellStyle(fontStyle); pictureNumCell.setCellStyle(fontStyle); }
对应的是创建excel中的主体内容
private void buildMainbody(List<Product> productList,Long totalCount,HttpServletRequest request, HSSFWorkbook workBook, HSSFSheet sheet, int i) { //创建行,下标注意 HSSFRow contentRow = sheet.createRow(i+5); Product product = productList.get(i); //创建列 HSSFCell idCell = contentRow.createCell(6); idCell.setCellValue(product.getId()); HSSFCell nameCell = contentRow.createCell(7); nameCell.setCellValue(product.getProductName()); HSSFCell priceCell = contentRow.createCell(8); priceCell.setCellValue(product.getProductPrice()); if(product.getProductPrice()<50) { //年龄样式 buildPriceStyle(workBook, priceCell); }else if(product.getProductPrice()>100){ buildPriceMaxStyle(workBook, priceCell); } HSSFCell brandNameCell = contentRow.createCell(9); brandNameCell.setCellValue(product.getBrand().getBrandName()); HSSFCell imgCell = contentRow.createCell(10); buildImgUrl(workBook,request, sheet, i, product, imgCell); HSSFCell imgPrictureCell = contentRow.createCell(11); imgPrictureCell.setCellValue(totalCount); HSSFCellStyle fontStyle = bulidFontStyleHead(workBook); idCell.setCellStyle(fontStyle); nameCell.setCellStyle(fontStyle); brandNameCell.setCellStyle(fontStyle); imgPrictureCell.setCellStyle(fontStyle); imgCell.setCellStyle(fontStyle); }
对应的是主体内容中的价格的样式
private void buildPriceStyle(HSSFWorkbook workBook, HSSFCell ageCell) { //设置样式 HSSFCellStyle style = workBook.createCellStyle(); HSSFFont font = workBook.createFont(); font.setFontHeightInPoints((short) 11);//字号 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗 font.setColor(HSSFColor.RED.index);//设置字体颜色 font.setFontName("宋体"); // 将“黑体”字体应用到当前单元格上 style.setFont(font); style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//内容左右居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//内容上下居中 ageCell.setCellStyle(style); }
对应的是主体内容中的最大价格的样式
private void buildPriceMaxStyle(HSSFWorkbook workBook, HSSFCell ageCell) { //设置样式 HSSFCellStyle style = workBook.createCellStyle(); HSSFFont font = workBook.createFont(); font.setFontHeightInPoints((short) 11);//字号 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗 font.setColor(HSSFColor.BLUE.index);//设置字体颜色 font.setFontName("宋体"); // 将“黑体”字体应用到当前单元格上 style.setFont(font); style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//内容左右居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//内容上下居中 ageCell.setCellStyle(style); }
对应的是标题的样式
private HSSFCellStyle bulidFontStyleHead(HSSFWorkbook workBook) { //设置样式 HSSFCellStyle style = workBook.createCellStyle(); HSSFFont font = workBook.createFont(); font.setFontHeightInPoints((short) 11);//字号 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗 //font.setColor(HSSFColor.RED.index);//设置字体颜色 font.setFontName("宋体"); // 将“黑体”字体应用到当前单元格上 style.setFont(font); style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//内容左右居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//内容上下居中 return style; }
对应的图片的设置
private void buildImgUrl(HSSFWorkbook workBook,HttpServletRequest request, HSSFSheet sheet, int i, Product product, HSSFCell imgUrlCell) { BufferedImage bufferImg = null; File file=new File(request.getSession().getServletContext().getRealPath(product.getProductUrl())); if(file!=null && file.length()>0){ ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); try { bufferImg = ImageIO.read(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ImageIO.write(bufferImg, "jpg", byteArrayOut); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //画图的顶级管理器,一个sheet只能获取一个(一定要注意这点) HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); //anchor主要用于设置图片的属性 // HSSFClientAnchor anchor = new HSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2) HSSFClientAnchor anchor = new HSSFClientAnchor(11, i+11, 255, 255,(short) 10, 5+i, (short) 10, 5+i); anchor.setAnchorType(3); //插入图片 // HSSFPicture path = patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)); /* fileOut = new FileOutputStream("D:/测试Excel.xls"); // 写入excel文件 wb.write(fileOut); */ imgUrlCell.equals( patriarch.createPicture(anchor, workBook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG))); } }