如何使用C#获取Word文档中的段落编号?

问题描述:

我使用程序集Microsoft.Office.Interop.Word;如何使用C#获取Word文档中的段落编号?

我的文档是一个Microsoft.Office.Interop.Word.Document对象,我想获取本文档中每个段落的编号。

我该怎么做?

+0

你是什么意思时,你说“每个段落的数量”? – 2012-08-02 13:31:03

+0

看看这个:http://support.microsoft.com/kb/315728,它是用VB.net制作的。我想用C#做同样的事情 – user1523566 2012-08-03 08:25:20

你需要的东西是这样的:

object misValue = System.Reflection.Missing.Value; 
    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); 
    object docPth = @"c:\tmp\aDoc.doc"; 
    Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref docPth, ref misValue, ref misValue, 
     ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, 
     ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue); 
    wordApp.Visible = true; 
    foreach (Microsoft.Office.Interop.Word.Paragraph aPar in aDoc.Paragraphs) 
    { 
     Microsoft.Office.Interop.Word.Range parRng = aPar.Range; 
     string sText = parRng.Text; 
     string sList = parRng.ListFormat.ListString; 
     int nLevel = parRng.ListFormat.ListLevelNumber; 
     MessageBox.Show("Text = " + sText + " - List = " + sList + " - Level " + nLevel.ToString()); 
    } 

在开始使用Microsoft.Office.Interop.Word library/dll之前,您必须阅读该库的文档。

这里阅读:

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.paragraphs_members.aspx

此外,取决于你用什么版本的Office做。

+1

我已经阅读过文档,我使用visual studio 2008和框架3.5 – user1523566 2012-08-02 13:13:22

如果您有一个Document对象,那么您已经可以获取文档中每个段落的'数字'或'索引'。例如,如果你需要得到第二段的文本文档中,你说:

MSWord.Application app = (MSWord.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"); 
MSWord.Document doc = app.ActiveDocument; //the document that's on screen and 'active' 

Console.WriteLine("Paragraph Count: " + doc.Paragraphs.Count); //show total number of paragraphs available in document. 
Console.Write Line("Paragraph number 2 text: " + doc.Paragraphs[2].Range.Text);    //show text of paragraph number 2 

Console.ReadLine(); 

如果这没有帮助。请...编辑你的问题。除非您澄清,否则我们实在无法做任何事情。

+0

我想要做类似的事情:http://support.microsoft.com/kb/315728但是使用C#以获得该段落的列表和其级别 – user1523566 2012-08-03 08:12:01

+0

如果还不清楚,我已准备好解释更多。 – user1523566 2012-08-03 08:26:54