POI Word 模板 文字 图片 替换 验证通过必须3.7版本

实验环境:POI3.7+Word2007

Word模板:

替换后效果:

代码:

1、入口文件

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

2、封装的工具类WordUtil.java

Java代码 复制代码 收藏代码
  1. package test1; 
  2.  
  3. import java.io.ByteArrayInputStream; 
  4. import java.io.IOException; 
  5. import java.io.InputStream; 
  6. import java.util.Iterator; 
  7. import java.util.List; 
  8. import java.util.Map; 
  9. import java.util.Map.Entry; 
  10. import org.apache.poi.POIXMLDocument; 
  11. import org.apache.poi.openxml4j.opc.OPCPackage; 
  12. import org.apache.poi.xwpf.usermodel.XWPFParagraph; 
  13. import org.apache.poi.xwpf.usermodel.XWPFRun; 
  14. import org.apache.poi.xwpf.usermodel.XWPFTable; 
  15. import org.apache.poi.xwpf.usermodel.XWPFTableCell; 
  16. import org.apache.poi.xwpf.usermodel.XWPFTableRow; 
  17.  
  18. /**
  19. * 适用于word 2007
  20. * poi 版本 3.7
  21. */ 
  22. public class WordUtil { 
  23.  
  24.     /**
  25.      * 根据指定的参数值、模板,生成 word 文档
  26.      * @param param 需要替换的变量
  27.      * @param template 模板
  28.      */ 
  29.     public static CustomXWPFDocument generateWord(Map<String, Object> param, String template) { 
  30.         CustomXWPFDocument doc = null
  31.         try
  32.             OPCPackage pack = POIXMLDocument.openPackage(template); 
  33.             doc = new CustomXWPFDocument(pack); 
  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 (it.hasNext()) { 
  43.                     XWPFTable table = it.next(); 
  44.                     List<XWPFTableRow> rows = table.getRows(); 
  45.                     for (XWPFTableRow row : rows) { 
  46.                         List<XWPFTableCell> cells = row.getTableCells(); 
  47.                         for (XWPFTableCell cell : cells) { 
  48.                             List<XWPFParagraph> paragraphListTable =  cell.getParagraphs(); 
  49.                             processParagraphs(paragraphListTable, param, doc); 
  50.                         } 
  51.                     } 
  52.                 } 
  53.             } 
  54.         } catch (Exception e) { 
  55.             e.printStackTrace(); 
  56.         } 
  57.         return doc; 
  58.     } 
  59.     /**
  60.      * 处理段落
  61.      * @param paragraphList
  62.      */ 
  63.     public static void processParagraphs(List<XWPFParagraph> paragraphList,Map<String, Object> param,CustomXWPFDocument doc){ 
  64.         if(paragraphList != null && paragraphList.size() > 0){ 
  65.             for(XWPFParagraph paragraph:paragraphList){ 
  66.                 List<XWPFRun> runs = paragraph.getRuns(); 
  67.                 for (XWPFRun run : runs) { 
  68.                     String text = run.getText(0); 
  69.                     if(text != null){ 
  70.                         boolean isSetText = false
  71.                         for (Entry<String, Object> entry : param.entrySet()) { 
  72.                             String key = entry.getKey(); 
  73.                             if(text.indexOf(key) != -1){ 
  74.                                 isSetText = 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.                                     text = text.replace(key, ""); 
  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.                                     ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray); 
  86.                                     try
  87.                                         int ind = doc.addPicture(byteInputStream,picType); 
  88.                                         doc.createPicture(ind, width , height,paragraph); 
  89.                                     } catch (Exception e) { 
  90.                                         e.printStackTrace(); 
  91.                                     } 
  92.                                 } 
  93.                             } 
  94.                         } 
  95.                         if(isSetText){ 
  96.                             run.setText(text,0); 
  97.                         } 
  98.                     } 
  99.                 } 
  100.             } 
  101.         } 
  102.     } 
  103.     /**
  104.      * 根据图片类型,取得对应的图片类型代码
  105.      * @param picType
  106.      * @return int
  107.      */ 
  108.     private static int getPictureType(String picType){ 
  109.         int res = CustomXWPFDocument.PICTURE_TYPE_PICT; 
  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 res; 
  124.     } 
  125.     /**
  126.      * 将输入流中的数据写入字节数组
  127.      * @param in
  128.      * @return
  129.      */ 
  130.     public static byte[] inputStream2ByteArray(InputStream in,boolean isClose){ 
  131.         byte[] byteArray = null
  132.         try
  133.             int total = in.available(); 
  134.             byteArray = new byte[total]; 
  135.             in.read(byteArray); 
  136.         } catch (IOException e) { 
  137.             e.printStackTrace(); 
  138.         }finally
  139.             if(isClose){ 
  140.                 try
  141.                     in.close(); 
  142.                 } catch (Exception e2) { 
  143.                     System.out.println("关闭流失败"); 
  144.                 } 
  145.             } 
  146.         } 
  147.         return byteArray; 
  148.     } 
package test1;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

/**
 * 适用于word 2007
 * poi 版本 3.7
 */
public class WordUtil {

	/**
	 * 根据指定的参数值、模板,生成 word 文档
	 * @param param 需要替换的变量
	 * @param template 模板
	 */
	public static CustomXWPFDocument generateWord(Map<String, Object> param, String template) {
		CustomXWPFDocument doc = null;
		try {
			OPCPackage pack = POIXMLDocument.openPackage(template);
			doc = new CustomXWPFDocument(pack);
			if (param != null && param.size() > 0) {
				
				//处理段落
				List<XWPFParagraph> paragraphList = doc.getParagraphs();
				processParagraphs(paragraphList, param, doc);
				
				//处理表格
				Iterator<XWPFTable> it = doc.getTablesIterator();
				while (it.hasNext()) {
					XWPFTable table = it.next();
					List<XWPFTableRow> rows = table.getRows();
					for (XWPFTableRow row : rows) {
						List<XWPFTableCell> cells = row.getTableCells();
						for (XWPFTableCell cell : cells) {
							List<XWPFParagraph> paragraphListTable =  cell.getParagraphs();
							processParagraphs(paragraphListTable, param, doc);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;
	}
	/**
	 * 处理段落
	 * @param paragraphList
	 */
	public static void processParagraphs(List<XWPFParagraph> paragraphList,Map<String, Object> param,CustomXWPFDocument doc){
		if(paragraphList != null && paragraphList.size() > 0){
			for(XWPFParagraph paragraph:paragraphList){
				List<XWPFRun> runs = paragraph.getRuns();
				for (XWPFRun run : runs) {
					String text = run.getText(0);
					if(text != null){
						boolean isSetText = false;
						for (Entry<String, Object> 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());
								} 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 {
										int ind = doc.addPicture(byteInputStream,picType);
										doc.createPicture(ind, width , height,paragraph);
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							}
						}
						if(isSetText){
							run.setText(text,0);
						}
					}
				}
			}
		}
	}
	/**
	 * 根据图片类型,取得对应的图片类型代码
	 * @param picType
	 * @return int
	 */
	private static 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 in
	 * @return
	 */
	public static byte[] inputStream2ByteArray(InputStream in,boolean isClose){
		byte[] byteArray = null;
		try {
			int total = in.available();
			byteArray = new byte[total];
			in.read(byteArray);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(isClose){
				try {
					in.close();
				} catch (Exception e2) {
					System.out.println("关闭流失败");
				}
			}
		}
		return byteArray;
	}
}

3、重写的类 CustomXWPFDocument

Java代码 复制代码 收藏代码
  1. package test1;   
  2.    
  3. import java.io.IOException; 
  4. import java.io.InputStream; 
  5. import org.apache.poi.openxml4j.opc.OPCPackage; 
  6. import org.apache.poi.xwpf.usermodel.XWPFDocument; 
  7. import org.apache.poi.xwpf.usermodel.XWPFParagraph; 
  8. import org.apache.xmlbeans.XmlException; 
  9. import org.apache.xmlbeans.XmlToken; 
  10. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; 
  11. import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; 
  12. import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; 
  13.    
  14. /**
  15. * 自定义 XWPFDocument,并重写 createPicture()方法
  16. */ 
  17. public class CustomXWPFDocument extends XWPFDocument {   
  18.     public CustomXWPFDocument(InputStream in) throws IOException {   
  19.         super(in);   
  20.     }   
  21.    
  22.     public CustomXWPFDocument() {   
  23.         super();   
  24.     }   
  25.    
  26.     public CustomXWPFDocument(OPCPackage pkg) throws IOException {   
  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 height,XWPFParagraph paragraph) {   
  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.         String picXml = ""   
  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.         XmlToken xmlToken = null;   
  77.         try {   
  78.             xmlToken = XmlToken.Factory.parse(picXml);   
  79.         } catch (XmlException xe) {   
  80.             xe.printStackTrace();   
  81.         }   
  82.         inline.set(xmlToken);  
  83.          
  84.         inline.setDistT(0);     
  85.         inline.setDistB(0);     
  86.         inline.setDistL(0);     
  87.         inline.setDistR(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.         docPr.setName("图片" + id);     
  96.         docPr.setDescr("测试");  
  97.     }   
  98. }   
package test1;  
  
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
  
/**
 * 自定义 XWPFDocument,并重写 createPicture()方法
 */
public class CustomXWPFDocument extends XWPFDocument {  
    public CustomXWPFDocument(InputStream in) throws IOException {  
        super(in);  
    }  
  
    public CustomXWPFDocument() {  
        super();  
    }  
  
    public CustomXWPFDocument(OPCPackage pkg) throws IOException {  
        super(pkg);  
    }  
  
    /**
     * @param id
     * @param width 宽
     * @param height 高
     * @param paragraph  段落
     */
    public void createPicture(int id, int width, int height,XWPFParagraph paragraph) {  
        final int EMU = 9525;  
        width *= EMU;  
        height *= EMU;  
        String blipId = getAllPictures().get(id).getPackageRelationship().getId();  
        CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();  
        String picXml = ""  
                + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"  
                + "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"  
                + "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"  
                + "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""  
                + id  
                + "\" name=\"Generated\"/>"  
                + "            <pic:cNvPicPr/>"  
                + "         </pic:nvPicPr>"  
                + "         <pic:blipFill>"  
                + "            <a:blip r:embed=\""  
                + blipId  
                + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"  
                + "            <a:stretch>"  
                + "               <a:fillRect/>"  
                + "            </a:stretch>"  
                + "         </pic:blipFill>"  
                + "         <pic:spPr>"  
                + "            <a:xfrm>"  
                + "               <a:off x=\"0\" y=\"0\"/>"  
                + "               <a:ext cx=\""  
                + width  
                + "\" cy=\""  
                + height  
                + "\"/>"  
                + "            </a:xfrm>"  
                + "            <a:prstGeom prst=\"rect\">"  
                + "               <a:avLst/>"  
                + "            </a:prstGeom>"  
                + "         </pic:spPr>"  
                + "      </pic:pic>"  
                + "   </a:graphicData>" + "</a:graphic>";  
  
        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("测试"); 
    }  
}  

评论 3 您还未登录,请先 登录 后发表或查看评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值