{"id":5227,"date":"2022-04-24T23:02:19","date_gmt":"2022-04-24T15:02:19","guid":{"rendered":"https:\/\/ixyzero.com\/blog\/?p=5227"},"modified":"2022-04-25T00:21:12","modified_gmt":"2022-04-24T16:21:12","slug":"%e7%94%a8-docx4j-%e5%af%b9%e6%96%87%e6%a1%a3%e6%b7%bb%e5%8a%a0-%e5%88%a0%e9%99%a4%e8%87%aa%e5%ae%9a%e4%b9%89%e5%b1%9e%e6%80%a7","status":"publish","type":"post","link":"https:\/\/ixyzero.com\/blog\/archives\/5227.html","title":{"rendered":"\u7528 docx4j \u5bf9\u6587\u6863\u6dfb\u52a0\/\u5220\u9664\u81ea\u5b9a\u4e49\u5c5e\u6027"},"content":{"rendered":"\n<p>=Start=<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u7f18\u7531\uff1a<\/h4>\n\n\n\n<p>\u7b80\u5355\u8bb0\u5f55\u4e00\u4e0b\u7528 docx4j \u5bf9Office\u6587\u6863\uff08docx\/xlsx\/pptx\uff09\u6dfb\u52a0\u5220\u9664\u81ea\u5b9a\u4e49\u5c5e\u6027\u7684\u65b9\u6cd5\uff0c\u65b9\u4fbf\u6709\u9700\u8981\u7684\u53c2\u8003\u3002<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u6b63\u6587\uff1a<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">\u53c2\u8003\u89e3\u7b54\uff1a<\/h5>\n\n\n\n<p>Maven\u7684\u76f8\u5173\u4f9d\u8d56<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!-- https:\/\/mvnrepository.com\/artifact\/org.docx4j\/docx4j-JAXB-Internal -->\n&lt;!-- use the JAXB shipped in Java 8 -->\n&lt;dependency>\n    &lt;groupId>org.docx4j&lt;\/groupId>\n    &lt;artifactId>docx4j-JAXB-Internal&lt;\/artifactId>\n    &lt;version>8.3.4&lt;\/version>\n&lt;\/dependency>\n\n&lt;!-- use the JAXB Reference Implementation -->\n&lt;dependency>\n    &lt;groupId>org.docx4j&lt;\/groupId>\n    &lt;artifactId>docx4j-JAXB-ReferenceImpl&lt;\/artifactId>\n    &lt;version>8.3.4&lt;\/version>\n&lt;\/dependency>\n\n&lt;!-- use the MOXy JAXB implementation -->\n&lt;dependency>\n    &lt;groupId>org.docx4j&lt;\/groupId>\n    &lt;artifactId>docx4j-JAXB-MOXy&lt;\/artifactId>\n    &lt;version>8.3.4&lt;\/version>\n&lt;\/dependency>\n\n&lt;!-- https:\/\/mvnrepository.com\/artifact\/commons-io\/commons-io -->\n&lt;dependency>\n    &lt;groupId>commons-io&lt;\/groupId>\n    &lt;artifactId>commons-io&lt;\/artifactId>\n    &lt;version>2.11.0&lt;\/version>\n&lt;\/dependency><\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p>\u6d4b\u8bd5\u9a8c\u8bc1\u4ee3\u7801<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example;\n\nimport org.docx4j.XmlUtils;\nimport org.docx4j.docProps.custom.Properties;\nimport org.docx4j.jaxb.Context;\nimport org.docx4j.openpackaging.exceptions.Docx4JException;\nimport org.docx4j.openpackaging.exceptions.InvalidFormatException;\nimport org.docx4j.openpackaging.packages.WordprocessingMLPackage;\nimport org.docx4j.openpackaging.parts.DocPropsCustomPart;\nimport org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;\n\nimport java.io.File;\nimport java.util.List;\n\n\/**\n * @author ixyzero\n * Created on 2022-04-18\n *\/\npublic class docx4jCodeExample {\n    public static void main(String&#91;] args) {\n        String filePath = \"welcome.docx\";\n        String content = \"welcome to docx4j!\";\n        docxCreate(filePath, content);\n        docxReadProps(filePath);\n\n        docxAddProps(filePath);\n        docxReadProps(filePath);\n\n        docxDeleteProp(filePath, \"1\");\n        docxReadProps(filePath);\n\n        docxDeleteProp(filePath, \"1st custom property\");\n        docxReadProps(filePath);\n\n        docxDeleteProp(filePath, \"all_key\");\n        docxReadProps(filePath);\n    }\n\n    public static int docxCreate(String filePath, String contentString) {\n        WordprocessingMLPackage wordMLPackage = null;\n        try {\n            wordMLPackage = WordprocessingMLPackage.createPackage();\n        } catch (InvalidFormatException e) {\n            e.printStackTrace();\n            return 1;\n        }\n        MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();\n        mainDocumentPart.addStyledParagraphOfText(\"Title\", \"Hello World!\");\n        mainDocumentPart.addParagraphOfText(contentString);\n\n        File exportFile = new File(filePath);\n        try {\n            wordMLPackage.save(exportFile);\n        } catch (Docx4JException e) {\n            e.printStackTrace();\n            return 1;\n        }\n\n        return 0;\n    }\n\n    public static int docxReadProps(String filePath) {\n        WordprocessingMLPackage wordMLPackage = null;\n        try {\n            wordMLPackage = WordprocessingMLPackage.load(new File(filePath));\n        } catch (Docx4JException e) {\n            e.printStackTrace();\n            return 1;\n        }\n\n        \/\/ 1. \u67e5\u770b\u6838\u5fc3\u5c5e\u6027-getDocPropsCorePart core properties\n        org.docx4j.openpackaging.parts.DocPropsCorePart docPropsCorePart = wordMLPackage.getDocPropsCorePart();\n        org.docx4j.docProps.core.CoreProperties coreProps = (org.docx4j.docProps.core.CoreProperties) docPropsCorePart.getJaxbElement();\n        \/\/ Title of the document\n        \/\/ Note: Word for Mac 2010 doesn't set title\n        String title = \"Missing\";\n        if (coreProps.getTitle() != null) {\n            List&lt;String> list = coreProps.getTitle().getValue().getContent();\n            if (list.size() > 0) {\n                title = list.get(0);\n            }\n        }\n        System.out.println(\"'dc:title' is \" + title);\n\n        \/\/ 2. \u67e5\u770b\u6269\u5c55\u5c5e\u6027-getDocPropsExtendedPart extended properties\n        org.docx4j.openpackaging.parts.DocPropsExtendedPart docPropsExtendedPart = wordMLPackage.getDocPropsExtendedPart();\n        org.docx4j.docProps.extended.Properties extendedProps = (org.docx4j.docProps.extended.Properties) docPropsExtendedPart.getJaxbElement();\n        \/\/ Document creator Application\n        System.out.println(\"'Application' is \" + extendedProps.getApplication() + \" v.\" + extendedProps.getAppVersion());\n\n        \/\/ 3. \u67e5\u770b\u81ea\u5b9a\u4e49\u5c5e\u6027-getDocPropsCustomPart custom properties\n        org.docx4j.openpackaging.parts.DocPropsCustomPart docPropsCustomPart = wordMLPackage.getDocPropsCustomPart();\n        if (docPropsCustomPart == null) {\n            System.out.println(\"&#91;read]No Document Custom Properties. getDocPropsCustomPart returns null\");\n        } else {\n            \/\/ traverse custom properties and print\n            org.docx4j.docProps.custom.Properties customProps = (org.docx4j.docProps.custom.Properties) docPropsCustomPart.getJaxbElement();\n            System.out.println(String.format(\"&#91;read]size of Custom Properties = %d\",customProps.getProperty().size()));\n            for (org.docx4j.docProps.custom.Properties.Property prop : customProps.getProperty()) {\n                \/\/ Could create a generic Object getValue() method.\n                if (prop.getLpwstr() != null) {\n                    System.out.println(prop.getName() + \" = \" + prop.getLpwstr());\n                } else {\n                    System.out.println(prop.getName() + \": \\n \" + XmlUtils.marshaltoString(prop, true, Context.jcDocPropsCustom));\n                }\n            }\n            \/\/ System.out.println(customProps.getProperty()); \/\/ &#91;org.docx4j.docProps.custom.Properties$Property@2da3b078, ...]\n        }\n        System.out.println();\n        return 0;\n    }\n\n    \/\/ \u6d4b\u8bd5\u8d77\u89c1\uff0c\u6ca1\u6709\u628a\u65b0\u589e\u5c5e\u6027key\/value\u914d\u7f6e\u6210\u53c2\u6570\u53d8\u6210\u52a8\u6001\u53ef\u8c03\u7684\uff0c\u4e0d\u8fc7\u4fee\u6539\u8d77\u6765\u5f88\u7b80\u5355\n    public static int docxAddProps(String filePath) {\n        WordprocessingMLPackage wordMLPackage = null;\n        try {\n            wordMLPackage = WordprocessingMLPackage.load(new File(filePath));\n        } catch (Docx4JException e) {\n            e.printStackTrace();\n            return 1;\n        }\n\n        \/\/ \u81ea\u5b9a\u4e49\u5c5e\u6027\u53ef\u80fd\u4e3a\u7a7a\n        org.docx4j.openpackaging.parts.DocPropsCustomPart docPropsCustomPart = wordMLPackage.getDocPropsCustomPart();\n        if (docPropsCustomPart == null) {\n            System.out.println(\"&#91;add]No Document Custom Properties. let's add some.\");\n            \/\/ \u65b9\u6cd5\u4e00\uff08\u8f83\u4e3a\u7e41\u7410\uff09\n            \/\/ 1. create a DocPropsCustomPart and custom.Properties\n            try {\n                docPropsCustomPart = new DocPropsCustomPart();\n                wordMLPackage.addTargetPart(docPropsCustomPart);\n            } catch (InvalidFormatException e) {\n                e.printStackTrace();\n                return 1;\n            }\n            org.docx4j.docProps.custom.ObjectFactory objFactory = new org.docx4j.docProps.custom.ObjectFactory();\n            org.docx4j.docProps.custom.Properties customProps = objFactory.createProperties();\n            docPropsCustomPart.setJaxbElement(customProps);\n\n            \/\/ 2. create a custom property.\n            org.docx4j.docProps.custom.Properties.Property newProp = objFactory.createPropertiesProperty();\n            newProp.setName(\"1st custom property\");\n            newProp.setFmtid(docPropsCustomPart.fmtidValLpwstr ); \/\/ Magic string\n            newProp.setPid( customProps.getNextId() );\n            newProp.setLpwstr(\"value_here\");\n\n            \/\/ 3. add it\n            customProps.getProperty().add(newProp);\n\n            \/\/ \u65b9\u6cd5\u4e8c\uff08\u7b80\u4fbf\u5feb\u6377\uff09\n            \/\/ step all in one\n            wordMLPackage.addDocPropsCustomPart();\n            docPropsCustomPart = wordMLPackage.getDocPropsCustomPart();\n            docPropsCustomPart.setProperty(\"key1\", \"value1\");\n        } else {\n            org.docx4j.docProps.custom.Properties customProps = (org.docx4j.docProps.custom.Properties) docPropsCustomPart.getJaxbElement();\n\n            \/\/ 1. createPropertiesProperty, create a custom property.\n            org.docx4j.docProps.custom.ObjectFactory objFactory = new org.docx4j.docProps.custom.ObjectFactory();\n            org.docx4j.docProps.custom.Properties.Property newProp = objFactory.createPropertiesProperty();\n            newProp.setName(\"last custom prop by add\");\n            newProp.setFmtid(docPropsCustomPart.fmtidValLpwstr ); \/\/ Magic string\n            newProp.setPid( customProps.getNextId() );\n            newProp.setLpwstr(\"value_here2\");\n            \/\/ 2. add it\n            customProps.getProperty().add(newProp);\n        }\n        \n        \/\/ save changes\n        try {\n            wordMLPackage.save(new File(filePath));\n        } catch (Docx4JException e) {\n            e.printStackTrace();\n            return 1;\n        }\n\n        return 0;\n    }\n\n    private static boolean isNumeric(String str){\n        return str != null &amp;&amp; str.matches(\"&#91;0-9.]+\");\n    }\n    private static boolean isDigit(String str){\n        return str != null &amp;&amp; str.matches(\"&#91;0-9]+\");\n    }\n\n    public static int docxDeleteProp(String filePath, String filterStr) {\n        WordprocessingMLPackage wordMLPackage = null;\n        try {\n            wordMLPackage = WordprocessingMLPackage.load(new File(filePath));\n        } catch (Docx4JException e) {\n            e.printStackTrace();\n            return 1;\n        }\n\n        \/\/ \u81ea\u5b9a\u4e49\u5c5e\u6027\u53ef\u80fd\u4e3a\u7a7a\n        org.docx4j.openpackaging.parts.DocPropsCustomPart docPropsCustomPart = wordMLPackage.getDocPropsCustomPart();\n        if (docPropsCustomPart == null) {\n            System.out.println(\"&#91;delete]No Document Custom Properties. Do nothing.\");\n            return 0;\n        }\n\n        org.docx4j.docProps.custom.Properties customProps = (org.docx4j.docProps.custom.Properties) docPropsCustomPart.getJaxbElement();\n        List&lt;Properties.Property> customPropList = customProps.getProperty();\n        if (filterStr.equalsIgnoreCase(\"all_key\")) {\n            \/\/ delete all\n            System.out.println(\"&#91;delete]try to delete all Custom Properties.\");\n            customProps.getProperty().clear();\n        } else if (isDigit(filterStr)) {\n            \/\/ delete by index\n            System.out.println(\"&#91;delete]try to delete Custom Properties by index(start from 0).\");\n            int index = Integer.parseInt(filterStr);\n            if (index >= customPropList.size()) {\n                index = customPropList.size()-1;\n            }\n            customProps.getProperty().remove(index);\n        } else {\n            \/\/ delete by name\n            org.docx4j.docProps.custom.Properties.Property tmpProp = new Properties.Property();\n            for (org.docx4j.docProps.custom.Properties.Property prop : customProps.getProperty()) {\n                if (prop.getName().equalsIgnoreCase(filterStr.toLowerCase())) {\n                    System.out.println(\"&#91;delete]try to delete by Custom Property's key->\" + prop.getName());\n                    tmpProp = prop;\n                    \/\/ customProps.getProperty().remove(prop); \/\/ java.util.ConcurrentModificationException (modCount != expectedModCount)\n                }\n            }\n            customProps.getProperty().remove(tmpProp);\n        }\n\n        \/\/ \u5fc5\u987b\u8981\u4fdd\u5b58\uff0c\u5426\u5219\u66f4\u6539\u4e0d\u4f1a\u751f\u6548\n        \/\/ save changes before exit\n        try {\n            wordMLPackage.save(new File(filePath));\n        } catch (Docx4JException e) {\n            e.printStackTrace();\n            return 1;\n        }\n\n        return 0;\n    }\n}<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\">\u53c2\u8003\u94fe\u63a5\uff1a<\/h5>\n\n\n\n<p>Java Examples for org.docx4j.docProps.custom.Properties.Property #\u8bfb\u53d6docx\u6587\u4ef6\u7684\u81ea\u5b9a\u4e49\u5c5e\u6027\uff0c\u4ee3\u7801\u7b80\u5355\u76f4\u63a5\u53ef\u7528<br><a href=\"https:\/\/www.javatips.net\/api\/org.docx4j.docprops.custom.properties.property\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.javatips.net\/api\/org.docx4j.docprops.custom.properties.property<\/a><br><a href=\"https:\/\/github.com\/plutext\/docx4j\/blob\/master\/docx4j-samples-docx4j\/src\/main\/java\/org\/docx4j\/samples\/DocProps.java\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/github.com\/plutext\/docx4j\/blob\/master\/docx4j-samples-docx4j\/src\/main\/java\/org\/docx4j\/samples\/DocProps.java<\/a><\/p>\n\n\n\n<p>\u4e0a\u9762\u7684\u94fe\u63a5\u91cc\u9762\u5bf9\u4e8e\u6ca1\u6709\u81ea\u5b9a\u4e49\u5c5e\u6027\u7684docx\u6587\u6863\u8fdb\u884c\u6dfb\u52a0\u81ea\u5b9a\u4e49\u5c5e\u6027\u65f6\u4f1a\u62a5\u9519\uff0c\u53ef\u4ee5\u53c2\u8003\u8fd9\u4e2a\u94fe\u63a5\u6765\u4ece\u5934\u5f00\u59cb\u6dfb\u52a0\u81ea\u5b9a\u4e49\u5c5e\u6027<br><a href=\"https:\/\/www.javatips.net\/api\/docx4j-master\/src\/scratchpad\/org\/docx4j\/model\/fields\/AbstractFormattingSwitchTest.java\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.javatips.net\/api\/docx4j-master\/src\/scratchpad\/org\/docx4j\/model\/fields\/AbstractFormattingSwitchTest.java<\/a><\/p>\n\n\n\n<p>java docx4j \u4f7f\u7528\u6559\u7a0b_docx4j\u6df1\u5165\u5b66\u4e60\u6574\u7406 #\u5bf9docx\u6587\u4ef6\u6709\u4e00\u4e9b\u7b80\u5355\u4ecb\u7ecd\u53ef\u4ee5\u5b66\u4e60\u53c2\u8003<br><a href=\"https:\/\/blog.csdn.net\/weixin_33374585\/article\/details\/114719233\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/blog.csdn.net\/weixin_33374585\/article\/details\/114719233<\/a><\/p>\n\n\n\n<p>Introduction To Docx4J<br><a href=\"https:\/\/www.baeldung.com\/docx4j\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.baeldung.com\/docx4j<\/a><\/p>\n\n\n\n<p>How to remove custom properties in docx4j<br><a href=\"https:\/\/stackoverflow.com\/questions\/13143542\/how-to-remove-custom-properties-in-docx4j\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/stackoverflow.com\/questions\/13143542\/how-to-remove-custom-properties-in-docx4j<\/a><\/p>\n\n\n\n<p>=END=<\/p>\n","protected":false},"excerpt":{"rendered":"<p>=Start= \u7f18\u7531\uff1a \u7b80\u5355\u8bb0\u5f55\u4e00\u4e0b\u7528 docx4j \u5bf9Office\u6587\u6863\uff08docx\/xlsx\/pptx\uff09\u6dfb\u52a0\u5220 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[23,7,12],"tags":[1803,1802,61,1805,1804,963],"class_list":["post-5227","post","type-post","status-publish","format-standard","hentry","category-knowledgebase-2","category-programing","category-tools","tag-docx","tag-docx4j","tag-java","tag-pptx","tag-xlsx","tag-963"],"views":3464,"_links":{"self":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/5227","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/comments?post=5227"}],"version-history":[{"count":1,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/5227\/revisions"}],"predecessor-version":[{"id":5228,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/5227\/revisions\/5228"}],"wp:attachment":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/media?parent=5227"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/categories?post=5227"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/tags?post=5227"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}