Imorting Table styles in word document using OpenXML Sdk


/ Published in: C#
Save to your folder(s)

After importing tables from source document to target document, use this snippet to import table styles missing in the target document to enable correct formatting of the table.


Copy this code and paste it in your HTML
  1. internal static XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
  2.  
  3. internal static void ImportTableStyles(string sourcefilepath, string destinationfilepath)
  4. {
  5. using (var repeaterSourceDocument = WordprocessingDocument.Open(sourcefilepath, true))
  6. {
  7. XDocument source_style_doc;
  8.  
  9. var repeaterSourceDocumentPackagePart = repeaterSourceDocument.MainDocumentPart.OpenXmlPackage.Package.GetPart(new Uri("/word/styles.xml", UriKind.Relative));
  10.  
  11. //Get styles.xml
  12. using (TextReader tr = new StreamReader(repeaterSourceDocumentPackagePart.GetStream()))
  13. source_style_doc = XDocument.Load(tr);
  14.  
  15. var tableStylesFromRepeaterSource = source_style_doc.Descendants(w + "style").Where(x => x.Attribute(w + "type").Value == "table").Select(x => x).ToList();
  16.  
  17. using (var targetFileToImportTableStyles = WordprocessingDocument.Open(destinationfilepath, true))
  18. {
  19. XDocument dest_style_doc;
  20.  
  21. var destpart = targetFileToImportTableStyles.MainDocumentPart.OpenXmlPackage.Package.GetPart(new Uri("/word/styles.xml", UriKind.Relative));
  22.  
  23. //Get styles.xml
  24. using (TextReader trd = new StreamReader(destpart.GetStream()))
  25. dest_style_doc = XDocument.Load(trd);
  26.  
  27. //Add all the style elements from source document styles.xml
  28. foreach (var styleelement in tableStylesFromRepeaterSource)
  29. {
  30. if (!dest_style_doc.Elements(XName.Get("styles", w.NamespaceName)).Any(x => (string)x.Attribute("styleId") == (string)styleelement.Attribute("styleId")))
  31. {
  32. dest_style_doc.Element(XName.Get("styles", w.NamespaceName)).Add(styleelement);
  33. }
  34. }
  35.  
  36. //Save the style.xml of targetFile
  37. using (TextWriter tw = new StreamWriter(destpart.GetStream(FileMode.Create)))
  38. dest_style_doc.Save(tw, SaveOptions.None);
  39.  
  40. }
  41. }
  42. }

URL: http://www.adigopula.co.uk/post/Importing-Table-Styles-in-Word-Document-using-OpenXML-sdk.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.