无法使用 Open XML SDK 创建文档

Cannot create documents with Open XML SDK

我正在学习将 Open XML SDK 与 Visual Studio Community 2015 一起使用。我尝试按照此处的示例创建文档:https://msdn.microsoft.com/en-us/library/dd440953(v=office.12).aspx

我的代码:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
          Program p = new Program();
          p.HelloWorld("abc.docx");
        }

        public void HelloWorld(string docName)
        {
            // Create a Wordprocessing document. 
            using (WordprocessingDocument package = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
            {
                // Add a new main document part. 
                package.AddMainDocumentPart();

                // Create the Document DOM. 
                package.MainDocumentPart.Document =
                  new Document(
                    new Body(
                      new Paragraph(
                        new Run(
                          new Text("Hello World!")))));

                // Save changes to the main document part. 
                package.MainDocumentPart.Document.Save();
            }
        }

    }
}

我在 WordprocessingDocument.Create 上遇到错误:

Error   CS0012  The type 'Package' is defined in an assembly that is not referenced. 
You must add a reference to assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=1234'.  
ConsoleApplication1 c:\users\john\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs

我已经用 nuget

安装了 DocumentFormat.OpenXml

代码有什么问题?

错误消息已经告诉您如何解决您的问题:

You must add a reference to assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=1234'.

在 Visual Studio 的 Solution Explorer 中右键单击项目的 References 节点并选择 添加引用。然后,在 Assemblies -> Framework 下,您必须 select WindowsBase 并且作为参考。然后重新编译您的项目(请注意,这需要您使用 .NET Framework 3.5 或任何更高版本)。