c#获取word中各级标题

2 篇文章 0 订阅

//大致思路:循环段落,判断每个段落属于几级标题或者是正文(或者循环行也行)   

 Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;//获取当前最新一个打开的文档           

foreach (Paragraph item in doc.Paragraphs)
                {

                    var style_Word = (Microsoft.Office.Interop.Word.Style)item.get_Style();

                    if (style_Word.NameLocal == "标题 1")
                    {
                      string  str = item.Range.Text + Environment.NewLine; //获取到的一级标题
                    }

                    if (style_Word.NameLocal == "标题 2")
                    {
                      string  str = item.Range.Text + Environment.NewLine; //获取到的二级标题
                    }

                  if (style_Word.NameLocal =="正文")
                    {
                      string  str = item.Range.Text + Environment.NewLine; //获取正文内容

                    }

                }

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C# ,可以通过使用 Microsoft.Office.Interop.Word 命名空间的对象来获取 Word 文档分页符的位置。下面是一个示例代码: ``` using Word = Microsoft.Office.Interop.Word; // 打开 Word 文档 Word.Application wordApp = new Word.Application(); Word.Document doc = wordApp.Documents.Open("C:\\test.docx"); // 获取文档的所有分页符 Word.Range range = doc.Range(); object pageBreakType = Word.WdBreakType.wdSectionBreakNextPage; Word.Find find = range.Find; find.Text = "^m"; // ^m 表示分页符 find.Replacement.Text = ""; find.Execute(ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref pageBreakType, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing); // 遍历分页符并获取其位置 while (range.Find.Found) { int pageNum = range.Information[Word.WdInformation.wdActiveEndPageNumber]; int location = range.Start; Console.WriteLine("分页符在第 {0} 页,位置为 {1}", pageNum, location); range.Start = range.End + 1; range.End = doc.Content.End; find.Execute(ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref pageBreakType, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing, ref Type.Missing); } // 关闭 Word 文档和应用程序 doc.Close(); wordApp.Quit(); ``` 在上面的代码,首先打开 Word 文档并获取其范围。然后使用 `Find()` 方法查找文档的所有分页符,并遍历每个分页符以获取其位置和所在页码。最后关闭 Word 文档和应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值