這篇文章主要介紹Java如何替換word文檔文字并指定位置插入圖片,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)公司主營(yíng)汨羅網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,成都app軟件開(kāi)發(fā),汨羅h5重慶小程序開(kāi)發(fā)搭建,汨羅網(wǎng)站營(yíng)銷(xiāo)推廣歡迎汨羅等地區(qū)企業(yè)咨詢先說(shuō)下 需要的依賴包
<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>
示例,下圖

如上圖,需要替換的字符串地方“$1”為“1231”,在指定位置插入書(shū)簽,并命名“test” ,插入的圖片如下

本人也沒(méi)太過(guò)多去研究,親測(cè)通過(guò)有效,在這分享下
1.demo
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
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.Body;
import org.docx4j.wml.BooleanDefaultTrue;
import org.docx4j.wml.CTBookmark;
import org.docx4j.wml.Color;
import org.docx4j.wml.Document;
import org.docx4j.wml.Drawing;
import org.docx4j.wml.HpsMeasure;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.RPr;
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.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;import com.aisino.qysds.common.constant.ERRORConstants;
import com.aisino.qysds.common.exception.SysException;
import com.aisino.qysds.service.IExportBgService;
import com.google.common.collect.Maps;
public class ExportBgServiceImpl {
public static void main(String[] args) throws Exception {
Map<String, String> map = Maps.newHashMap();
map.put("$1", "1231");
XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage("D:\\tp\\test.docx"));
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("D:\\tp\\test1.docx");
document.write(outStream);
outStream.close();
//-----------------------------------這塊為生成圖片 和 插入圖片
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("修改類(lèi)", 1);
dataset.setValue("提示類(lèi)", 1);
dataset.setValue("校驗(yàn)不通過(guò)", 3);
dataset.setValue("正常類(lèi)", 3);
JFreeChart chart = ChartFactory.createPieChart3D(null, dataset, true, false, false);
chart.getLegend().setItemFont(new Font("黑體", Font.BOLD, 15)); // 設(shè)置圖例類(lèi)別字體
// TextTitle title = new TextTitle(titleString);
// title.setFont(new Font("黑體", Font.ITALIC, 20));//設(shè)置標(biāo)題字體
// 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對(duì)象,生成的格式,
// {0}表示section名,{1}表示section的值,{2}表示百分比。可以自定義
piePlot.setLabelGenerator(generator);// 設(shè)置百分比
piePlot.setLabelFont(new Font("黑體", Font.ITALIC, 15));// 設(shè)置餅圖中類(lèi)別字體
piePlot.setNoDataMessage("此時(shí)并沒(méi)有任何數(shù)據(jù)可用");
piePlot.setCircular(false);
piePlot.setLabelGap(0.02D);
piePlot.setIgnoreNullValues(true);// 設(shè)置不顯示空位
piePlot.setIgnoreZeroValues(true);// 設(shè)置不顯示負(fù)值或零值
String fName = "pie.png";
File file = new File("D:\\tp", fName);
if (file.exists()) {
file.delete();
}
try {
ChartUtilities.saveChartAsPNG(file, chart, 800, 500);
File file2 = new File("D:\\tp\\test1.docx");
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();
// 提取書(shū)簽并創(chuàng)建書(shū)簽的游標(biāo)
RangeFinder rt = new RangeFinder("CTBookmark", "CTMarkupRange");
new TraversalUtil(paragraphs, rt);
for (CTBookmark bm : rt.getStarts()) {
if (bm.getName().equals("test")) {// 這里的test為 word文檔中預(yù)設(shè)的 書(shū)簽名
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不是正常屏幕大小,用于設(shè)置插入圖片的大小
P p = (P) (bm.getParent());
ObjectFactory factory = new ObjectFactory();
// R對(duì)象是匿名的復(fù)雜類(lèi)型,然而我并不知道具體啥意思,估計(jì)這個(gè)要好好去看看ooxml才知道
R run = factory.createR();
// drawing理解為畫(huà)布?
Drawing drawing = factory.createDrawing();
drawing.getAnchorOrInline().add(inline);
run.getContent().add(drawing);
p.getContent().add(run);
}
}
wPackage.save(new FileOutputStream(new File("D:\\tp\\test1.docx")));
} catch (IOException e) {
}
}
}最后效果圖如下:

以上是“Java如何替換word文檔文字并指定位置插入圖片”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
新聞標(biāo)題:Java如何替換word文檔文字并指定位置插入圖片-創(chuàng)新互聯(lián)
文章位置:http://chinadenli.net/article4/cohgoe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、定制開(kāi)發(fā)、網(wǎng)站改版、商城網(wǎng)站、營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容
移動(dòng)網(wǎng)站建設(shè)知識(shí)