From:https://blog.csdn.net/weixin_32155265/article/details/126177808
用C#操作Word,电脑上原生的库为Microsoft.Office.Interop.Word,虽然有些慢,但也能用。操作word的另外一个库是Spire.Doc,但是商业的,破解版也不好搞,还是凑合用Microsoft.Office.Interop.Word吧。
现在需要根据Word模板生成受控报告,主要借助word标签实现该功能。但现在有一个需求,就是需要添加如下格式的页脚:第 页 共 页 PAGE_OF_
涉及到获取当前页面的页码。查了好多帖子,最后等外网找到了解决方案,那就直接放代码:
自此声明:上面代码用到的库为Microsoft.Office.Interop.Word。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
//设置页脚 /* 第 页 共 页 * PAGE_OF_ */ void setFooter(ref Word.Application app) { object missing = System.Reflection.Missing.Value; app.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; app.ActiveWindow.ActivePane.Selection.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; app.ActiveWindow.Selection.TypeText("第"); Object CurrentPage = Word.WdFieldType.wdFieldPage; app.ActiveWindow.Selection.Fields.Add(app.ActiveWindow.Selection.Range, ref CurrentPage, ref missing, ref missing); app.ActiveWindow.Selection.TypeText("页 共"); Object TotalPages = Word.WdFieldType.wdFieldNumPages; app.ActiveWindow.Selection.Fields.Add(app.ActiveWindow.Selection.Range, ref TotalPages, ref missing, ref missing); app.ActiveWindow.Selection.TypeText("页\n"); /* Insert current page number "Page X of N" on a word document */ /*======================================================================*/ // Open up the footer in the word document app.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; // Set current Paragraph Alignment to Center app.ActiveWindow.ActivePane.Selection.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; // Type in 'Page ' app.ActiveWindow.Selection.TypeText("PAGE"); // Add in current page field CurrentPage = Word.WdFieldType.wdFieldPage; app.ActiveWindow.Selection.Fields.Add(app.ActiveWindow.Selection.Range, ref CurrentPage, ref missing, ref missing); // Type in ' of ' app.ActiveWindow.Selection.TypeText("OF"); // Add in total page field TotalPages = Word.WdFieldType.wdFieldNumPages; app.ActiveWindow.Selection.Fields.Add(app.ActiveWindow.Selection.Range, ref TotalPages, ref missing, ref missing); /*======================================================================*/ } |
