• 导出包含图片的excel、word、pdf 笔记


    /**
    	 * 导出word
    	 * @throws Exception 
    	 */
    	@Override
    	public byte[] WordExport(
    			List<VbLibGlobalAnalyListVoRes> vbLibGlobalAnalyList, String picId) throws Exception {
    		//Blank Document 
    		CustomXWPFDocument  document= null;
    		ByteArrayOutputStream os = null;
    		try{
    			os=new ByteArrayOutputStream();
    			document= new CustomXWPFDocument ();  
            //添加标题  
            XWPFParagraph titleParagraph = document.createParagraph();  
            //设置段落居中  
            titleParagraph.setAlignment(ParagraphAlignment.CENTER);  
      
            XWPFRun titleParagraphRun = titleParagraph.createRun();  
            titleParagraphRun.setText("漏洞风险分析");  
            titleParagraphRun.setColor("000000");  
            titleParagraphRun.setFontSize(20);  
      
            //工作经历表格  
            XWPFTable ComTable = document.createTable();  
            //列宽自动分割  
            CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();  
            comTableWidth.setType(STTblWidth.DXA);  
            comTableWidth.setW(BigInteger.valueOf(9072));  
      
            //表格第一行  
            XWPFTableRow comTableRowOne = ComTable.getRow(0);  
            comTableRowOne.getCell(0).setText("编号");  
            comTableRowOne.addNewTableCell().setText("漏洞名称");  
            comTableRowOne.addNewTableCell().setText("SG编号");  
            comTableRowOne.addNewTableCell().setText("受影响资产数量");  
            comTableRowOne.addNewTableCell().setText("漏洞描述");  
            comTableRowOne.addNewTableCell().setText("发布日期");  
            
            for (int i=0;i<vbLibGlobalAnalyList.size();i++) {
            	VbLibGlobalAnalyListVoRes voRes = vbLibGlobalAnalyList.get(i);
            	 //表格第二行  
                XWPFTableRow comTableRowTwo = ComTable.createRow();  
                comTableRowTwo.getCell(0).setText(i+1+"");  
                comTableRowTwo.getCell(1).setText(voRes.getVbName());  
                comTableRowTwo.getCell(2).setText(voRes.getSgvbCode());  
                comTableRowTwo.getCell(3).setText(voRes.getInfluenceNum());
                comTableRowTwo.getCell(4).setText(voRes.getVbDesc());
                comTableRowTwo.getCell(5).setText(voRes.getFoundTime());
    		}
            
            /**
             * 插入图片
             */
            //下载mongdb图片
            byte[] fileBody = fileDao.getBody(picId);
            XWPFParagraph pargraph = document.createParagraph();
            document.addPictureData(fileBody, XWPFDocument.PICTURE_TYPE_PNG);
            document.createPicture(document.getAllPictures().size()-1, 600, 395, pargraph);
            CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();  
            XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);  
      
            document.write(os);  
            return os.toByteArray();
    		}catch (Exception e) {
    			throw e;
    		}finally{
    			if(null!=os){
    				os.close();  
    			}
    			if(null!=document){
    				document.close();
    			}
    		}
    	}
    	/**
    	 * 导出pdf
    	 */
    	@Override
    	public byte[] PdfExport(
    			List<VbLibGlobalAnalyListVoRes> vbLibGlobalAnalyList, String picId) throws Exception {
    		 ByteArrayOutputStream bos =null;
    		 Document document=null;
    	        try {
    	        	bos = new ByteArrayOutputStream(); 
    	            /** 实例化文档对象 */
    	        	document = new Document(PageSize.A4, 50, 50, 50, 50);
    	            /** 创建 PdfWriter 对象 */
    	            PdfWriter.getInstance(document,// 文档对象的引用
    	            		bos);//文件的输出路径+文件的实际名称
    	            document.open();// 打开文档
    	            /** pdf文档中中文字体的设置,注意一定要添加iTextAsian.jar包 */
    	            BaseFont bfChinese = BaseFont.createFont("STSong-Light",
    	                    "UniGB-UCS2-H", false);
    	            com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);//加入document:
    	            /** 创建章节对象 */
    //	            Paragraph title1 = new Paragraph("漏洞风险分析表", FontChinese);
    	            Chapter chapter1 = new Chapter(1);
    	            chapter1.setNumberDepth(1);
    	            /** 创建章节中的小节 */
    	            Paragraph title11 = new Paragraph("漏洞风险分析表", FontChinese);
    	            Section section1 = chapter1.addSection(title11);
    	            /** 创建表格对象(包含行列矩阵的表格) */
    	            Table t = new Table(6);// X行6列
    	           /* t.setBorderColor(new Color(220, 255, 100));
    	            t.setPadding(5);
    	            t.setSpacing(5);
    	            t.setBorderWidth(1);*/
    	            Cell c1 = new Cell(new Paragraph("编号", FontChinese));
    	            t.addCell(c1);
    	            c1 = new Cell(new Paragraph("漏洞名称", FontChinese));
    	            t.addCell(c1);
    	            c1 = new Cell(new Paragraph("SG编号", FontChinese));
    	            t.addCell(c1);
    	            c1 = new Cell(new Paragraph("受影响资产数量", FontChinese));
    	            t.addCell(c1);
    	            c1 = new Cell(new Paragraph("漏洞描述", FontChinese));
    	            t.addCell(c1);
    	            c1 = new Cell(new Paragraph("发布日期", FontChinese));
    	            t.addCell(c1);
    	            // 第二行开始不需要new Cell()
    	            for (int i = 0; i < vbLibGlobalAnalyList.size(); i++) {
    	            	VbLibGlobalAnalyListVoRes voRes = vbLibGlobalAnalyList.get(i);
    	            	 t.addCell(i+1+"");
    	            	 t.addCell(voRes.getVbName());
    	            	 t.addCell(voRes.getSgvbCode());
    	            	 t.addCell(voRes.getInfluenceNum());
    	            	 t.addCell(voRes.getVbDesc());
    	 	             t.addCell(voRes.getFoundTime());
    				}
    	            section1.add(t);
    	           
    	        	//创建章节对象
    //	            Paragraph title2 = new Paragraph("漏洞风险分析图", FontChinese);
    	            Chapter chapter2 = new Chapter(1);
    	            chapter2.setNumberDepth(1);
    	           //创建章节中的小节
    	            Paragraph title12 = new Paragraph("漏洞风险分析图", FontChinese);
    	            Section section2 = chapter2.addSection(title12);
    	            // 添加图片
    	            
    	            byte[] fileBody = fileDao.getBody(picId);
    	            
    	            Image img = Image.getInstance(fileBody);//图片的地址
    //	            img.setAbsolutePosition(mmTopx(0), mmTopx(1));
    	            img.scalePercent(50f); 
    	            document.add(chapter1);
    	            section2.add(img);
    	            document.add(chapter2);
    	            document.close();
    	            return bos.toByteArray();
    	        } catch (Exception e) {
    	           throw e;
    	        }finally{
    	        	if(null!=document){
    	        		document.close();
    	        	}
    	        	if(null!=bos){
    	        		bos.close();
    				}
    	        }
    			}
    
    /**
    	 * 导出excel
    	 * 
    	 * @throws Exception
    	 */
    	@Override
    	public byte[] excelExport(List<VbLibGlobalAnalyListVoRes> list,String picId) throws Exception {
    		ByteArrayOutputStream os = null;
    		XSSFWorkbook wb = null;
    		try{
    		// 第一步,创建一个webbook,对应一个Excel文件
    		wb = new XSSFWorkbook();
    		// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
    		XSSFSheet sheet = wb.createSheet("漏洞库分析");
    		// sheet.setColumnWidth(0, 1000*255);
    		sheet.setDefaultColumnWidth(16);
    		// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    		XSSFRow row = sheet.createRow((int) 0);
    		// 第四步,创建单元格,并设置值表头 设置表头居中
    
    		XSSFCellStyle styleCell = wb.createCellStyle();
    		styleCell.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
    		styleCell.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
    
    		styleCell.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
    		styleCell.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
    		styleCell.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
    		styleCell.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中
    		styleCell.setWrapText(true);// 设置自动换行
    		styleCell.setFillForegroundColor(IndexedColors.AQUA.getIndex());// 设置背景色
    		styleCell.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    		// 字体样式
    		XSSFFont font = wb.createFont();
    		font.setFontName("黑体");
    		font.setFontHeightInPoints((short) 10);
    		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 字体加粗
    		styleCell.setFont(font);
    
    		XSSFCellStyle styleHeffCell = wb.createCellStyle();
    
    		styleHeffCell.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
    
    		styleHeffCell.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
    		styleHeffCell.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
    		styleHeffCell.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
    		styleHeffCell.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
    		styleHeffCell.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中
    		styleHeffCell.setWrapText(true);// 设置自动换行
    
    		XSSFCell cell = row.createCell((short) 0);
    		cell.setCellValue("编号");
    		cell.setCellStyle(styleCell);
    
    		cell = row.createCell((short) 1);
    		cell.setCellValue("漏洞名称");
    		cell.setCellStyle(styleCell);
    
    		cell = row.createCell((short) 2);
    		cell.setCellValue("SG编号");
    		cell.setCellStyle(styleCell);
    
    		cell = row.createCell((short) 3);
    		cell.setCellValue("受影响资产数量");
    		cell.setCellStyle(styleCell);
    
    		cell = row.createCell((short) 4);
    		cell.setCellValue("漏洞描述");
    		cell.setCellStyle(styleCell);
    
    		cell = row.createCell((short) 5);
    		cell.setCellValue("发布日期");
    		cell.setCellStyle(styleCell);
    
    		// 第五步,写入实体数据
    
    		for (int i = 0; i < list.size(); i++) {
    
    			row = sheet.createRow((int) i + 1);
    			VbLibGlobalAnalyListVoRes vbLibGlobalAnalyListVoRes = list.get(i);
    			// 第四步,创建单元格,并设置值
    			XSSFCell hssfCell = row.createCell((short) 0);
    			hssfCell.setCellValue(i + 1);
    			hssfCell.setCellStyle(styleHeffCell);
    
    			hssfCell = row.createCell((short) 1);
    			hssfCell.setCellValue(vbLibGlobalAnalyListVoRes.getVbName());
    			hssfCell.setCellStyle(styleHeffCell);
    
    			hssfCell = row.createCell((short) 2);
    			hssfCell.setCellValue(vbLibGlobalAnalyListVoRes.getSgvbCode());
    			hssfCell.setCellStyle(styleHeffCell);
    
    			hssfCell = row.createCell((short) 3);
    			hssfCell.setCellValue(vbLibGlobalAnalyListVoRes.getInfluenceNum());
    			hssfCell.setCellStyle(styleHeffCell);
    
    			hssfCell = row.createCell((short) 4);
    			hssfCell.setCellValue(vbLibGlobalAnalyListVoRes.getVbDesc());
    			hssfCell.setCellStyle(styleHeffCell);
    
    			hssfCell = row.createCell((short) 5);
    			hssfCell.setCellValue(vbLibGlobalAnalyListVoRes.getFoundTime());
    			hssfCell.setCellStyle(styleHeffCell);
    
    		}
    			/**
    			 * 插入图片
    			 */
    			//下载图片
    			byte[] fileBody = fileDao.getBody(picId);
    			// 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
    			XSSFDrawing patriarch = sheet.createDrawingPatriarch();
    			// 八个参数,前四个表示图片离起始单元格和结束单元格边缘的位置,
    			// 后四个表示起始和结束单元格的位置,如下表示从第2列到第12列,从第1行到第15行,需要注意excel起始位置是0
    			int size = list.size();
    			XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,
    					(short) 0, (short) size+1, (short) 6, (short) size+20);
    			anchor.setAnchorType(3);
    			// 插入图片
    			patriarch.createPicture(anchor, wb.addPicture(
    					fileBody, XSSFWorkbook.PICTURE_TYPE_PNG));
    			
    		os = new ByteArrayOutputStream();
    		wb.write(os);
    		return os.toByteArray();
    	}catch(Exception e){
    		throw e;
    	}finally{
    		if(os != null){
    			os.close();
    		}
    		if(wb != null){
    			wb.close();
    		}
    		
    	}
    	}
    

      Controller调用方法

     /**
         * 下载
         * @param request
         * @param response
         * @param fileName
         * @param fileContent
         * @throws Exception
         *
         * @author linan
         */
        public static  void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName, byte[] fileContent)throws Exception{
    
            String userAgent = request.getHeader("user-agent").toUpperCase();
            if (null != userAgent && -1 != userAgent.indexOf("MSIE") || userAgent.indexOf("TRIDENT")!=-1) {
                // win10 ie edge 浏览器 和其他系统的ie
                fileName = URLEncoder.encode(fileName, "UTF-8");
                fileName = fileName.replace("+", "%20");// 处理空格变“+”的问
                fileName = fileName.replaceAll("%28", "\(");
                fileName = fileName.replaceAll("%29", "\)");
            } else {
                // fe
                fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
            }
    
            response.addHeader("Content-Disposition", "attachment;filename="" + fileName + """);
            response.addHeader("Content-Length", "" + fileContent.length);
            response.setContentType("application/octet-stream");
            response.getOutputStream().write(fileContent);
        }
    

      Html直接get调用

  • 相关阅读:
    test
    男神zyh的青睐
    HH的项链
    PAT刷题经验
    LaTeX常用数学符号
    Battle Over Cities Hard Version
    Cut
    文本生成器
    Explorer Space
    2021.04.21
  • 原文地址:https://www.cnblogs.com/e206842/p/9290562.html
Copyright © 2020-2023  润新知