word中加入excel附件
excel单元格中插入图片
word freemarker
Excel poi 制作, jxl 插入图片

压缩图片/宽高,动态控制单元格高度与宽度

1.word 需要模板
手动创建word excel .向word中插入excel附件并另存为 word xml 格式


替换符替换 文字 和附件base64内容
有两个binaryData标签 一个是base64,另一个是附件显示的样式

/*** word附件导出*/@ResponseBody@RequestMapping(value = "/generateReports", method = RequestMethod.GET)public void generateReports(HttpServletRequest request, HttpServletResponse response) throws Exception {//查询数据Map condition = getSelection(request);//生成excelLong num = System.currentTimeMillis();String filename = num + ".xls";sendExcel(request, response, filename);//制作wordWordUtil wordUtil = new WordUtil();Map<String, Object> dataMap = new HashMap<String, Object>();/**wordTemplate*/Department dept = (Department) request.getSession().getAttribute("CURRENT_DEPT");
//        List<Map> mapList = sortingService.findShopInfoBySort2(condition);// if (mapList.size() > 0) {//向word中添加数据mapDate startTime = DateUtil.parseTime(start);Date endTime = DateUtil.parseTime(end);String startTime1 = new SimpleDateFormat("yyyy年MM月dd日").format(startTime);String endTime1 = new SimpleDateFormat("yyyy年MM月dd日").format(endTime);dataMap.put("startTime", startTime1);dataMap.put("endTime", endTime1);//  }//调试
//        Thread.sleep(1000);
//        dataMap.put("excelEnclosure", wordUtil.getFileStr(filePath + "副本" + filename));//写入try {response.setCharacterEncoding("UTF-8");response.setHeader("content-Type", "application/msword");response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("函告" + num + ".doc", "UTF-8"));} catch (Exception ex) {ex.printStackTrace();}wordUtil.createDoc(dataMap, response, "wordTemplate", filePath + "函告" + num + ".doc");//删除临时文件File file = new File(filePath + "副本" + filename);if (file.exists()) {file.delete();}}public class WordUtil {public Configuration configure=null;public WordUtil(){//       configure=new Configuration(Configuration.VERSION_2_3_22);configure=new Configuration();configure.setDefaultEncoding("utf-8");}
//创建wordpublic void createDoc( Map<String,Object> dataMap,HttpServletResponse response, String downloadType, String savePath){try {//加载需要装填的模板Template template=null;//设置模板装置方法和路径,FreeMarker支持多种模板装载方法。可以从servlet,classpath,数据库装载。//加载模板文件,放在template下configure.setClassForTemplateLoading(this.getClass(), "/com/~/util/template");//设置对象包装器//configure.setObjectWrapper(new DefaultObjectWrapper());//设置异常处理器configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);//定义Template对象,注意模板类型名字与downloadType要一致template=configure.getTemplate(downloadType + ".xml");File outFile=new File(savePath);Writer out=null;//指定编码表需使用转换流,转换流对象要接收一个字节输出流out = response.getWriter();template.process(dataMap, out);out.close();} catch (IOException e) {e.printStackTrace();} catch (TemplateException e) {e.printStackTrace();}}}/*** 制作excel*/public void sendExcel(HttpServletRequest request, HttpServletResponse response, String filename) {//condition 筛选条件Map condition = getSelection(request);//获取数据List<TShopCheckInfo> list = this.tShopCheckInfoService.selectShopInfoList(condition);//列头String[] title = {  "是否", "图片",};String sheetName = "sheet1";String[][] content = new String[list.size()][2];try {int nu = 50;if (list.size() < nu) {nu = list.size();}//循环添加数据   数据库存的图片地址for (int i = 0; i < list.size(); i++) {content[i][0] = list.get(i).getEscape() ? (StringUtils.isNotEmpty(list.get(i).getEscapeText()) ? "是(" + list.get(i).getEscapeText() + ")" : "是") : "否";content[i][1] = list.get(i).getEscapeImgs();}} catch (Exception e) {e.printStackTrace();}HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);try {// TODO: 2020/7/29  地址需要更换//输出Excel文件// 这里是先将文件输出到服务器本地,再用WritableWorkbook进行图片处理FileOutputStream output = new FileOutputStream(filePath + filename);wb.write(output);output.flush();//测试Thread.sleep(1000);//插入图片到excelList<String> nameList = new ArrayList<>();excelImgUpdate(filePath, filename, list, nameList);//响应到客户端
//            FileInputStream inputStream = new FileInputStream(filePath + "副本" + filename);
//            org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(inputStream);//setHeader
//            downLoadExcel("附件" + filename, response, workbook);
//            FileOutputStream output = new FileOutputStream(filePath + filename);//删除临时文件
//            nameList.add(filePath + "副本" + filename);nameList.add(filePath + filename);delTemporary(nameList);} catch (Exception e) {e.printStackTrace();}}package com.ztwx.ezxf.util;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
public class ExcelUtil {/*** 导出Excel*/public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {// 第一步,创建一个HSSFWorkbook,对应一个Excel文件if (wb == null)wb = new HSSFWorkbook();// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheetHSSFSheet sheet = wb.createSheet(sheetName);//设置单元格的宽度sheet.setDefaultColumnWidth(18);//设置第一列宽度sheet.setColumnWidth(0, 252*40+323);//设置第四列宽度sheet.setColumnWidth(3, 252*25+323);// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制HSSFRow row = sheet.createRow(0);// 第四步,创建单元格,并设置值表头 设置表头居中HSSFCellStyle style = wb.createCellStyle();style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中//声明列对象HSSFCell cell = null;HSSFCell cell2 = null;HSSFFont font = wb.createFont();//创建标题for (int i = 0; i < title.length; i++) {cell = row.createCell(i);cell.setCellValue(title[i]);//字体
//          font.setBoldweight(Font.BOLDWEIGHT_BOLD);font.setFontHeightInPoints((short) 12);style.setFont(font);cell.setCellStyle(style);}//创建内容for (int i = 0; i < values.length; i++) {row = sheet.createRow(i + 1);//清空字体
//          font.setBoldweight((short)400);
//          font.setBold(false);
//          style.setFont(font);for (int j = 0; j < values[i].length; j++) {//将内容按顺序赋给对应的列对象cell2 = row.createCell(j);if(StringUtils.isNotBlank(values[i][j])){cell2.setCellValue(values[i][j]);}else{cell2.setCellValue("/");}//              内容设置样式cell2.setCellStyle(style);}}return wb;}
}//向excel 加入图片public List<String> excelImgUpdate(String filePath, String filename, List<TShopCheckInfo> list, List<String> nameList) throws Exception {Workbook wb = Workbook.getWorkbook(new File(filePath + filename)); // 获得原始文档//创建副本;WritableWorkbook workbook = Workbook.createWorkbook(new File(filePath + "副本" + filename), wb);WritableSheet sheet = workbook.getSheet(0);//调用图片插入函数  图片插入的行列//用map存放有图片时候对应的行信息  列固定
//        Map<Integer, ArrayList> map = new HashMap();for (int i = 0; i < list.size(); i++) {//8   插入对应的列String json9 = list.get(i).getEscapeImgs();ArrayList arrayList9 = getImgSrc(json9);if (arrayList9.size() > 0) {nameList = imgExcelService.addPictureToExcel(nameList, sheet, arrayList9, i + 1, 8);}}//写入Excel表格中;workbook.write();//关闭流;workbook.close();return nameList;}//图片压缩与写入  单元格控制
public List<String> addPictureToExcel(List<String> nameList,WritableSheet picSheet, ArrayList pictureFilePaths, double cellRow, double cellCol)throws Exception {final double cellSpace = 0.02;//图片之间的间隔 占比double picWidthMax = 0;double picHeightSum = 0;//空出图片 离上下边框的距离ImgFile[] imgFiles = new ImgFile[pictureFilePaths.size()];//存放临时文件名for (int i = 0; i < pictureFilePaths.size(); i++) {ImgFile imgFile = new ImgFile();//下载图片到本地Long da = System.currentTimeMillis();
//            String filePath = AddressUtil.getMacOrWin();String path = filePath + da + ".jpg";nameList.add(path);downloadPicture(pictureFilePaths.get(i).toString(), path);//图片压缩
//            Thumbnails.of(path).size(300,300).toFile(path);CompressImageUtil.reduceImg(path,path,0,0,0.5f);File imageFile = new File(path);// 读入图片BufferedImage picImage = ImageIO.read(imageFile);ByteArrayOutputStream pngByteArray = new ByteArrayOutputStream();//将其他图片格式写成png的形式ImageIO.write(picImage, "PNG", pngByteArray);imgFile.setPngByteArray(pngByteArray);// 取得图片的像素高度,宽度//这里设置图片在单元格的尺寸 原理不清楚  该值为具体实验值double picWidth = picImage.getWidth() * 0.06;
//            double picWidth = picImage.getWidth() ;double picHeight = picImage.getHeight() * 7;
//            double picHeight = picImage.getHeight() ;imgFile.setHeigth(picHeight);imgFile.setWidth(picWidth);//汇总if (picWidth > picWidthMax) {picWidthMax = picWidth;}picHeightSum += picHeight;imgFiles[i] = imgFile;}WritableFont font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED);WritableCellFormat cellFormat = new WritableCellFormat(font);//设置背景颜色;cellFormat.setBackground(Colour.WHITE);//设置边框;cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);//设置自动换行;cellFormat.setWrap(true);//设置文字居中对齐方式;cellFormat.setAlignment(Alignment.CENTRE);//设置垂直居中;cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);Label imageLabel = new Label((int) cellCol, (int) cellRow, "", cellFormat);picSheet.addCell(imageLabel);//获取图片需要插入的单元格
//        WritableCell cell =picSheet.getWritableCell(0, 0);//设置单元格宽高picSheet.setColumnView((int) cellCol, (int) picWidthMax);//列宽picSheet.setRowView((int) cellRow, (int) picHeightSum);//行高double widthStart = cellSpace;//开始宽度double heightStart = cellSpace;//开始高度//插入图片for (ImgFile imgFile0 : imgFiles) {double heigthFact = imgFile0.getHeigth() / picHeightSum;//实际高度double widthFact = imgFile0.getWidth() / picWidthMax;//图片高度压缩了cellSpace+moreHeight,目的是为了该图片高度不超出单元格if (heightStart + heigthFact >= 1) {double moreHeight = heightStart + heigthFact - 1.00;heigthFact -= moreHeight;heigthFact -= cellSpace;}//图片宽度压缩了cellSpace,目的是为了该图片宽度不超出单元格if (widthFact >= 1) {widthFact -= cellSpace;}//生成图片对象WritableImage image = new WritableImage(cellCol + widthStart, cellRow + heightStart,widthFact, heigthFact, imgFile0.getPngByteArray().toByteArray());//将图片对象插入到sheetpicSheet.addImage(image);//开始高度累加,获取下一张图片的起始高度(相对该单元格)heightStart += heigthFact;heightStart += cellSpace;//图片直接间隔为cellSpace}return nameList;}private static void downloadPicture(String urlList, String path) {URL url = null;try {url = new URL(urlList);DataInputStream dataInputStream = new DataInputStream(url.openStream());FileOutputStream fileOutputStream = new FileOutputStream(new File(path));ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int length;while ((length = dataInputStream.read(buffer)) > 0) {output.write(buffer, 0, length);}BASE64Encoder encoder = new BASE64Encoder();String encode = encoder.encode(buffer);//返回Base64编码过的字节数组字符串System.out.println(encode);fileOutputStream.write(output.toByteArray());dataInputStream.close();fileOutputStream.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

java 向word中添加excel附件并向excel单元格中加入图片并压缩图片并根据图片动态控制单元格高度宽度相关推荐

  1. R语言使用scatterplot3d包的scatterplot3d函数可视化3D散点图(3D scatter plots)、在3D散点图中添加垂直线和数据点描影、3D图中添加回归平面

    R语言使用scatterplot3d包的scatterplot3d函数可视化3D散点图(3D scatter plots).在3D散点图中添加垂直线和数据点描影.3D图中添加回归平面(overlaid ...

  2. android 设置 linearlayout 高度,在RelativeLayout中动态设置LinearLayout高度/宽度

    我在RelativeLayout中有一个linearLayout.我需要能够根据屏幕尺寸动态设置线性布局的高度.我有一些困难. 我怎么能做到这一点?在RelativeLayout中动态设置Linear ...

  3. java操作word,添加页眉,页眉图片,替换书签,添加水印(全)

    java操作word文档,添加页眉文本,页眉图片,替换书签,水印 原模板截图: 生成后的文档效果截图: 第一步:引入maven <dependency><groupId>spi ...

  4. 使用java将word文档docx,doc(包含图形,文本框)完美转换成所有格式图片(pdf,png,gif,jpeg等等)

    使用java将word文档docx,doc(包含图形,文本框,图片等)完美转换成所有格式图片(pdf,png,gif,jpeg等等)下文中附带代码,效果图等 思路 使用到的包 实现代码 效果图: 思路 ...

  5. python向mysql中添加数据标签_用python在MySQL中写入数据和添加数据

    在笔者之前的博文中,已介绍了用python连接与mysql数据库的知识.包括如何安装python连接mysql的pymysql包,如何通过cusor语句将python与mysql连接起来,以及如何用p ...

  6. python在子类中添加新的属性_pycharm实现在子类中添加一个父类没有的属性

    我就废话不多说了,还是直接看代码吧! class Car(): """一次模拟汽车的简单尝试""" def __init__(self, m ...

  7. 服务中添加mysql服务_Windows平台下在服务中添加MySQL

    widows下查看服务 1.桌面计算机-->右键-->管理-->计算机管理(本地)--->服务和应用程序-->服务 2.运行 中输入 services.msc 在服务中添 ...

  8. 计算机管理中添加用户属性,如何在计算机右键菜单栏中添加属性选项

    如何在计算机右键菜单栏中添加属性选项 电脑是现在最常用的工具之一,有些用户想知道如何在计算机右键菜单栏中添加属性选项,接下来小编小编就给大家介绍一下具体的操作步骤. 具体如下: 1. 首先第一步按下[ ...

  9. 向对象中添加数据_在RMarkdown编译HTML文件中添加数据下载按钮

    介绍一个工具包, 主要是用来解决我平常写文档时文档和结果分离的问题. 它可以在 RMarkdown 输出的 HTML 文件中添加下载数据的按钮, 而不需要运行 shiny 模式. 安装 install ...

最新文章

  1. java.sql在哪_我的Java访问MS SQL的程序错在哪了?谢谢!
  2. 201621123055《JAVA程序设计》第七周学习总结
  3. Hive数据导入Elasticsearch
  4. XMLHttpRequest
  5. JVM - 剖析Java对象头Object Header之对象大小
  6. python多级网址爬取_python-29:多级页面爬取源码
  7. js中自执行函数(function(){})()和(function(){}())区别
  8. poj 2705 Tangled in Cables 基础prim
  9. 字符串的排列组合问题
  10. html怎么把正方形改成圆形,css中如何把正方形变成圆形
  11. 阿里云服务器 ECS 数据盘与系统盘是什么?
  12. 单目标跟踪 Siamese系列网络:SiamFC、SiamRPN、one-shot跟踪、one-shotting单样本学习、DaSiamRPN、SiamRPN++、SiamMask
  13. 欢迎来到魔法的未来~
  14. MongoDB高性能、高可用之副本集、读写分离、分片、操作实践
  15. 亲测bitLock再次上锁方法
  16. 织梦dedecms 仿制目标网站首页
  17. for循环--下标越界导致死循环原因
  18. 景瑞地产商业智能BI整体实施过程
  19. win10下安装并启动zookeeper
  20. 【博学谷学习记录】超强总结,用心分享|人工智能第五课Python中变量的应用场景及常用方法II

热门文章

  1. 什么是IO多路复用,理解IO多路复用
  2. C语言 文件的打开方式
  3. Java - JDK动态代理原理
  4. 几种矩阵分解算法: LU分解,Cholesky分解,QR分解,SVD分解,Jordan分解
  5. 杨辉三角寄数列求和c语言,杨辉三角与高阶等差数列的求和
  6. 心跳包机制及Socket通信服务的心跳包
  7. DP方法(动态规划) 寻找最长公共子序列 LCS问题(c++)
  8. npm 的 --unsafe-perm 参数
  9. supermap新建数据源_supermap iDesktop 处理数据集及生成场景缓存
  10. zynq7000 资源介绍