JAVA实现替换WORD模板中的文字和图片

时间:2024-04-15 12:20:20

1.本来有其他方法可以实现的,但是由于jar包一直有问题所以换了种,要是还有其他的更好的方法,希望可以讨论

2.废话不说直接上代码;

3.我自己加了个生成图片的方法,也可以不需要直接用已经存在的图片替换即可  ,注意jar包的引入,import的时候看清楚是什么包!!!先给出MAVEN中pom.xml需要导入的包

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-excelant</artifactId>
      <version>3.12</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <version>3.12</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.8</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.8</version>
    </dependency>


    <!-- 生成图片-->
    <dependency>
      <groupId>org.jfree</groupId>
      <artifactId>jfreechart</artifactId>
      <version>1.0.19</version>
    </dependency>
    <dependency>
      <!--支持插入图片-->
      <groupId>org.docx4j</groupId>
      <artifactId>docx4j</artifactId>
      <version>3.3.1</version>
    </dependency>

 


package com.example.demo;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.poi.POIXMLDocument;
import org.docx4j.wml.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.assertj.core.util.Maps;
import org.docx4j.TraversalUtil;

import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.finders.RangeFinder;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;

import org.docx4j.wml.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

public class ReplaceWordUtils {
//模板路径
public static final String DOC_PATH = "D:\\report\\test.docx";
//图片路径
public static final String IMAGE_PATH = "D:\\report\\test.png";
//替换文字图片后的路径
public static final String DOC_PATH2 = "D:\\report\\test1.docx";

//word文档中替换文字方法
public static void replaceContent(Map<String, String> map,String wordPath){
XWPFDocument document = null;
try
{
document = new XWPFDocument(POIXMLDocument.openPackage(wordPath));
Iterator<XWPFParagraph> itPara = document.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());
for (Map.Entry<String, String> entry : map.entrySet()) {
if (oneparaString.equals(entry.getKey())) {
oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
}
}
runs.get(i).setText(oneparaString, 0);
}
}
FileOutputStream outStream = null;
outStream = new FileOutputStream(DOC_PATH2);
document.write(outStream);
outStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}

}

public static void replaceImage(){
//-----------------------------------插入图片---------------------------------------
File file = new File(IMAGE_PATH);
try {
File file2 = new File(DOC_PATH2);
WordprocessingMLPackage wPackage = WordprocessingMLPackage.load(new FileInputStream(file2));
MainDocumentPart mainDocumentPart = wPackage.getMainDocumentPart();
Document wmlDoc = (Document) mainDocumentPart.getJaxbElement();
Body body = wmlDoc.getBody();
// 提取正文中所有段落
List<Object> paragraphs = body.getContent();
// 提取书签并创建书签的游标
RangeFinder rt = new RangeFinder("CTBookmark", "CTMarkupRange");
new TraversalUtil(paragraphs, rt);
for (CTBookmark bm : rt.getStarts()) {
if (bm.getName().equals("images")) {// 这里的test为 word文档中预设的 书签名
InputStream inputStream = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(inputStream);
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wPackage, bytes);
Inline inline = imagePart.createImageInline(null, null, 0, 1, false, 10000);//这里的100000不是正常屏幕大小,用于设置插入图片的大小
P p = (P) (bm.getParent());
ObjectFactory factory = new ObjectFactory();
// R对象是匿名的复杂类型,然而我并不知道具体啥意思,估计这个要好好去看看ooxml才知道
R run = factory.createR();
// drawing理解为画布?
Drawing drawing = factory.createDrawing();
drawing.getAnchorOrInline().add(inline);
run.getContent().add(drawing);
p.getContent().add(run);
}
}
wPackage.save(new FileOutputStream(new File(DOC_PATH2)));
} catch (Exception e) {
e.printStackTrace();
}
}


//生成图片
public static void initImg(){
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("修改类", 1);
dataset.setValue("提示类", 1);
dataset.setValue("校验不通过", 3);
dataset.setValue("正常类", 3);
JFreeChart chart = ChartFactory.createPieChart3D(null, dataset, true, false, false);
chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15)); // 设置图例类别字体
// TextTitle title = new TextTitle(titleString);
// title.setFont(new Font("黑体", Font.ITALIC, 20));//设置标题字体
// chart.setTitle(title);
PiePlot piePlot = (PiePlot) chart.getPlot();
DecimalFormat df = new DecimalFormat("0.00%");
NumberFormat nf = NumberFormat.getInstance();
StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator("{0} {2}", nf, df);// 获得StandardPieSectionLabelGenerator对象,生成的格式,
// {0}表示section名,{1}表示section的值,{2}表示百分比。可以自定义
piePlot.setLabelGenerator(generator);// 设置百分比
piePlot.setLabelFont(new Font("黑体", Font.ITALIC, 15));// 设置饼图中类别字体
piePlot.setNoDataMessage("此时并没有任何数据可用");
piePlot.setCircular(false);
piePlot.setLabelGap(0.02D);
piePlot.setIgnoreNullValues(true);// 设置不显示空位
piePlot.setIgnoreZeroValues(true);// 设置不显示负值或零值

try
{
ChartUtilities.saveChartAsPNG(new File(IMAGE_PATH), chart, 800, 500);
}
catch (IOException e)
{
e.printStackTrace();
}
}

public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("unit","4");
map.put("startValue","85");
map.put("controlRod10","90");
map.put("plan","35计划");
map.put("position","总经理处");
//替换文字
replaceContent(map,DOC_PATH);
//生成图片
initImg();
//替换图片
replaceImage();
}

}
 

4.以上是所有代码,其中模板截图如下:箭头是要替换的文字以及图片需要插入标签,替换的时候需要用到

 

 

 

 

5.最后的结果是这样的

 

 以上就是整个逻辑代码了,可以自己在尝试下,有的逻辑可以自己改改,有什么问题可以留言。