Java poi 模板操作,替换文字、图片

    研究了好几天基于docx的word模板操作,其他的都还好,只是图片稍微有点复杂。直接看代码吧。

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
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;

public class CreateFile {

	@SuppressWarnings("resource")
	public static void main(String[] args) throws Exception{
			Map<String,String> parm = new HashMap<String, String>();
			parm.put("${bjbh}", "11");
			parm.put("${applyDepartmentPerson}", "22");
			parm.put("${receive_year}", "33");
			parm.put("${receive_month}", "44");
			parm.put("${receive_day}", "55");
			parm.put("${dealName}", "66");
			searchAndReplace ("C:/Users/Administrator/Desktop/news1.docx","C:/Users/Administrator/Desktop/neword_1.docx",parm);
	}
	
	
	
	 @SuppressWarnings("resource")
	public static void searchAndReplace(String srcPath, String destPath,Map<String, String> map) {
	        try {
	        	InputStream docis = new FileInputStream(srcPath);
	        	CustomXWPFDocument document = new CustomXWPFDocument(docis);
	            // 替换段落中的指定文字
	            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
	            while (itPara.hasNext()) {
	                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
	                //String s = paragraph.getParagraphText();        
	                Set<String> set = map.keySet();
	                Iterator<String> iterator = set.iterator();
	                while (iterator.hasNext()) {
	                    String key = iterator.next();
	                    List<XWPFRun> run=paragraph.getRuns();
	                     for(int i=0;i<run.size();i++)
	                     {
	                      if(run.get(i).getText(run.get(i).getTextPosition())!=null && run.get(i).getText(run.get(i).getTextPosition()).trim().equals(key))
	                      {    
	                        /**参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
	                         * 就可以把原来的文字全部替换掉了
	                        * */         
	                          run.get(i).setText(map.get(key),0);    
	                      }    
	                     }    
	                }    
	            }

	            // 替换表格中的指定文字=
	            Iterator<XWPFTable> itTable = document.getTablesIterator();
	            while (itTable.hasNext()) {
	                XWPFTable table = (XWPFTable) itTable.next();
	                int rcount = table.getNumberOfRows();
	                for (int i = 0; i < rcount; i++) {
	                    XWPFTableRow row = table.getRow(i);
	                    List<XWPFTableCell> cells = row.getTableCells();
	                    for (XWPFTableCell cell : cells) {
	                        for (Entry<String, String> e : map.entrySet()) {
	                            if (cell.getText().equals(e.getKey())) {
	                                cell.removeParagraph(0);
	                                cell.setText(e.getValue());
	                            }
	                        }
	                    }
	                }
	            }
	            
	            InputStream is = new FileInputStream("C:/Users/Administrator/Desktop/img1.png");
	            String blipId = document.addPictureData(is, CustomXWPFDocument.PICTURE_TYPE_PNG);
	            document.createPicture(blipId,document.getNextPicNameNumber(CustomXWPFDocument.PICTURE_TYPE_PNG), 500, 500);
	            FileOutputStream outStream = null;
	            outStream = new FileOutputStream(destPath);
	            document.write(outStream);
	            outStream.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	    }
	
	
	public static void rwdoc (){
		try{
			File file = new File("C:/Users/Administrator/Desktop/aa.doc");
			File file1 = new File("C:/Users/Administrator/Desktop/aa_11.doc");
			InputStream istr = new FileInputStream(file);
			HWPFDocument wDoc = new HWPFDocument(istr);
			Range range = wDoc.getRange();
			range.replaceText("${bjbh}", "11");
			range.replaceText("${applyDepartmentPerson}", "22");
			range.replaceText("${receive_year}", "33");
			range.replaceText("${receive_month}", "44");
			range.replaceText("${receive_day}", "55");
			range.replaceText("${dealName}", "66");
			OutputStream out = new FileOutputStream(file1);
			wDoc.write(out);
			wDoc.wait();
			out.flush();out.close();
			
		}catch (Exception e){
			
		}
		
	}

}

     以上代码实现了文字替换功能,下面实现插入图片功能。

package test;

import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
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.CTPoint2D;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTEffectExtent;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTPosH;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTPosV;

public class CustomXWPFDocument extends XWPFDocument {

	public CustomXWPFDocument(InputStream in) throws IOException {
		super(in);
	}

	public void createPicture(String blipId, int id, int width, int height) {
		final int EMU = 9525;
		width *= EMU;
		height *= EMU;

		org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR ctr = createParagraph()
				.createRun().getCTR();

		CTAnchor anchor = ctr.addNewDrawing().addNewAnchor();

		anchor.setDistT(0);
		anchor.setDistB(0);
		anchor.setDistL(0);
		anchor.setDistR(0);
		anchor.setRelativeHeight(0);
		anchor.setBehindDoc(false);
		anchor.setLocked(false);
		anchor.setLayoutInCell(false);
		anchor.setAllowOverlap(false);
		anchor.setSimplePos(null);

		CTPoint2D cp2d = anchor.addNewSimplePos();
		cp2d.setX(0);
		cp2d.setY(0);

		CTEffectExtent ctext = anchor.addNewEffectExtent();
		ctext.setL(0);
		ctext.setT(0);
		ctext.setR(6985);
		ctext.setB(635);

		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=\"Picture " + id + "\" descr=\"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=\"1459865\" cy=\"1428115\"/>"
				+ "            </a:xfrm>"
				+ "            <a:prstGeom prst=\"rect\">"
				+ "               <a:avLst/>"
				+ "            </a:prstGeom>"
				+ "         </pic:spPr>"
				+ "      </pic:pic>"
				+ "   </a:graphicData>" + "</a:graphic>";

		// CTGraphicalObjectData graphicData =
		// inline.addNewGraphic().addNewGraphicData();
		XmlToken xmlToken = null;
		try {
			xmlToken = XmlToken.Factory.parse(picXml);
		} catch (XmlException xe) {
			xe.printStackTrace();
		}
		anchor.set(xmlToken);

		anchor.setDistT(0);
		anchor.setDistB(0);
		anchor.setDistL(0);
		anchor.setDistR(0);

		CTPosH ctph = anchor.addNewPositionH();
		//ctph.setRelativeFrom(org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.STRelFromH.Enum.forString("column"));
		ctph.setPosOffset(3100000);

		CTPosV ctpv = anchor.addNewPositionV();
		//ctpv.setRelativeFrom(org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.STRelFromV.Enum.forString("paragraph"));
		ctpv.setPosOffset(5210000);
		
		CTPositiveSize2D extent = anchor.addNewExtent();
		extent.setCx(1459865);
		extent.setCy(1428115);

		CTNonVisualDrawingProps docPr = anchor.addNewDocPr();
		docPr.setId(id);
		docPr.setName("Picture " + id);
		docPr.setDescr("Generated");

	}

}

    下面是模板------

    下面是转换后效果------
 
 

猜你喜欢

转载自aa80303857.iteye.com/blog/2399584