实验环境:POI3.7+Word2007

Word模板:

POI Word 模板 文字 图片 替换_xml

 

替换后效果:

POI Word 模板 文字 图片 替换_apache_02


 

代码:

1、入口文件


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


     

    2、封装的工具类WordUtil.java


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


       

      3、重写的类 CustomXWPFDocument


        1. package
        2.
        3. import
        4. import
        5. import
        6. import
        7. import
        8. import
        9. import
        10. import
        11. import
        12. import
        13.
        14. /**
        15. * 自定义 XWPFDocument,并重写 createPicture()方法
        16. */
        17. public class CustomXWPFDocument extends
        18. public CustomXWPFDocument(InputStream in) throws
        19. super(in);
        20. }
        21.
        22. public
        23. super();
        24. }
        25.
        26. public CustomXWPFDocument(OPCPackage pkg) throws
        27. super(pkg);
        28. }
        29.
        30. /**
        31. * @param id
        32. * @param width 宽
        33. * @param height 高
        34. * @param paragraph 段落
        35. */
        36. public void createPicture(int id, int width, int
        37. final int EMU = 9525;
        38. width *= EMU;
        39. height *= EMU;
        40. String blipId = getAllPictures().get(id).getPackageRelationship().getId();
        41. CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();
        42. ""
        43. "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
        44. " <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
        45. " <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
        46. " <pic:nvPicPr>" + " <pic:cNvPr id=\""
        47. + id
        48. "\" name=\"Generated\"/>"
        49. " <pic:cNvPicPr/>"
        50. " </pic:nvPicPr>"
        51. " <pic:blipFill>"
        52. " <a:blip r:embed=\""
        53. + blipId
        54. "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
        55. " <a:stretch>"
        56. " <a:fillRect/>"
        57. " </a:stretch>"
        58. " </pic:blipFill>"
        59. " <pic:spPr>"
        60. " <a:xfrm>"
        61. " <a:off x=\"0\" y=\"0\"/>"
        62. " <a:ext cx=\""
        63. + width
        64. "\" cy=\""
        65. + height
        66. "\"/>"
        67. " </a:xfrm>"
        68. " <a:prstGeom prst=\"rect\">"
        69. " <a:avLst/>"
        70. " </a:prstGeom>"
        71. " </pic:spPr>"
        72. " </pic:pic>"
        73. " </a:graphicData>" + "</a:graphic>";
        74.
        75. inline.addNewGraphic().addNewGraphicData();
        76. null;
        77. try
        78. xmlToken = XmlToken.Factory.parse(picXml);
        79. catch
        80. xe.printStackTrace();
        81. }
        82. inline.set(xmlToken);
        83.
        84. 0);
        85. 0);
        86. 0);
        87. 0);
        88.
        89. CTPositiveSize2D extent = inline.addNewExtent();
        90. extent.setCx(width);
        91. extent.setCy(height);
        92.
        93. CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        94. docPr.setId(id);
        95. "图片"
        96. "测试");
        97. }
        98. }

         

        http://huangqiqing123.iteye.com/blog/1927761​​