【问题标题】:pass values from java variables to microsoft word (doc and docx) variables将值从 java 变量传递到 microsoft word(doc 和 docx)变量
【发布时间】:2026-01-28 02:45:01
【问题描述】:

如何将 microsoft word 文档变量值替换为 java 变量中的值?我有一个 .doc 或 .docx 文件模板,我在其中定义了一些变量。

当用户从我的应用程序中单击下载按钮时,.doc 或 .docx 变量必须从 java 变量中获取值。

【问题讨论】:

标签: java ms-word docx doc


【解决方案1】:

我为此使用 docx4j:

        String inputfilepath = "binding-simple1.docx";
        String outputfilepath = "OUT_VariableReplace.docx";

        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
                .load(new java.io.File(inputfilepath));
        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

        HashMap<String, String> mappings = new HashMap<String, String>();
        mappings.put("subjectId", "E000001");

        // Approach 1 (from 3.0.0; faster if you haven't yet caused unmarshalling to occur):

        documentPart.variableReplace(mappings);
        Docx4J.save(wordMLPackage, new File(outputfilepath));

变量参数如下:${subjectId}

【讨论】:

    【解决方案2】:

    我负责一出戏!使用具有 .docx 扩展名的模板生成 word 文档的 Intranet。为此,我们有以下继承树:Document > Word > [someDocument]

    抽象类 Word 处理替换 Word 文档中的变量

    public abstract class Word extends Document {
        public static JAXBContext context = org.docx4j.jaxb.Context.jc;
    
        public Word(String inputfilepath){
            super(inputfilepath);
        }
    
        public String generer(String outputfilepath) throws Exception {
    
            //String inputfilepath = System.getProperty("user.dir")+"/app/doc/adhesionTemplate.docx";
    
            //String outputfilepath = System.getProperty("user.dir")+ "/test-out.docx";
    
            // Open a document from the file system
            // 1. Load the Package
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
    
            // 2. Fetch the document part
            MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
    
            org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart.getJaxbElement();
    
            // xml --> string
            String xml = XmlUtils.marshaltoString(wmlDocumentEl, true);
    
            //Change the variables using an abstract function getMapping()
            HashMap<String, String> mappings = getMapping();
    
            Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);
    
            // change JaxbElement
            documentPart.setJaxbElement((org.docx4j.wml.Document) obj);
    
            //Footers : 
            List<SectionWrapper> wrappers = wordMLPackage.getDocumentModel().getSections();
            for (SectionWrapper sw : wrappers) {
                FooterPart footer = sw.getHeaderFooterPolicy().getDefaultFooter();
                if (footer != null) {
                    Ftr footerDoc = footer.getJaxbElement();
                    String footerXml = XmlUtils.marshaltoString(footerDoc, true);
                    Object footerObj = XmlUtils.unmarshallFromTemplate(footerXml, mappings);
                    footer.setJaxbElement( (Ftr) footerObj);
                }
            }
    
            // Save it
            SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
            saver.save(outputfilepath);
            Console.commande("sudo chmod 660 \"" + outputfilepath + "\"");
    
            System.out.println("Saved output to:" + outputfilepath);
    
            return outputfilepath;
    
        }
    

    然后,我们有继承自这个 Word 抽象类的类:

    public class FAC extends Word {
    
        public FAC() {
            super(System.getProperty("user.dir") + "/templates/Facture.docx");
        }
    
        @Override
        public HashMap<String, String> getMapping() {
    
            //Preparing variables
            int price = blablabla;
    
            HashMap<String, String> map = new HashMap<String, String>();
    
            map.put("FACDate", Utils.dateConvert(new Date()));
            map.put("somePrice", String.valueOf(price));
    
    
            return map;
        }
    }
    

    注意:“Document”超类没有什么特别之处,只是一个变量“inputFilePath”和抽象方法getMapping()

    希望对您或像我这样的未来观众有所帮助:P

    【讨论】: