如何添加页面号和打印日期ms互操作词DLL

时间:2015-08-17 07:06:40

标签: c# ms-word office-interop

我想使用MS-Interop Word DLL将以下文本添加到MS-Word页脚中。

必需的页脚文字:

"第1页,共10页,日期= {当前日期}"这样的事情。 我添加了以下代码添加页面号。和当前日期,但它不允许我添加任何自定义文本,如" Page 1 of 10"。

这是我的代码

foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
            {
        Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        footerRange.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);


        footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldDate,"Date = ");
        footerRange.Fields.UpdateSource();
        footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage, "Page No = ");
        footerRange.Fields.UpdateSource();


        footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;


    }

如何添加此类功能?

1 个答案:

答案 0 :(得分:0)

这是我找到的解决方案。

 Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);


                    footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages);
                    Microsoft.Office.Interop.Word.Paragraph p4 = footerRange.Paragraphs.Add();
                    p4.Range.Text = " of ";
                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                    footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                    Microsoft.Office.Interop.Word.Paragraph p1 = footerRange.Paragraphs.Add();
                    p1.Range.Text = "Page: ";
                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                    Microsoft.Office.Interop.Word.Paragraph p3 = footerRange.Paragraphs.Add();
                    p3.Range.Text = " " + Environment.NewLine;

                    footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldDate);
                    Microsoft.Office.Interop.Word.Paragraph p2 = footerRange.Paragraphs.Add();
                    p2.Range.Text = "Print date: ";

                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                }