word中导出目录是一个常见的问题。详细代码如下:
public static void ExportMenu(int maxLevel, Document word) //利用标题样式生成目录
{
//GoToTheBeginning(word);
GotoBookMark("bmContent", word);
object start = 0;
object end = 0;
Range myRange = word.Application.Selection.Range; //word.Application.ActiveDocument.Range(ref start, ref end); //位置区域
object useHeadingStyle = true; //使用Head样式
object upperHeadingLevel = 1; //最大一级
object lowerHeadingLevel = maxLevel; //最小三级
object useHypeLinks = true;
//TablesOfContents的Add方法添加目录
word.TablesOfContents.Add(myRange, ref useHeadingStyle,
ref upperHeadingLevel, ref lowerHeadingLevel,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref useHypeLinks, ref Nothing, ref Nothing);
word.TablesOfContents[1].UpdatePageNumbers(); //更新页码
TableOfContents myContent = word.TablesOfContents[1]; //目录
Paragraphs myParagraphs = myContent.Range.Paragraphs; //目录里的所有段,一行一段
}
当然,在之前导出的文档中,要设置好相应级别的标题。