java实现word文档中查找文本并替换文本,图片,表格

前言

        这里用的spire word for java ,用的是成都冰蓝科技有限公司的 Spire 系列,支持多种语言如:java ,.net,C#,VB等等,之后有时间再更新一些其他的如apose,Jacob 等,还有一些根据标签动态生成表格等等,奉上地址:冰蓝科技 e-iceblue | 您的办公文档开发技术专家 | C#/VB.Net Excel, Word, PowerPoint, PDF, Barcode 组件

提供spire jar 无水印全功能免费无限制使用,以及项目案例演示,包含如何引用该jar包,以及项目源码地址https://download.csdn.net/download/luolearn/89310724

查找word文档中的的文本并替换为新文本

查找word文档中的的文本并替换为图片

查找word文档中的的文本并替换为表格

一:引入maven依赖

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.4.14</version>
    </dependency>
</dependencies>

二:查找并替换

2.1 查找word文档中的的文本并替换为新文本

Spire.Doc for Java 也提供了 Document.setReplaceFirst() 方法,用于更改 Document.replace() 方法的替换模式为替换第一个匹配项或替换所有匹配项。

查找文本并替换第一个匹配项的详细操作步骤如下:

  • 创建 Document 类的对象。
  • 用 Document.loadFromFile() 方法载入 Word 文档。
  • 用 Document.setReplaceFirst() 方法将替换模式设置为仅替换第一个匹配项。
  • 用 Document.replace() 方法将 “小鹿”的第一个匹配项替换为“水牛”。
  • 用 Document.saveToFile() 方法保存结果文档。
import com.spire.doc.Document;

public class replaceText {
    public static void main(String[] args) {

        //创建 Document 类的对象
        Document document = new Document();

        //载入Word文档
        document.loadFromFile("洞穴艺术.docx");

        //将所有“鹿”的匹配项替换为“水牛”
        document.replace("小鹿", "水牛", false, true);

        //保存结果文档
        document.saveToFile("查找替换.docx");
    }
}

2.2 查找word文档中的的文本并替换为图片

Spire.Doc for Java 还支持查找文档中的文本并将其替换为图片。首先我们需要查找文本并获取所有匹配项,然后载入图片作为 DocumentObject 对象并插入到匹配项所在位置,最后将匹配项文本删除即可。

查找并替换文本为图片的详细操作步骤如下:

  • 创建 Document 类的对象。
  • 用 Document.loadFromFile() 方法载入 Word 文档。
  • 用 Document.findAllString() 方法查找文档中与“小鹿”匹配的所有匹配项。
  • 在匹配项中循环,将所有匹配项文本替换为载入的图片。
  • 用 Document.saveToFile() 方法保存文档。
    import com.spire.doc.Document;
    import com.spire.doc.DocumentObject;
    import com.spire.doc.FileFormat;
    import com.spire.doc.documents.TextSelection;
    import com.spire.doc.fields.DocPicture;
    import com.spire.doc.fields.TextRange;
    
    public class replaceTextWithImage {
    
        public static void main(String[] args) {
    
            //创建 Document 类的对象
            Document document = new Document();
    
            //载入Word文档
            document.loadFromFile("洞穴艺术.docx");
    
            //查找文档中与“小鹿”匹配的所有匹配项
            TextSelection[] selections = document.findAllString("小鹿", true, true);
    
            //循环遍历所有匹配项,替换为载入的图片
            int index = 0;
            TextRange range = null;
            for (Object obj : selections) {
    
                TextSelection textSelection = (TextSelection)obj;
    
                //创建 DocPicture 类的对象并载入图片
                DocPicture pic = new DocPicture(document);
                pic.loadImage("小鹿.png");
    
                range = textSelection.getAsOneRange();
                index = range.getOwnerParagraph().getChildObjects().indexOf(range);
                range.getOwnerParagraph().getChildObjects().insert(index,pic);
                range.getOwnerParagraph().getChildObjects().remove(range);
            }
    
            //将指定的匹配项替换为图片
            //创建 DocPicture 类的对象并载入图片
            //DocPicture pic = new DocPicture(document);
            //pic.loadImage("C:/Users/Allen/Desktop/deer.png");
            //Object object = selections[1];
            //TextSelection selection = (TextSelection) object;
            //TextRange textRange = selection.getAsOneRange();
            //int i = textRange.getOwnerParagraph().getChildObjects().indexOf(textRange);
            //textRange.getOwnerParagraph().getChildObjects().insert(i,pic);
            //textRange.getOwnerParagraph().getChildObjects().remove(textRange);
    
            //保存结果文档
            document.saveToFile("查找并替换文本为图片.docx", FileFormat.Docx_2013);
        }
    }

2.3 查找word文档中的的文本并替换为表格

2.3.1  同文档复制表格到文本标签(如A.docx文档文件中的表格复制到A.docx文档文件中的文本标签)

他会完全复制A模版中的表格的样式,替换标签文本




import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

/**
 * 复制文档中的表格到文本标签处
 * 1. 同文档复制表格到文本标签(如A.docx文档文件中的表格复制到A.docx文档文件中的文本标签)
 * 2. 不同文档复制表格到文本标签(如A.docx文档文件中的表格复制到B.docx文档文件中的文本标签)
 */
public class demoTest1 {
    public static void main(String[] args) {
        //1.同一个模版复制整个表格到文本标签处
        copyAtemplateGenerate();

    }

   

    /**
     * 复制A word模版下表格到文本标签处并且生成一个替换好的新的B word模版(A存在,B新生成)
     * @return
     */
    private static void  copyAtemplateGenerate() {
        Document document = new Document();
        //加载文档
        document.loadFromFile("A.docx");

        //查找文档中与“${Copy_Mark}”匹配的所有匹配项,所以返回的是一个数组
        //参数一:要查找的字符串 参数二:是否区分大小写 参数三:是否查找表格中的文本
        TextSelection[] selections = document.findAllString("Copy_Mark", true, true);

        Section section = document.getSections().get(0);
        //获取第一个表格
        Table originalTable =section.getTables().get(0);

        TextRange range = null;
        for (Object obj : selections) {
            TextSelection textSelection = (TextSelection)obj;

            range = textSelection.getAsOneRange();

            // 获取替换文本所在的段落
            Paragraph ownerParagraph = range.getOwnerParagraph();
            // 段落在body下面的索引
            int i = ownerParagraph.getOwner().getChildObjects().indexOf(ownerParagraph);
            // 在段落的位置插入表格
            ownerParagraph.getOwner().getChildObjects().insert(i,originalTable.deepClone());
            // 删除原来的段落
            ownerParagraph.getOwner().getChildObjects().remove(ownerParagraph);
        }

        //保存文档
        document.saveToFile("Copy_A_table.docx", FileFormat.Docx_2013);
    }

}

2.3.2  不同文档复制表格到文本标签(如A.docx文档文件中的表格复制到B.docx文档文件中的文本标签)

这个就大同小异了,一样的道理




import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

/**
 * 复制文档中的表格到文本标签处
 * 1. 同文档复制表格到文本标签(如A.docx文档文件中的表格复制到A.docx文档文件中的文本标签)
 * 2. 不同文档复制表格到文本标签(如A.docx文档文件中的表格复制到B.docx文档文件中的文本标签)
 */
public class demoTest1 {
    public static void main(String[] args) {


        //2.不同模版复制表格到文本标签处
        copyATemplateTableToBTextRange();

    }

    /**
     * 复制A word模版下表格到B模版文本标签处(A,B模版都已经存在)
     */
    private static void copyATemplateTableToBTextRange() {
        Document A_document = new Document();
        A_document.loadFromFile("A.docx");
        //获取A模版中的表格的位置
        Section section = A_document.getSections().get(0);
        //获取第一个表格
        Table originalTable =section.getTables().get(0);


        Document B_document = new Document();
        B_document.loadFromFile("B.docx");
        //找到B模版中的标签位置
        TextSelection[] selections = B_document.findAllString("Copy_Mark", true, true);

        TextRange range = null;
        for (Object obj : selections) {
            TextSelection textSelection = (TextSelection)obj;

            range = textSelection.getAsOneRange();

            // 获取替换文本所在的段落
            Paragraph ownerParagraph = range.getOwnerParagraph();
            // 段落在body下面的索引
            int i = ownerParagraph.getOwner().getChildObjects().indexOf(ownerParagraph);
            // 在B模版的标签段落的位置插入A模版的表格
            ownerParagraph.getOwner().getChildObjects().insert(i,originalTable.deepClone());
            // 删除原来的段落
            ownerParagraph.getOwner().getChildObjects().remove(ownerParagraph);
        }
        //保存文档
        B_document.saveToFile("Copy_A_table_to_B.docx", FileFormat.Docx_2013);
    }

   

}

  • 26
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用Apache POI库来操作Word文档。具体实现步骤如下: 1. 导入Apache POI库。 2. 读取需要替换Word文档。 ```java FileInputStream file = new FileInputStream("原始文档.docx"); XWPFDocument doc = new XWPFDocument(file); ``` 3. 遍历Word文档的所有段落和表格查找需要替换的字段,并进行替换。 ```java for (XWPFParagraph para : doc.getParagraphs()) { List<XWPFRun> runs = para.getRuns(); for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); String text = run.getText(0); if (text != null && text.startsWith("#") && text.endsWith("#")) { // 进行替换 run.setText("替换后的文本", 0); } } } for (XWPFTable table : doc.getTables()) { for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph para : cell.getParagraphs()) { List<XWPFRun> runs = para.getRuns(); for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); String text = run.getText(0); if (text != null && text.startsWith("#") && text.endsWith("#")) { // 进行替换 run.setText("替换后的文本", 0); } } } } } } ``` 4. 将替换后的Word文档保存到新文件。 ```java FileOutputStream out = new FileOutputStream("替换后的文档.docx"); doc.write(out); out.close(); ``` 完整代码如下: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.List; import org.apache.poi.xwpf.usermodel.XWPFDocument; 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 WordReplace { public static void main(String[] args) throws Exception { FileInputStream file = new FileInputStream("原始文档.docx"); XWPFDocument doc = new XWPFDocument(file); for (XWPFParagraph para : doc.getParagraphs()) { List<XWPFRun> runs = para.getRuns(); for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); String text = run.getText(0); if (text != null && text.startsWith("#") && text.endsWith("#")) { // 进行替换 run.setText("替换后的文本", 0); } } } for (XWPFTable table : doc.getTables()) { for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph para : cell.getParagraphs()) { List<XWPFRun> runs = para.getRuns(); for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); String text = run.getText(0); if (text != null && text.startsWith("#") && text.endsWith("#")) { // 进行替换 run.setText("替换后的文本", 0); } } } } } } FileOutputStream out = new FileOutputStream("替换后的文档.docx"); doc.write(out); out.close(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值