coderstory
V2EX  ›  Java

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

  •  
  •   coderstory ·
    coderstory · Jul 3, 2022 · 2391 views
    This topic created in 1453 days ago, the information mentioned may be changed or developed.

    问题: 需要实现一个替换 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 replies    2022-07-03 20:29:59 +08:00
    coderstory
        1
    coderstory  
    OP
       Jul 3, 2022
    好像普通的付费无法读取 文本框的内容

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

    好像只能使用光标 一段一段读取 原始数据的方式 米有现成封装好的代码
    拿到 txbxContent 对象后又不清楚怎么处理了
    orangie
        2
    orangie  
       Jul 3, 2022
    好像 stackOverflow 上一搜就有,/questions/46802369/replace-text-in-text-box-of-docx-by-using-apache-poi
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3570 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 04:40 · PVG 12:40 · LAX 21:40 · JFK 00:40
    ♥ Do have faith in what you're doing.