简体   繁体   English

打开 XML。 如何在 docx 中使用 C# 添加创建者?

[英]OpenXml. How to add creator using C# in docx?

I am trying to add some core properties to the Docx document.我正在尝试向 Docx 文档添加一些核心属性。 I have found only one example in different places of how it can be done.我在不同的地方只发现了一个关于如何完成的例子。

For instance here .例如这里 But there is a problem.但有一个问题。

If we look at the structure of the Docx itself created by Word application and using OpenXml, there is a difference between them.如果我们看一下 Word 应用程序和使用 OpenXml 创建的 Docx 本身的结构,它们之间是有区别的。

Structure of the docx created using openxml and document.PackageProperties.Creator = "vso"使用 openxml 和 document.PackageProperties.Creator = "vso" 创建的 docx 的结构

Moreover, validation of the file can't be succeeded if I want to check the file by productivity tool from Microsoft.此外,如果我想通过 Microsoft 的生产力工具检查文件,则无法成功验证文件。 Of course, the word can read this file, but it is not a proper way to generate a word file from my point of view.当然,word可以读取这个文件,但从我的角度来看,这不是生成word文件的正确方式。

Here you can see the structure of the docx created by the word application itself在这里可以看到word应用程序本身创建的docx的结构

One more aspect, if I write following:另一方面,如果我写以下内容:

CoreFilePropertiesPart corePackageProperties = document.CoreFilePropertiesPart;
if (corePackageProperties == null)
{
   corePackageProperties = document.AddCoreFilePropertiesPart();
}

then core.xml file is created in the proper place of structure, but it is empty.然后在结构的适当位置创建 core.xml 文件,但它是空的。

So, the question is does OpenXML SDK have the way to get the structure of the docx the same as using the word application itself?那么,问题是 OpenXML SDK 有没有办法像使用应用程序本身一样获取 docx 的结构?

Microsoft documentation suggests : 微软文档建议:

using (XmlTextWriter writer = new XmlTextWriter(coreFilePropPart.GetStream(FileMode.Create), System.Text.Encoding.UTF8))
{
  writer.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<cp:coreProperties xmlns:cp=\"https://schemas.openxmlformats.org/package/2006/metadata/core-properties\"></cp:coreProperties>");
  writer.Flush();
}

I had the same issue when creating an Excel file and this sort it out.我在创建 Excel 文件时遇到了同样的问题,并对此进行了整理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM