在 C# 中从 OpenXML 生成 word 文档时更改默认文档布局

Change default document layout when generating word document from OpenXML in C#

我已经能够使用与 this SO question 中使用的格式类似的格式生成一个简单的 word 文档,但是每当我打开该文档时,它都会在打印布局视图中打开。有没有一种方法可以通过编程方式使其默认在 Web 布局视图中打开?

是的,您可以使用 OpenXML.WordProcessing.View. You need to create a View with its Val set to ViewValues.Web. Then you need to create a Settings object and append the view to it. Finally, you need to create a DocumentSettingsPart 并将其 Settings 属性 设置为您创建的 settings 对象。

这听起来比实际情况更糟,下面是一个完整的方法,它采用 question you mention 中的代码加上上面的代码。我已经从那个答案中删除了内存流代码以简化事情;此代码将在磁盘上创建一个文件。

public static void CreateWordDoc(string filename)
{
    using (var wordDocument = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document))
    {
        // Add a main document part. 
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

        // Create the document structure and add some text.
        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());
        run.AppendChild(new Text("Hello world!"));

        //the following sets the default view when loading in Word
        DocumentSettingsPart documentSettingsPart = mainPart.AddNewPart<DocumentSettingsPart>();
        Settings settings = new Settings();
        View view1 = new View() { Val = ViewValues.Web };
        settings.Append(view1);
        documentSettingsPart.Settings = settings;

        mainPart.Document.Save();
    }
}