java读取word并搜索内容

支持word
package com.data.util;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileContentSearch2 {

    private static String FileName = "D:\\dataword";// 文件夹名字

    private static String FileEnd = "docx";// 文件名称后缀 txt sql bat

    private static String SearchStr = "哈";//要查找的字符串

    private static Boolean IngronCase = true;// 是否区分大小写

    private static List<String> pathlist = new ArrayList<>();

    public static void main(String[] args) {


        //解析docx模板并获取document对象
        XWPFDocument document;
        //获取XWPFRun对象输出整个文本内容
        StringBuffer tempText = new StringBuffer();
        pathlist = getFileList(FileName);
        for (int k = 0; k < pathlist.size(); k++) {
            File file = new File(pathlist.get(k));
            if (file.exists()) {
                try {
                    document = new XWPFDocument(POIXMLDocument.openPackage(file.toString()));
                    //获取整个文本对象
                    List<XWPFParagraph> allParagraph = document.getParagraphs();
                    for (XWPFParagraph xwpfParagraph : allParagraph) {
                        List<XWPFRun> runList = xwpfParagraph.getRuns();
                        for (XWPFRun xwpfRun : runList) {
                            tempText.append(xwpfRun.toString());
                            if (tempText != null) {
                                if (IngronCase) {
                                    if (tempText.toString().contains(SearchStr)) {
                                        System.out.println("找到了"+tempText+"文件"+file.getName());
                                        break;
                                    }
                                } else {
                                    if (tempText.toString().toLowerCase().contains(SearchStr.toLowerCase())) {
                                        System.out.println("找到了");
                                        break;
                                    }
                                }
                            }
                            tempText.setLength(0);
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }        //文档内容
                //return tempText.toString();
            }
        }
    }

    public static List<String> getFileList(String strPath) {
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if (files[i].isDirectory()) { // 判断是文件还是文件夹
                    getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
                } else if (fileName.endsWith("." + FileEnd)) { // 判断文件名是否以.avi结尾
                    String strFileName = files[i].getAbsolutePath();
                    pathlist.add(strFileName);
                } else {
                    continue;
                }
            }

        }
        return pathlist;
    }
}


  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用 Apache POI 库来读取 Word 文档并操作书签。以下是一个 Java 示例代码,可以读取 Word 文档中的指定书签,并将其内容替换为指定的文本: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.xmlbeans.XmlCursor; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTMarkupRange; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; public class WordBookmarkReplace { public static void main(String[] args) throws Exception { String filePath = "path/to/word/document.docx"; String bookmarkName = "bookmark1"; String replacementText = "replacement text"; // Load the Word document POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath)); XWPFDocument doc = new XWPFDocument(fs); // Find the bookmark by name CTBookmark bookmark = findBookmarkByName(doc, bookmarkName); if (bookmark == null) { throw new IllegalArgumentException("Bookmark not found: " + bookmarkName); } // Replace the bookmark content with the replacement text CTMarkupRange range = bookmark.getDomNode().getFirstChild().getDomNode().getFirstChild(); XmlCursor cursor = range.newCursor(); XWPFParagraph p = doc.getParagraphArray(cursor.getBookmarkId()); XWPFRun r = p.getRuns().get(0); r.setText(replacementText, 0); // Save the modified document FileOutputStream out = new FileOutputStream(filePath); doc.write(out); out.close(); doc.close(); } private static CTBookmark findBookmarkByName(XWPFDocument doc, String name) { for (CTBookmark bookmark : doc.getDocument().getBody().getSdtArray()) { if (bookmark.getName().equals(name)) { return bookmark; } } return null; } } ``` 在这个示例中,我们首先加载 Word 文档,然后使用 `findBookmarkByName` 方法查找指定名称的书签。如果找到了书签,我们就可以使用其范围信息找到书签所在的段落和文本,并将其替换为指定的文本。最后,我们将修改后的文档保存回原始文件

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值