研究了好几天基于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 parm = new HashMap();
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 map) {
try {
InputStream docis = new FileInputStream(srcPath);
CustomXWPFDocument document = new CustomXWPFDocument(docis);
// 替换段落中的指定文字
Iterator itPara = document.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
//String s = paragraph.getParagraphText();
Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List run=paragraph.getRuns();
for(int i=0;i 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 cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
for (Entry 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 = ""
+ ""
+ " "
+ " "
+ " " + " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " " + " ";
// 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");
}
}