2012-02-24 14 views
0

thisチュートリアルに沿って、C#を使って操作できるWordのドキュメントテンプレートを作成しようとしています。しかし、私はいつも次のエラーを受け取ります: "名前 'mainPart'は現在のコンテキストオープン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(); 

答えて

2

初めてアクセスする前に、各部品を作成する必要があります。 これを試してみてください:

doc.AddMainDocumentPart() 
+0

これは実質的に問題を解決します。私は何を入れましたか: "MainDocumentPart mainPart = doc.AddMainDocumentPart();"感謝万円。 :) –

関連する問題