[英]Open XML SDK 2.0
I'm trying to follow this tutorial to made a Word doc template that i can manipulate using C#. 我试图按照本教程制作一个Word文档模板,可以使用C#对其进行操作。 But i always get the following error: "The name 'mainPart' does not exist in the current context open XML".
但是我总是收到以下错误:“名称'mainPart'在当前上下文打开的XML中不存在”。 I'm using Open Xml 2.0.
我正在使用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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.