模板制作

制作word模版,${xxxx}是要替换的内容。注意${xxxx}是一个整体,中间不能断开,因为利用POI的API程序操作时,判断是否有这个${xxxx}才进行替换。

依赖的包

org.apache.poi poi 3.15org.apache.poi poi-ooxml 3.15

操作docx文件

POI在读写word docx文件时是通过xwpf模块来进行的,其核心是XWPFDocument。一个XWPFDocument代表一个docx文档,其可以用来读docx文档,也可以用来写docx文档。XWPFDocument中主要包含下面这几种对象:

  • XWPFParagraph:代表一个段落。
  • XWPFRun:代表具有相同属性的一段文本。
  • XWPFTable:代表一个表格。
  • XWPFTableRow:表格的一行。
  • XWPFTableCell:表格对应的一个单元格

具体代码:

/**  * 根据指定的参数值、模板,生成 word 文档  * @param param 需要替换的变量,key值与模板里${xxxx}的xxx一样  * @param template 模板,docx文档  */  public CustomXWPFDocument generateWord(Map param, String template) { CustomXWPFDocument doc = null;  try {  OPCPackage pack = POIXMLDocument.openPackage(template);  doc = new CustomXWPFDocument(pack);  if (param != null && param.size() > 0) { //处理段落  List paragraphList = doc.getParagraphs();  processParagraphs(paragraphList, param, doc);   //处理表格  Iterator it = doc.getTablesIterator();  while (it.hasNext()) {  XWPFTable table = it.next();  List rows = table.getRows(); for (XWPFTableRow row : rows) { List cells = row.getTableCells(); for (XWPFTableCell cell : cells) {  List paragraphListTable = cell.getParagraphs();  processParagraphs(paragraphListTable, param, doc);  }  }  }  }  } catch (Exception e) {  e.printStackTrace();  }  return doc;  }
/**  * 处理段落  * @param paragraphList  */  public void processParagraphs(List paragraphList,Map param,CustomXWPFDocument doc){ if(paragraphList != null && paragraphList.size() > 0){  for(XWPFParagraph paragraph : paragraphList){ List runs = paragraph.getRuns();  for (XWPFRun run : runs) {  String text = run.getText(0);  if(text != null){  boolean isSetText = false;  for (Entry entry : param.entrySet()) {  String key = "${"+ entry.getKey() +"}"; if(text.indexOf(key) != -1){ isSetText = true;  Object value = entry.getValue();  if (value instanceof String) {//文本替换  text = text.replace(key, value.toString());  //System.out.println(text); } else if (value instanceof Double) { text = text.replace(key, value.toString()); } else if (value instanceof Map) {//图片替换 text = text.replace(key, "");  Map pic = (Map)value;  int width = Integer.parseInt(pic.get("width").toString());  int height = Integer.parseInt(pic.get("height").toString());  int picType = getPictureType(pic.get("type").toString());  byte[] byteArray = (byte[]) pic.get("content");  ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);  try {  String ind = doc.addPictureData(byteInputStream, picType); int id = doc.getNextPicNameNumber(picType); createPicture(id, ind, width , height, run); //System.out.println("图片替换"); } catch (Exception e) {  e.printStackTrace();  }  }  }  }  if(isSetText){  run.setText(text,0);  }  }  }  }  }  }
/**  * 根据图片类型,取得对应的图片类型代码  * @param picType  * @return int  */  private int getPictureType(String picType){ int res = CustomXWPFDocument.PICTURE_TYPE_PICT;  if(picType != null){  if(picType.equalsIgnoreCase("png")){  res = CustomXWPFDocument.PICTURE_TYPE_PNG; }else if(picType.equalsIgnoreCase("dib")){  res = CustomXWPFDocument.PICTURE_TYPE_DIB;  }else if(picType.equalsIgnoreCase("emf")){  res = CustomXWPFDocument.PICTURE_TYPE_EMF;  }else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){  res = CustomXWPFDocument.PICTURE_TYPE_JPEG;  }else if(picType.equalsIgnoreCase("wmf")){  res = CustomXWPFDocument.PICTURE_TYPE_WMF;  }  }  return res; } /**  * @param id  * @param width 宽  * @param height 高  * @param run 段落 */  public void createPicture(int id, String blipId, int width, int height,XWPFRun run) { final int EMU = 9525;  width *= EMU;  height *= EMU;   CTInline inline = run.getCTR().addNewDrawing().addNewInline();  String picXml = ""  + ""  + " "  + " "  + " " + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " "  + " " + "";   inline.addNewGraphic().addNewGraphicData();  XmlToken xmlToken = null;  try {  xmlToken = XmlToken.Factory.parse(picXml);  } catch (XmlException xe) {  xe.printStackTrace();  }  inline.set(xmlToken);   inline.setDistT(0);  inline.setDistB(0);  inline.setDistL(0);  inline.setDistR(0);   CTPositiveSize2D extent = inline.addNewExtent();  extent.setCx(width);  extent.setCy(height);   CTNonVisualDrawingProps docPr = inline.addNewDocPr();  docPr.setId(id);  docPr.setName("图片" + id);  docPr.setDescr("测试");  }

输出docx文档

把返回的XWPFDocument写入到对应的流中。

FileOutputStream fopts = new FileOutputStream("E://andy.docx");doc.write(fopts);

转pdf文档

相关包的依赖:

fr.opensagres.xdocreportfr.opensagres.poi.xwpf.converter.core2.0.1fr.opensagres.xdocreportfr.opensagres.poi.xwpf.converter.pdf2.0.1

把XWPFDocument转成PDF:

FileOutputStream fopts = new FileOutputStream(new FIle("E://andy.pdf"));PdfOptions options = PdfOptions.create();options.fontProvider(new IFontProvider() { @Override public Font getFont(String s, String s1, float v, int i, Color color) { try { BaseFont bfChinese = BaseFont.createFont(rootPath + "wordtemplate/simsun.ttf

java poi doc转docx_POI动态插入数据到Word文档相关推荐

  1. 关于用java编写生成word文档,动态添加数据到word文档的一些心得

    关于用java编写生成word文档,动态添加数据到word文档的一些心得,经过翻阅了无数的有用的和无用的资料以后,总算找到了一种靠谱的方法 1.概述 经过反反复复的查阅资料,总算找到了一个靠谱的生成w ...

  2. java将后台数据库查询到的数据导出word文档当中

    java将后台数据库查询到的数据导出word文档当中 之前项目需求使用Java导出word文档,一直没有进行整理,今天把它进行整理出来,以便以后使用到:下面是导出的word文档. // 前端报告表格 ...

  3. Java 将xml模板动态填充数据转换为word文档

    需要用到的jar包: commons-codec-1.10.jar freemarker-2.3.21.jar jacob-1.6.jar 实现思路: 1.先将word文档另存为 : Word 200 ...

  4. java 导出word 带格式_java 导出数据为word文档(保持模板格式)

    导出数据到具体的word文档里面,word有一定的格式,需要保持不变 这里使用freemarker来实现: ①:设计好word文档格式,需要用数据填充的地方用便于识别的长字符串替换  如  aaaaa ...

  5. java如何根据模板填充数据生成word文档

    java根据模板填充数据生成word文档 这篇文章干什么? 思路总览 1.准备word模板 2.转换文件格式 3.编写代码 补充--下载流 这篇文章干什么?   使用代码将word模板内容进行替换,并 ...

  6. java 获取office文件页数_jacob如何获取word文档的页码

    ActiveXComponent app = new ActiveXComponent("Word.Application"); //启动word String inFile = ...

  7. Java项目中利用Freemarker模板引擎导出--生成Word文档

    应邀写的一篇文章:Java项目中利用Freemarker模板引擎导出--生成Word文档 资源下载:https://download.csdn.net/download/weixin_41367523 ...

  8. java毕业论文_【毕业论文】基于java的博客网站设计与开发毕业论文(word文档)

    <[毕业论文]基于java的博客网站设计与开发毕业论文.doc>由会员分享,可免费在线阅读全文,更多与<[毕业论文]基于java的博客网站设计与开发毕业论文(word文档)>相 ...

  9. 如何在富文本中插入表情,word文档,及数学公式?

    前言 互联网寒冬一直在持续,不知道大家过的还好吗?不过话说回来,技术过硬,你在哪里都是最靓的仔.今天就给大家补充一点弹药,如何在富文本中插入表情,word文档,及数学公式. 为什么是 TinyMCE ...

最新文章

  1. python求10的所有因数_python怎么求因数
  2. Spring集成MyBatis框架
  3. 网络编程: 基于UDP协议的socket
  4. ASP.NET MVC 入门7、Hellper与数据的提交与绑定
  5. 深入理解Linux内核01:内存寻址
  6. 无法启动windows安全中心服务
  7. js语音识别_js 语音识别_js 语音识别库 - 云+社区 - 腾讯云
  8. 微服务架构下的数据一致性:概念及相关模式
  9. NVIDIA Nsight Compute,Nsight Systems, Nsight Graphics,Nsight Deep Learning Designer简介-草稿
  10. UNIX编程艺术 UNIX哲学
  11. 2022-2028全球全站仪市场现状及未来发展趋势
  12. Python自动化测试之PO模式
  13. 双目相机标定(MATLAB TOOLBOX_calib)
  14. 滕振宇谈如何进行单元测试
  15. 8脚 tja1050t_高速光耦:CAN总线通信硬件原理图(采用TJA1050T CAN总线驱
  16. wifi连接状态android,判断android设备wifi连接状态
  17. 百度CarLife Android车机端黑屏问题
  18. 虎牙、斗鱼同道同命:共同御寒
  19. 纯Asp实现微信支付
  20. 嵌入式应用-详解移植并使用freetype显示文字

热门文章

  1. kettle-多文件合并
  2. python os读取文件
  3. 【AtCoder】ARC 081 E - Don't Be a Subsequence
  4. PlatformTransactionManager
  5. 做了一个验证码识别的网站
  6. 今天学得有点多——end用法
  7. 服务器放在机柜_服务器网络机柜的保养维护
  8. 值传递与引用传递区别,具体表现
  9. 计算机桌面变色怎么办,电脑屏幕变色了怎么办
  10. dlib疲劳检测_基于OpenCV的实时睡意检测系统