当前位置:   article > 正文

使用POI 导出word模板文件_poi根据模板导出word

poi根据模板导出word

maven依赖

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.16</version>
  5. </dependency>

自定义XWPFDocument 类,重写方法插入图片:

  1. /**
  2. * @BelongsProject: exchange
  3. * @BelongsPackage: com.elens.util
  4. * @Author: xuweichao
  5. * @CreateTime: 2019-03-20 12:34
  6. * @Description: 重写XWPFDocument的方法,插入图片
  7. */
  8. public class CustomXWPFDocument extends XWPFDocument {
  9. public CustomXWPFDocument() {
  10. super();
  11. }
  12. public CustomXWPFDocument(OPCPackage opcPackage) throws IOException {
  13. super(opcPackage);
  14. }
  15. public CustomXWPFDocument(InputStream in) throws IOException {
  16. super(in);
  17. }
  18. public void createPicture(XWPFRun run,String blipId, int id, int width, int height) {
  19. final int EMU = 9525;
  20. width *= EMU;
  21. height *= EMU;
  22. //旧版本方法 .getPackageRelationship() 在该依赖包下已被删除
  23. //String blipId = getAllPictures().get(id).getPackageRelationship().getId();
  24. //在docment下创建XWPFRun 图片会被添加到文档末尾
  25. // CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline();
  26. CTInline inline =run.getCTR().addNewDrawing().addNewInline();
  27. String picXml = "" +
  28. "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
  29. " <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
  30. " <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
  31. " <pic:nvPicPr>" +
  32. " <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
  33. " <pic:cNvPicPr/>" +
  34. " </pic:nvPicPr>" +
  35. " <pic:blipFill>" +
  36. " <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
  37. " <a:stretch>" +
  38. " <a:fillRect/>" +
  39. " </a:stretch>" +
  40. " </pic:blipFill>" +
  41. " <pic:spPr>" +
  42. " <a:xfrm>" +
  43. " <a:off x=\"0\" y=\"0\"/>" +
  44. " <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
  45. " </a:xfrm>" +
  46. " <a:prstGeom prst=\"rect\">" +
  47. " <a:avLst/>" +
  48. " </a:prstGeom>" +
  49. " </pic:spPr>" +
  50. " </pic:pic>" +
  51. " </a:graphicData>" +
  52. "</a:graphic>";
  53. //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
  54. XmlToken xmlToken = null;
  55. try {
  56. xmlToken = XmlToken.Factory.parse(picXml);
  57. } catch (XmlException xe) {
  58. xe.printStackTrace();
  59. }
  60. inline.set(xmlToken);
  61. //graphicData.set(xmlToken);
  62. inline.setDistT(0);
  63. inline.setDistB(0);
  64. inline.setDistL(0);
  65. inline.setDistR(0);
  66. CTPositiveSize2D extent = inline.addNewExtent();
  67. extent.setCx(width);
  68. extent.setCy(height);
  69. CTNonVisualDrawingProps docPr = inline.addNewDocPr();
  70. docPr.setId(id);
  71. docPr.setName("Picture " + id);
  72. docPr.setDescr("Generated");
  73. }
  74. }

文件导出工具类:

  1. public class POIWordUtil {
  2. /**
  3. * 根据模板生成新word文档
  4. * 判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
  5. *
  6. * @param inputUrl 模板存放地址
  7. * @param outputUrl 新文档存放地址
  8. * @param textMap 需要替换的信息集合
  9. * @param tableList 需要插入的表格信息集合
  10. * @return 成功返回true, 失败返回false
  11. */
  12. public static boolean changWord(String inputUrl, String outputUrl,
  13. Map<String, Object> textMap, List<String[]> tableList) {
  14. //模板转换默认成功
  15. boolean changeFlag = true;
  16. try {
  17. //获取docx解析对象
  18. CustomXWPFDocument document = new CustomXWPFDocument(POIXMLDocument.openPackage(inputUrl));
  19. //解析替换文本段落对象
  20. POIWordUtil.changeText(document, textMap);
  21. //解析替换表格对象
  22. POIWordUtil.changeTable(document, textMap, tableList);
  23. //生成新的word
  24. File file = new File(outputUrl);
  25. if (!file.getParentFile().exists()) {
  26. file.getParentFile().mkdirs();
  27. }
  28. FileOutputStream stream = new FileOutputStream(file);
  29. document.write(stream);
  30. stream.close();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. changeFlag = false;
  34. }
  35. return changeFlag;
  36. }
  37. /**
  38. * 替换段落文本
  39. *
  40. * @param document docx解析对象
  41. * @param textMap 需要替换的信息集合
  42. */
  43. public static void changeText(XWPFDocument document, Map<String, Object> textMap) {
  44. //获取段落集合
  45. List<XWPFParagraph> paragraphs = document.getParagraphs();
  46. for (XWPFParagraph paragraph : paragraphs) {
  47. //判断此段落时候需要进行替换
  48. String text = paragraph.getText();
  49. if (checkText(text)) {
  50. List<XWPFRun> runs = paragraph.getRuns();
  51. for (XWPFRun run : runs) {
  52. //替换模板原来位置
  53. run.setText((String) changeValue(run.toString(), textMap), 0);
  54. }
  55. }
  56. }
  57. }
  58. /**
  59. * 替换表格对象方法
  60. *
  61. * @param document docx解析对象
  62. * @param textMap 需要替换的信息集合
  63. * @param tableList 需要插入的表格信息集合
  64. */
  65. public static void changeTable(CustomXWPFDocument document, Map<String, Object> textMap,
  66. List<String[]> tableList) {
  67. //获取表格对象集合
  68. List<XWPFTable> tables = document.getTables();
  69. for (int i = 0; i < tables.size(); i++) {
  70. //只处理行数大于等于2的表格,且不循环表头
  71. XWPFTable table = tables.get(i);
  72. if (table.getRows().size() > 1) {
  73. //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
  74. if (checkText(table.getText())) {
  75. List<XWPFTableRow> rows = table.getRows();
  76. //遍历表格,并替换模板
  77. eachTable(document, rows, textMap);
  78. } else {
  79. // System.out.println("插入"+table.getText());
  80. insertTable(table, tableList);
  81. }
  82. }
  83. }
  84. }
  85. /**
  86. * 遍历表格,包含对图片内容的替换
  87. *
  88. * @param rows 表格行对象
  89. * @param textMap 需要替换的信息集合
  90. */
  91. public static void eachTable(CustomXWPFDocument document, List<XWPFTableRow> rows, Map<String, Object> textMap) {
  92. for (XWPFTableRow row : rows) {
  93. List<XWPFTableCell> cells = row.getTableCells();
  94. for (XWPFTableCell cell : cells) {
  95. //判断单元格是否需要替换
  96. if (checkText(cell.getText())) {
  97. List<XWPFParagraph> paragraphs = cell.getParagraphs();
  98. for (XWPFParagraph paragraph : paragraphs) {
  99. List<XWPFRun> runs = paragraph.getRuns();
  100. for (XWPFRun run : runs) {
  101. // run.setText(changeValue(run.toString(), textMap),0);
  102. Object ob = changeValue(run.toString(), textMap);
  103. if (ob instanceof String) {
  104. run.setText((String) ob, 0);
  105. } else if (ob instanceof Map) {
  106. run.setText("", 0);
  107. Map pic = (Map) ob;
  108. int width = Integer.parseInt(pic.get("width").toString());
  109. int height = Integer.parseInt(pic.get("height").toString());
  110. int picType = getPictureType(pic.get("type").toString());
  111. byte[] byteArray = (byte[]) pic.get("content");
  112. ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
  113. try {
  114. String ind = document.addPictureData(byteInputStream, picType);
  115. document.createPicture(run, ind, document.getNextPicNameNumber(picType), width, height);
  116. } catch (Exception e) {
  117. e.printStackTrace();
  118. }
  119. }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. }
  126. /**
  127. * 为表格插入数据,行数不够添加新行
  128. *
  129. * @param table 需要插入数据的表格
  130. * @param tableList 插入数据集合
  131. */
  132. public static void insertTable(XWPFTable table, List<String[]> tableList) {
  133. //创建行,根据需要插入的数据添加新行,不处理表头
  134. for (int i = 1; i < tableList.size(); i++) {
  135. XWPFTableRow row = table.createRow();
  136. }
  137. //遍历表格插入数据
  138. List<XWPFTableRow> rows = table.getRows();
  139. for (int i = 1; i < rows.size(); i++) {
  140. XWPFTableRow newRow = table.getRow(i);
  141. List<XWPFTableCell> cells = newRow.getTableCells();
  142. for (int j = 0; j < cells.size(); j++) {
  143. XWPFTableCell cell = cells.get(j);
  144. cell.setText(tableList.get(i - 1)[j]);
  145. }
  146. }
  147. }
  148. /**
  149. * word跨列合并单元格
  150. */
  151. public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
  152. for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
  153. XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
  154. if (cellIndex == fromCell) {
  155. // The first merged cell is set with RESTART merge value
  156. cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
  157. } else {
  158. // Cells which join (merge) the first one, are set with CONTINUE
  159. cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
  160. }
  161. }
  162. }
  163. /**
  164. * word跨行并单元格
  165. */
  166. public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
  167. for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
  168. XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
  169. if (rowIndex == fromRow) {
  170. // The first merged cell is set with RESTART merge value
  171. cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
  172. } else {
  173. // Cells which join (merge) the first one, are set with CONTINUE
  174. cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
  175. }
  176. }
  177. }
  178. /**
  179. * 单元格设置字体
  180. * @param cell
  181. * @param cellText
  182. */
  183. private static void getParagraph(XWPFTableCell cell,String cellText){
  184. CTP ctp = CTP.Factory.newInstance();
  185. XWPFParagraph p = new XWPFParagraph(ctp, cell);
  186. p.setAlignment(ParagraphAlignment.CENTER);
  187. XWPFRun run = p.createRun();
  188. run.setText(cellText);
  189. CTRPr rpr = run.getCTR().isSetRPr() ? run.getCTR().getRPr() : run.getCTR().addNewRPr();
  190. CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();
  191. fonts.setAscii("仿宋");
  192. fonts.setEastAsia("仿宋");
  193. fonts.setHAnsi("仿宋");
  194. cell.setParagraph(p);
  195. }
  196. /**
  197. * 判断文本中时候包含$
  198. *
  199. * @param text 文本
  200. * @return 包含返回true, 不包含返回false
  201. */
  202. public static boolean checkText(String text) {
  203. boolean check = false;
  204. if (text.indexOf("$") != -1) {
  205. check = true;
  206. }
  207. return check;
  208. }
  209. /**
  210. * 匹配传入信息集合与模板
  211. *
  212. * @param value 模板需要替换的区域
  213. * @param textMap 传入信息集合
  214. * @return 模板需要替换区域信息集合对应值
  215. */
  216. public static Object changeValue(String value, Map<String, Object> textMap) {
  217. Object obj = null;
  218. Set<Map.Entry<String, Object>> textSets = textMap.entrySet();
  219. for (Map.Entry<String, Object> textSet : textSets) {
  220. //匹配模板与替换值 格式${key}
  221. String key = "${" + textSet.getKey() + "}";
  222. if (value.indexOf(key) != -1) {
  223. obj = textSet.getValue();
  224. }
  225. }
  226. if (!(obj instanceof Map)) {
  227. //模板未匹配到区域替换为空
  228. if (obj != null && checkText(obj.toString())) {
  229. obj = "";
  230. }
  231. }
  232. return obj;
  233. }
  234. /**
  235. * 根据图片类型,取得对应的图片类型代码
  236. *
  237. * @param picType
  238. * @return int
  239. */
  240. private static int getPictureType(String picType) {
  241. int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
  242. if (picType != null) {
  243. if (picType.equalsIgnoreCase("png")) {
  244. res = CustomXWPFDocument.PICTURE_TYPE_PNG;
  245. } else if (picType.equalsIgnoreCase("dib")) {
  246. res = CustomXWPFDocument.PICTURE_TYPE_DIB;
  247. } else if (picType.equalsIgnoreCase("emf")) {
  248. res = CustomXWPFDocument.PICTURE_TYPE_EMF;
  249. } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
  250. res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
  251. } else if (picType.equalsIgnoreCase("wmf")) {
  252. res = CustomXWPFDocument.PICTURE_TYPE_WMF;
  253. }
  254. }
  255. return res;
  256. }
  257. /**
  258. * 将输入流中的数据写入字节数组
  259. *
  260. * @param in
  261. * @return
  262. */
  263. public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
  264. byte[] byteArray = null;
  265. try {
  266. int total = in.available();
  267. byteArray = new byte[total];
  268. in.read(byteArray);
  269. } catch (IOException e) {
  270. e.printStackTrace();
  271. } finally {
  272. if (isClose) {
  273. try {
  274. in.close();
  275. } catch (Exception e2) {
  276. System.out.println("关闭流失败");
  277. }
  278. }
  279. }
  280. return byteArray;
  281. }
  282. }

功能测试:

  1. String file = "H:/export_template.docx";//doc 模板文件位置
  2. String outputUrl = "H:/doc/test.doc";//文件输出地址
  3. Map<String, Object> testMap = new HashMap<>();
  4. testMap.put("country", data.get("country").toString());
  5. testMap.put("birthday", data.get("birthday").toString());
  6. testMap.put("en_name", data.get("en_name").toString());
  7. testMap.put("enName", data.get("en_name").toString());
  8. testMap.put("gender", data.get("gender").toString());
  9. testMap.put("cn_name", data.get("cn_name").toString());
  10. testMap.put("introduce", data.get("introduce").toString());
  11. testMap.put("tags", data.get("tags").toString());
  12. testMap.put("main_related_china", data.get("main_related_china").toString());
  13. testMap.put("recent_related_china", data.get("recent_related_china").toString());
  14. testMap.put("type1", data.get("type1").toString());
  15. testMap.put("type2", data.get("type2").toString());
  16. testMap.put("recommend_org", data.get("recommend_org").toString());
  17. testMap.put("url_baike", data.get("url_baike").toString());
  18. testMap.put("url_facebook", data.get("url_facebook").toString());
  19. testMap.put("url_twitter", data.get("url_twitter").toString());
  20. testMap.put("url_wiki", data.get("url_wiki").toString());
  21. testMap.put("url_linkedin", data.get("url_linkedin").toString());
  22. testMap.put("url_blog", (String) data.get("url_blog");
  23. String photo = data.get("photo").toString();
  24. Map<String, Object> header = new HashMap<>();
  25. header.put("width", 150);
  26. header.put("height", 200);
  27. header.put("type", photo.substring(photo.indexOf(".") + 1));
  28. FileInputStream in = new FileInputStream("H:/img/test.png");
  29. header.put("content", POIWordUtil.inputStream2ByteArray(in, true));
  30. testMap.put("photo", header);
  31. POIWordUtil.changWord(file, outputUrl, testMap, null);

我这里数据data 是从es 取得,测试的时候搞点假数据就好,路径修改成自己的。

这里${en_name} 是提前占位,具体逻辑实现可以看一下工具类。

模板如下图:

最终效果是这样的

这里参考了网上的一些资料,但是没有达到预期的效果,通过对代码的解读做出修改,已在项目中应用,效果良好。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/307921
推荐阅读
相关标签
  

闽ICP备14008679号