[英]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.