POI|POI Word 模板 文字 图片 替换

POI Word 模板 文字 图片 替换
博客分类:java poi POI java WOrd 实验环境:POI3.7+Word2007
Word模板:
POI|POI Word 模板 文字 图片 替换
文章图片


替换后效果:
POI|POI Word 模板 文字 图片 替换
文章图片


代码:
1、入口文件
Java代码POI|POI Word 模板 文字 图片 替换
文章图片

  1. public class Test {
  2. public static void main(String[] args) throws Exception {
  3. Map param = new HashMap();
  4. param.put("${name}", "huangqiqing");
  5. param.put("${zhuanye}", "信息管理与信息系统");
  6. param.put("${sex}", "男");
  7. param.put("${school_name}", "山东财经大学");
  8. param.put("${date}", new Date().toString());
  9. Map header = new HashMap();
  10. header.put("width", 100);
  11. header.put("height", 150);
  12. header.put("type", "jpg");
  13. header.put("content", WordUtil.inputStream2ByteArray(new FileInputStream("c:\\new.jpg"), true));
  14. param.put("${header}",header);
  15. Map twocode = new HashMap();
  16. twocode.put("width", 100);
  17. twocode.put("height", 100);
  18. twocode.put("type", "png");
  19. twocode.put("content", ZxingEncoderHandler.getTwoCodeByteArray("测试二维码,huangqiqing", 100,100));
  20. param.put("${twocode}",twocode);
  21. CustomXWPFDocument doc = WordUtil.generateWord(param, "c:\\1.docx");
  22. FileOutputStream fopts = new FileOutputStream("c:/2.docx");
  23. doc.write(fopts);
  24. fopts.close();
  25. }
  26. }

2、封装的工具类WordUtil.java
Java代码POI|POI Word 模板 文字 图片 替换
文章图片
  1. package test1;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import org.apache.poi.POIXMLDocument;
  10. import org.apache.poi.openxml4j.opc.OPCPackage;
  11. import org.apache.poi.xwpf.usermodel.XWPFParagraph;
  12. import org.apache.poi.xwpf.usermodel.XWPFRun;
  13. import org.apache.poi.xwpf.usermodel.XWPFTable;
  14. import org.apache.poi.xwpf.usermodel.XWPFTableCell;
  15. import org.apache.poi.xwpf.usermodel.XWPFTableRow;
  16. /**
  17. * 适用于word 2007
  18. * poi 版本 3.7
  19. */
  20. public class WordUtil {
  21. /**
  22. * 根据指定的参数值、模板,生成 word 文档
  23. * @param param 需要替换的变量
  24. * @param template 模板
  25. */
  26. public static CustomXWPFDocument generateWord(Map param, String template) {
  27. CustomXWPFDocument doc = null;
  28. try {
  29. OPCPackage pack = POIXMLDocument.openPackage(template);
  30. doc = new CustomXWPFDocument(pack);
  31. if (param != null && param.size() > 0) {
  32. //处理段落
  33. List paragraphList = doc.getParagraphs();
  34. processParagraphs(paragraphList, param, doc);
  35. //处理表格
  36. Iterator it = doc.getTablesIterator();
  37. while (it.hasNext()) {
  38. XWPFTable table = it.next();
  39. List rows = table.getRows();
  40. for (XWPFTableRow row : rows) {
  41. List cells = row.getTableCells();
  42. for (XWPFTableCell cell : cells) {
  43. List paragraphListTable =cell.getParagraphs();
  44. processParagraphs(paragraphListTable, param, doc);
  45. }
  46. }
  47. }
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. return doc;
  53. }
  54. /**
  55. * 处理段落
  56. * @param paragraphList
  57. */
  58. public static void processParagraphs(List paragraphList,Map param,CustomXWPFDocument doc){
  59. if(paragraphList != null && paragraphList.size() > 0){
  60. for(XWPFParagraph paragraph:paragraphList){
  61. List runs = paragraph.getRuns();
  62. for (XWPFRun run : runs) {
  63. String text = run.getText(0);
  64. if(text != null){
  65. boolean isSetText = false;
  66. for (Entry entry : param.entrySet()) {
  67. String key = entry.getKey();
  68. if(text.indexOf(key) != -1){
  69. isSetText = true;
  70. Object value = https://www.it610.com/article/entry.getValue();
  71. if (value instanceof String) {//文本替换
  72. text = text.replace(key, value.toString());
  73. } else if (value instanceof Map) {//图片替换
  74. text = text.replace(key, "");
  75. Map pic = (Map)value;
  76. int width = Integer.parseInt(pic.get("width").toString());
  77. int height = Integer.parseInt(pic.get("height").toString());
  78. int picType = getPictureType(pic.get("type").toString());
  79. byte[] byteArray = (byte[]) pic.get("content");
  80. ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
  81. try {
  82. int ind = doc.addPicture(byteInputStream,picType);
  83. doc.createPicture(ind, width , height,paragraph);
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87. }
  88. }
  89. }
  90. if(isSetText){
  91. run.setText(text,0);
  92. }
  93. }
  94. }
  95. }
  96. }
  97. }
  98. /**
  99. * 根据图片类型,取得对应的图片类型代码
  100. * @param picType
  101. * @return int
  102. */
  103. private static int getPictureType(String picType){
  104. int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
  105. if(picType != null){
  106. if(picType.equalsIgnoreCase("png")){
  107. res = CustomXWPFDocument.PICTURE_TYPE_PNG;
  108. }else if(picType.equalsIgnoreCase("dib")){
  109. res = CustomXWPFDocument.PICTURE_TYPE_DIB;
  110. }else if(picType.equalsIgnoreCase("emf")){
  111. res = CustomXWPFDocument.PICTURE_TYPE_EMF;
  112. }else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){
  113. res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
  114. }else if(picType.equalsIgnoreCase("wmf")){
  115. res = CustomXWPFDocument.PICTURE_TYPE_WMF;
  116. }
  117. }
  118. return res;
  119. }
  120. /**
  121. * 将输入流中的数据写入字节数组
  122. * @param in
  123. * @return
  124. */
  125. public static byte[] inputStream2ByteArray(InputStream in,boolean isClose){
  126. byte[] byteArray = null;
  127. try {
  128. int total = in.available();
  129. byteArray = new byte[total];
  130. in.read(byteArray);
  131. } catch (IOException e) {
  132. e.printStackTrace();
  133. }finally{
  134. if(isClose){
  135. try {
  136. in.close();
  137. } catch (Exception e2) {
  138. System.out.println("关闭流失败");
  139. }
  140. }
  141. }
  142. return byteArray;
  143. }
  144. }

3、重写的类 CustomXWPFDocument
Java代码POI|POI Word 模板 文字 图片 替换
文章图片
  1. package test1;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import org.apache.poi.openxml4j.opc.OPCPackage;
  5. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  6. import org.apache.poi.xwpf.usermodel.XWPFParagraph;
  7. import org.apache.xmlbeans.XmlException;
  8. import org.apache.xmlbeans.XmlToken;
  9. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
  10. import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
  11. import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
  12. /**
  13. * 自定义 XWPFDocument,并重写 createPicture()方法
  14. */
  15. public class CustomXWPFDocument extends XWPFDocument {
  16. public CustomXWPFDocument(InputStream in) throws IOException {
  17. super(in);
  18. }
  19. public CustomXWPFDocument() {
  20. super();
  21. }
  22. public CustomXWPFDocument(OPCPackage pkg) throws IOException {
  23. super(pkg);
  24. }
  25. /**
  26. * @param id
  27. * @param width 宽
  28. * @param height 高
  29. * @param paragraph段落
  30. */
  31. public void createPicture(int id, int width, int height,XWPFParagraph paragraph) {
  32. final int EMU = 9525;
  33. width *= EMU;
  34. height *= EMU;
  35. String blipId = getAllPictures().get(id).getPackageRelationship().getId();
  36. CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();
  37. String picXml = ""
  38. + ""
  39. + ""
  40. + ""
  41. + "" + "
  42. + id
  43. + "\" name=\"Generated\"/>"
  44. + ""
  45. + ""
  46. + ""
  47. + "
  48. + blipId
  49. + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
  50. + ""
  51. + ""
  52. + ""
  53. + ""
  54. + ""
  55. + ""
  56. + ""
  57. + "
  58. + width
  59. + "\" cy=\""
  60. + height
  61. + "\"/>"
  62. + ""
  63. + ""
  64. + ""
  65. + ""
  66. + ""
  67. + ""
  68. + "" + "";
  69. inline.addNewGraphic().addNewGraphicData();
  70. XmlToken xmlToken = null;
  71. try {
  72. xmlToken = XmlToken.Factory.parse(picXml);
  73. } catch (XmlException xe) {
  74. xe.printStackTrace();
  75. }
  76. inline.set(xmlToken);
  77. inline.setDistT(0);
  78. inline.setDistB(0);
  79. inline.setDistL(0);
  80. inline.setDistR(0);
  81. CTPositiveSize2D extent = inline.addNewExtent();
  82. extent.setCx(width);
  83. extent.setCy(height);
  84. CTNonVisualDrawingProps docPr = inline.addNewDocPr();
  85. docPr.setId(id);
  86. docPr.setName("图片" + id);
  87. docPr.setDescr("测试");
  88. }
  89. }
【POI|POI Word 模板 文字 图片 替换】

    推荐阅读