Update toc in Open xml
-
Friday, June 01, 2012 8:50 AM
Hi,
i want to update Table of contents in my docx file usaing open xml.
can any one help me.
All Replies
-
Monday, June 04, 2012 2:11 AMModerator
Hi nikitha.P,
Thanks for posting in the MSDN Forum.
This is a simple sample for your goal, you are able to extend it by yourself. Please omit the comment, it just the track of my work.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; //using log4net; //using MyLog4Net; using System.Windows.Forms; using System.IO; namespace ConsoleApplication23 { class Program { //private static ILog log = MyLog4Net.MyLog4Net // .Generator1(AppDomain.CurrentDomain.BaseDirectory + "Logger.log", // typeof(Program), "DEBUG", true); [STAThread] static void Main(string[] args) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = false; ofd.Filter = "Word Document|*.docx"; ofd.ShowDialog(); string original = ofd.FileName; //log.Info("Original Document : " + original); string basepath = AppDomain.CurrentDomain.BaseDirectory; string target = basepath + "Test.docx"; //log.Info("Target Document : " + target); File.Copy(original, target, true); //log.Info("File Copied"); using (WordprocessingDocument wpd = WordprocessingDocument .Open(target, true)) { //log.Info("Document has been opened"); MainDocumentPart mdp = wpd.MainDocumentPart; //log.Info("Get Main Document part."); Document d = mdp.Document; Table table = d.Descendants<Table>().FirstOrDefault(); //log.Info("Get first table"); TableRow tr = table.Descendants<TableRow>().ToList()[1]; //log.Info("Get Second row of the table"); TableCell td = tr.Descendants<TableCell>().ToList()[2]; //log.Info("Get Third column of the table row"); Paragraph tc = td.Descendants<Paragraph>().FirstOrDefault(); if (tc == null) { tc = new Paragraph(); td.Append(tc); //log.Info("Append Paragraph"); } else { //log.Info("Get the content of the table cell"); Run r = new Run(); Text text = new Text(); text.Text = "I will append some content in here!"; r.Append(text); tc.Append(r); //log.Info("Update table information"); } d.Save(); //log.Info("Document has been saved"); } Console.ReadKey(); } } }Before update:
After update:
I hope it can help you.
Have a good day,
Tom
Tom Xu [MSFT]
MSDN Community Support | Feedback to us
- Marked As Answer by Tom_Xu_WXModerator Tuesday, June 26, 2012 7:26 AM

