V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
coderstory
V2EX  ›  Java

请教大佬 , POI 5.x 如何读取 docx 文件中文本框的内容并修改?

  •  
  •   coderstory ·
    coderstory · 2022-07-03 18:18:58 +08:00 · 1339 次点击
    这是一个创建于 654 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题: 需要实现一个替换 docx 内文本的功能,但是目前 docx 中文本框的内容读取不到

    开发环境

    1. springboot 2.x
    2. poi 5.2.2 poi-ooxml 5.2.2

    实现代码

    
        public void changeText(XWPFDocument document, Map<String, String> textMap) {
            // 替换页眉
            for (XWPFHeader xwpfHeader : document.getHeaderList()) {
                for (XWPFParagraph paragraph : xwpfHeader.getParagraphs()) {
                    replaceParagraph(paragraph, textMap);
                }
            }
            // 替换页脚
            for (XWPFFooter xwpfFooter : document.getFooterList()) {
                for (XWPFParagraph paragraph : xwpfFooter.getParagraphs()) {
                    replaceParagraph(paragraph, textMap);
                }
            }
    
            document.getBodyElements();
    
            // 替换段落内的文本信息
            List<XWPFParagraph> documentParagraphs = document.getParagraphs();
            for (XWPFParagraph xwpfParagraph : documentParagraphs) {
                replaceParagraph(xwpfParagraph, textMap);
            }
            .....(省略)
    

    其中 document.getParagraphs() 应该能读取 word 中所有段落的数据,但是很遗憾没有找到任何文本框中的段落或文本。我也没找到相关单独读取文本框对象的方法。

    idea 断点调试把 XWPFDocument 对象中的数据翻了一个边也只找到普通的不在文本框里的文本。

    现在有点懵,不知道怎么处理了。

    2 条回复    2022-07-03 20:29:59 +08:00
    coderstory
        1
    coderstory  
    OP
       2022-07-03 18:49:14 +08:00
    好像普通的付费无法读取 文本框的内容

    ```java
    CTBody ctbody = document.getDocument().getBody();
    XmlCursor xmlcursor = ctbody.newCursor();
    ```

    好像只能使用光标 一段一段读取 原始数据的方式 米有现成封装好的代码
    拿到 txbxContent 对象后又不清楚怎么处理了
    orangie
        2
    orangie  
       2022-07-03 20:29:59 +08:00
    好像 stackOverflow 上一搜就有,/questions/46802369/replace-text-in-text-box-of-docx-by-using-apache-poi
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5308 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 07:39 · PVG 15:39 · LAX 00:39 · JFK 03:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.