工具类
public class WordUtil {
/**
* 注意模板需要替换的字符串的格式
* 1、要连着打出来,或者在别的地方写好粘过来
* 2、先word转PDF,再将PDF转word
* <p>
* 替换word模板并生成新的word
*
* @param srcPath 模板地址
* @param destPath 新的word地址
* @param map 替换的内容
* @return 是否成功替换
*/
public static boolean newWord(String srcPath,
String destPath, Map<String, Object> map) {
//创建新的word文件
File errorExcelfile = new File(destPath);
if (!errorExcelfile.exists()) {
File file = errorExcelfile.getParentFile();
if (!file.exists())
file.mkdirs();
}
try {
CustomXWPFDocument doc = new CustomXWPFDocument(POIXMLDocument.openPackage(srcPath));
// 替换段落中的指定文字
Iterator<XWPFParagraph> itPara = doc.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
List<XWPFRun> runs = paragraph.getRuns();
for (int i = 0; i < runs.size(); i++) {
//遍历读取模板的内容
String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition());
if (oneparaString == null) {
continue;
}
//遍历要替换的内容 和模板相同字符串的key 被替换为value
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if (oneparaString.indexOf(key) != -1) {
Object value = entry.getValue();
if (value instanceof String) {
oneparaString = oneparaString.replace(entry.getKey(), entry.getValue().toString());
} else if (value instanceof Map) {
//判断如果值是map类型 就说明是图片
oneparaString = oneparaString.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);
//以字节流的形式 向 XWPFParagraph 添加图片
doc.addPictureData(byteInputStream, picType);
//创建图片模板
doc.createPicture(doc.getAllPictures().size() - 1, width, height, paragraph);
}
}
}
runs.get(i).setText(oneparaString, 0);
}
}
FileOutputStream outStream = null;
outStream = new FileOutputStream(destPath);
doc.write(outStream);
outStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据图片类型,取得对应的图片类型代码
*
* @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;
}
}
替换world 模板时 自定义 XWPFDocument,并重写 createPicture()方法;如果不替换图片可以不用重定义XWPFDocument
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();
System.out.println(blipId + ":" + inline);
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("测试");
}
}
注意: 注意模板需要替换的字符串的格式
* 1、在别的地方写好粘过来
* 2、先word转PDF,再将PDF转word