Darkleo’s Blog
Ein Schatz, der seinen Besitzer überallhin begleitet.

Word 2007 (.docx) - Dokumente in C# bearbeiten

January 28th, 2008 by darkleo

Ich habe verucht das Inhalt von .docx Dokumenten zu ändern, dabei war die Idee: docx ist nichts anderes als ZIP und man könnte ja das File entzippen und die document.xml ändern. Naja ist suboptimal, denn es gibt von Micosoft das "Microsoft SDK for Open XML Formats"

http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&displaylang=en

Ein kleines Beispiel:
Word-Dokument mit folgendem Inhalt (FULL.docx):

{FULL_NAME}
Tel: {PHONE}

 
static void Main(string[] args)
{
  Console.WriteLine("Start Processing...");
  SearchAndReplace(@"FULL.docx", @"FULL_OUT.docx");
  Console.ReadKey();
}
 
 
//Search and replace content in a part
public static void SearchAndReplace(string path, string path_out)
{
 using (WordprocessingDocument wordDoc =
          WordprocessingDocument.Open(path, true))
 {
  string docText = null;
 using (StreamReader sr =
          new StreamReader(wordDoc.MainDocumentPart.GetStream()))
 {
    docText = sr.ReadToEnd();
  }
 docText = docText.Replace("{FULL_NAME}", "Darkleo.COM/BLOG!");
 docText = docText.Replace("{PHONE}", "101010101011");
 CreateNewWordDocument(path_out, docText);
 }
}  
 
//Create a new package as a Word document.
public static void CreateNewWordDocument(string path,string xml_content)
{
 using (WordprocessingDocument wordDoc =
          WordprocessingDocument.Create(
          path,
          WordprocessingDocumentType.Document))
 {
 // Set the content of the document so that Word can open it.
 MainDocumentPart part = wordDoc.AddMainDocumentPart();
  using (Stream stream = part.GetStream())
  {
    byte[] buf = (new UTF8Encoding()).GetBytes(xml_content);
    stream.Write(buf, 0, buf.Length);
   }
 }
}

Weiter Infos: http://msdn2.microsoft.com/en-us/library/bb491088.aspx
Open XML Package Explorer: http://www.codeplex.com/PackageExplorer
Download: docx_test.zip

Posted in .NET, C#, Office

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.