繁体   English   中英

打开XML SDK 2.0

[英]Open XML SDK 2.0

我试图按照教程制作一个Word文档模板,可以使用C#对其进行操作。 但是我总是收到以下错误:“名称'mainPart'在当前上下文打开的XML中不存在”。 我正在使用Open Xml 2.0。

我想念什么吗?

        using System;
        using System.IO;
        using DocumentFormat.OpenXml.Packaging;

        ....

        Console.WriteLine("Starting up Word template updater ...");

        //get path to template and instance output
        string docTemplatePath = @"C:\Users\user\Desktop\Doc Offices XML\earth.docx";
        string docOutputPath = @"C:\Users\user\Desktop\Doc Offices XML\earth_Instance.docx";

        //create copy of template so that we don't overwrite it
        File.Copy(docTemplatePath, docOutputPath);

        Console.WriteLine("Created copy of template ...");

        //stand up object that reads the Word doc package
        using (WordprocessingDocument doc = WordprocessingDocument.Open(docOutputPath, true))
        {
            //create XML string matching custom XML part
            string newXml = "<root>" +
                "<Earth>Outer Space</Earth>" +
                "</root>";

            MainDocumentPart main = doc.MainDocumentPart;
            main.DeleteParts<CustomXmlPart>(main.CustomXmlParts);

            //add and write new XML part
            //CustomXmlPart customXml = main.AddNewPart<CustomXmlPart>();
            CustomXmlPart customXml = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
            using (StreamWriter ts = new StreamWriter(customXml.GetStream()))
            {

                ts.Write(newXml);
            }

            //closing WordprocessingDocument automatically saves the document
        }

        Console.WriteLine("Done");
        Console.ReadLine();

您需要先创建每个零件,然后才能首次访问它。 尝试这个:

  doc.AddMainDocumentPart()

暂无
暂无

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

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