简体   繁体   中英

Open XML SDK 2.0

I'm trying to follow this tutorial to made a Word doc template that i can manipulate using C#. But i always get the following error: "The name 'mainPart' does not exist in the current context open XML". I'm using Open Xml 2.0.

Any idea of what am i missing?

        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();

You need to create each part before you access it the first time. Try this:

  doc.AddMainDocumentPart()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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