刚要做目录的时候,我就想DocX应该提供了这个方面的函数。于是我就在讨论区搜索,看看别人是怎么用的。

我搜索了catalog; catalogue; list; contents;,但是都没有和目录有关的东西,搞得我以为没提供,于是就又各种搜索,什么list之类的,搜着搜着就找到了一篇。

说是需要下载一个patch,但是不造在哪。还有的提供了利用其他的xml布局来帮助生成目录的。这些都不用管了,我用的是在DocX.cs里的源码里直接修改下的好方法。

http://docx.codeplex.com/discussions/528384

抄录如下:

Hello together,

i'm sorry, i didn't like your solution proposals as I use docx to not have a need to include the open sdk. (But it took me to this solution 95% of the way, so thanks!)

I found out DocX can actually do that easily with just a few minor changes to the code.

To accomplish that goal add the following lines to DocX.cs into the class:

/// <summary>
        /// Activate Updating Fields on
Open
        /// </summary>
        public void
UpdateFieldsOnOpen()
        {
            XElement element = new
XElement(XName.Get("updateFields", DocX.w.NamespaceName));
            element.Add(new
XAttribute(XName.Get("val", DocX.w.NamespaceName),
"true"));

settings.Root.AddFirst(element);
        }

Finally you need to
modify the save process slightly because docx reloads the settings part
directly before saving the document.

// Comment out or
remove those lines:
-            using (TextReader tr = new
StreamReader(settingsPart.GetStream()))
-                settings =
XDocument.Load(tr);
// Insert this instead:
+            if (settings == null
)
+            {
+                using (TextReader tr =
new StreamReader(settingsPart.GetStream()))
+                    settings =
XDocument.Load(tr);
+            }

Use these lines to
use the new option:

docx.UpdateFieldsOnOpen();
docx.Save();

As a
result, word will tell you that some fields need updating when you open the
document.

Well
after you bypassed that new preview mode that they put into word to complicate
usage. Which i know everybody at my workplace loves very much.

It
works on my computer :).

I
hope it will help YOU ALL TOO since you are great people that deserve TOCs.

Best regards,

shoff

来自 <http://docx.codeplex.com/discussions/528384>

如上所述,就是在DocX.cs的源代码里改一下,在代码末尾添加

1 /// <summary>

2                 /// Activate Updating Fields on Open

3                 /// </summary>

4                 public void UpdateFieldsOnOpen()

5                 {

6                         XElement
element = new XElement(XName.Get("updateFields", DocX.w.NamespaceName));

7                         element.Add(new
XAttribute(XName.Get("val", DocX.w.NamespaceName), "true"));

8

9                         settings.Root.AddFirst(element);

10                 }

然后再修改下保存的函数save(),

1

2                         //using (TextReader tr = new
StreamReader(settingsPart.GetStream()))

3                         // settings = XDocument.Load(tr);

4                         if (settings == null)

5                         {

6                                       using (TextReader tr = new StreamReader(settingsPart.GetStream()))

7                                       settings
= XDocument.Load(tr);

8                         }

把原本是注释里的代码改成现在的样子。

然后重新生成下DocX.dll。

在使用的时候自己添加个函数

1 public static void update(string docx)

2                 {

3                         using (DocX document =
DocX.Load(docx))

4                         {

5                                 document.UpdateFieldsOnOpen();

6                                 document.Save();

7                         }

8

9                 }

让文档在打开的时候自动更新目录域。

不过这样的话你得首先有目录,我用的办法是新建一个word,给它加上目录,然后创建新word的时候把这个的目录页给插入到新文档里。

1 public static void loadTOC(string s, string path, string name)

2                 {

3                         if (!Directory.Exists(path))

4                         {

5                                 Directory.CreateDirectory(path);

6                         }

7                         string docx = @path + "\\" + name;

8                         DocX
_template = DocX.Load(s);

9                         DocX
_document = DocX.Create(docx);

10                         _document.InsertDocument(_template);

11                         _document.SaveAs(docx);

12                         addNewpage(docx);

13

14                 }

至此,目录就可以正常使用了。每次打开就会提示更新域。

如上,结果今天一大早去翻看Example的时候,发现原来作者已经更新了,并且添加了操作目录的代码。使用起来也很简单。

1 public static void AddToc(string docx)

2                 {

3

4                         using (var document =
DocX.Load(docx))

5                         {

6                                 document.InsertTableOfContents("目录", TableOfContentsSwitches.O | TableOfContentsSwitches.U |
TableOfContentsSwitches.Z | TableOfContentsSwitches.H, "Heading2");

7                                 document.Save();

9                         }

10                 }

这样就已经ok了,也不用修改什么代码了,作用和之前的那个一样。顿时心里一阵草泥马奔腾而过。

提醒:多看example里的项目,有需求先在里面找。

c#使用DocX给word添加目录TOC的更多相关文章

  1. DocX开源WORD操作组件的学习系列二

    DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...

  2. DocX操作word生成报表

    1.DocX简介 1.1 简介 DocX是一个在不需要安装word的情况下对word进行操作的开源轻量级.net组件,是由爱尔兰的一个叫Cathal Coffey的博士生开发出来的.DocX使得操作w ...

  3. C#操作Word生成目录

    OperateWord ow = new OperateWord(); Microsoft.Office.Interop.Word.ApplicationClass ss = ow.WordAppli ...

  4. DocX开源WORD操作组件的学习系列三

    DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...

  5. DocX开源WORD操作组件的学习系列一

    DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...

  6. C#使用Docx操作word文档

    C#使用Docx编写word表格 最近接手了一个小Demo,要求使用Docx,将Xml文件中的数据转换为word文档,组织数据形成表格. 写了已经一周,网络上的知识太零碎,就想自己先统计整理出来,方便 ...

  7. Java 给Word添加印章

    一.概述 本文以Java程序代码展示如何给Word文档添加印章,这里添加的印章为.png格式的图片,添加印章即在Word中的指定位置添加印章图片. 基本思路:加载word文档,获取段落,在段落中插入图 ...

  8. 使用FreePic2Pdf导出书签至Word建立层级目录——快速初始化Word笔记本目录

    使用FreePic2Pdf导出书签至Word建立层级目录 --快速初始化Word笔记本目录 文:安徽师范大学2014级计算机科学与技术 王昊 (Get Contact:441301158@qq.com ...

  9. DocX开源WORD操作组件的学习系列四

    DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...

随机推荐

  1. SQLServer 2008以上误操作数据库恢复方法——日志尾部备份(转)

    问题: 经常看到有人误删数据,或者误操作,特别是update和delete的时候没有加where,然后就喊爹喊娘了.人非圣贤孰能无过,做错可以理解,但不能纵容,这个以后再说,现在先来解决问题. 遇到这 ...

  2. 解决Web部署 svg/woff/woff2字体 404错误(转)

    http://blog.sina.com.cn/s/blog_4997f1b90102vkjn.html 最近项目中用到了fontawesome-webfont.svg等字体.部署项目后,发现没有&l ...

  3. Inno Setup命令行安装卸载参数

    安装命令行参数安装程序接受可选的命令行参数.这些对于系统管理员以及其它程序调用安装程序时有用./SP- 在安装开始时禁用“这将安装... 你想继续吗?”的提示,当然,如果 [Setup] 段的指令 D ...

  4. document.write('<script type=\"text/javascript\"><\/script>')

    document.write('<script type=\"text/javascript\"><\/script>')

  5. LeetCode:237

    题目:Delete Node in a Linked List(从列表中删除指定结点) 描述:Write a function to delete a node (except the tail) i ...

  6. JAVA中求解对象所占字节大小

    该类为cache4j缓存框架中的工具类方法,该方法实现了两个接口 接口1:计算对象在内存中所占字节数 接口2:复制对象,实现深度克隆效果,实现原理为先序列化对象,然后在反序列化对象:返回一个新的对象, ...

  7. UDKtoUE4Tool-UDKUE3资源移植UE4工具

    UDKtoUE4Tool UDKtoUE4Tool 是一个把UE3/UDK资源包(T3D格式)转换成UE4(T3D格式)的工具.作者Matt3D使用C#实现,未来考虑发布到Unreal Marketp ...

  8. Apache FtpServer扩展【动手实现自己的业务】

    Apache FtpServer是当下最热门的走ftp协议的用于用户上传下载的服务器. 官网http://mina.apache.org/ftpserver-project/   一般来说,用的话,去 ...

  9. 关于javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in &lt;forEach&gt;

    今天遇到这样一个异常: 严重: Servlet.service() for servlet jsp threw exceptionjavax.servlet.jsp.JspTagException: ...

  10. jar包程序 读取properties文件

    String proFilePath = System.getProperty("user.dir") + "\\Mysettings.properties"; ...