C#获取Word文档页数,并跳转到指定的页面获取内容,且插入分页符

本文介绍了如何使用MS Word创建、打开、计算页数、跳转到特定书签和页面、插入段落、分页、使用正则表达式分割段落、插入回车和分页符、以及操作文档内容的基本技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using MSWord = Microsoft.Office.Interop.Word;  

MSWord.Application wordApp; //Word应用程序变量

MSWord.Document wordDoc;    //Word文档变量

Object Nothing = Missing.Value;  //初始化

wordApp = new MSWord.ApplicationClass();

wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, refNothing, ref Nothing); // 新建Word

 

// 打开已存在的Word

object FileName = strPath;

object readOnly = false;

object isVisible = true;

wordDoc = wordApp.Documents.Open(ref FileName, ref Nothing, refreadOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, refNothing, ref Nothing);  


// 计算Word文档页数

MSWord.WdStatistic stat = MSWord.WdStatistic.wdStatisticPages;

int num = wordDoc.ComputeStatistics(stat, ref  Nothing);


// 跳转到指定书签

object what = MSWord.WdGoToItem.wdGoToBookmark;

object BookMarkName = "BookMark1";

wordDoc.ActiveWindow.Selection.GoTo(ref what, ref Nothing, refNothing, ref BookMarkName);

MessageBox.Show(wordDoc.ActiveWindow.Selection.Paragraphs[1].Range.Text.ToString()); 


//跳转到指定页

object What = MSWord.WdGoToItem.wdGoToPage;

object Which = MSWord.WdGoToDirection.wdGoToNext;

object Name = "1"; // 页数

wordDoc.ActiveWindow.Selection.GoTo(ref What, ref Which, refNothing, ref Name); // 第二个参数可以用Nothing

MessageBox.Show(wordDoc.ActiveWindow.Selection.Paragraphs[1].Range.Text.ToString()); 

MessageBox.Show(wordDoc.ActiveWindow.Selection.Sentences[1].Text.ToString());

MessageBox.Show(wordDoc.ActiveWindow.Selection.Paragraphs[1].Range.Sentences[1].Text.ToString());


MessageBox.Show(wordDoc.Content.Paragraphs[8].Range.Text.ToString());
MessageBox.Show(wordDoc.Content.Paragraphs[8].Range.Sentences[1].Text.ToString());



//插入段落并分页

Word.Paragraph oPara4;
oPara4 = mydoc.Content.Paragraphs.Add(ref oMissing);
oPara4.Range.Text = "附图一:";
oPara4.Range.Font.Name = "宋体";
oPara4.Range.Font.Size = 10.5f; 
oPara4.Range.InsertParagraphAfter();
insertChart(saveDocPath);//插入excel-chart
oPara4.Range.InsertParagraphAfter();

//插入分页符
insertBreakNextPage();


//用正则表达式分割段落

string string2 = "  段落1。\r\n 段落2。\r\n 段落3。";
string[] Paras = System.Text.RegularExpressions.Regex.Split(string2, @"\r\n");


//插入回车符

word.Selection.TypeParagraph();

//插入回格符

word.Selection.TypeBackspace();

//跳转到文档结尾

object wd_story = Word.WdUnits.wdStory;

word.Selection.EndKey(ref wd_story, ref oMissing);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值