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