0
我正在尝试关注this教程以创建一个Word文档模板,我可以使用C#进行操作。但我总是得到以下错误:“名称'mainPart'在当前上下文中不存在open XML”。我正在使用Open Xml 2.0。Open XML SDK 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();
叶氏,,实际上解决了这个问题。我放的是:“MainDocumentPart mainPart = doc.AddMainDocumentPart();”太感谢了。 :) – 2012-02-24 16:23:24