WPF应用程序生成Word文档测试

莫名其妙地有了这个需求,于是进行了一下实战。本文使用天气预报api自动生成Word格式的报表,使用VSTO相关技术,在VS2017+Word2016中测试通过,结果如图:
在这里插入图片描述

Word模板制作

图中大标题及文末日期为两个格式文本内容控件(RichTextContentControl),而后用{1}表示即将添加正文的部分。如图所示:在这里插入图片描述为了方便之后添加文字,将标题控件的标记(Tag)命名为TitleRTFControl,日期控件的标记(Tag)命名为DateRTFControl,将模板保存为Test.dotx。

在VS2017中新建WPF应用程序,添加对Microsoft.Office.Interop.Word和Microsoft.Office.Tools.Word的引用。并在MainWindow中添加按钮。
为方便起见,

using Word = Microsoft.Office.Interop.Word;
using Tools = Microsoft.Office.Tools.Word;

使用模板新建文档

Word.Application application = new Word.Application();//新建Word应用程序
application.Visible = true;//显示Word窗口,删除此句Word以后台方式运行
var document = application.Documents.Add(System.Environment.CurrentDirectory+"\\Test.dotx");//以模板新建文档

使用Tag寻找内容控件,获得其实例的引用,并修改其内容。注意,Word中数组的index多从1开始,而不是0

 #region 寻找内容控件
 Word.ContentControl TitleRTFControl = document.SelectContentControlsByTag("TitleRTFControl")[1];
 Word.ContentControl DateRTFControl = document.SelectContentControlsByTag("DateRTFControl")[1];
 #endregion
 #region 修改内容控件内容
 TitleRTFControl.Range.Text = "全国主要城市天气预报";
 DateRTFControl.Range.Text = DateTime.Now.ToString("yyyy年MM月dd日");
 #endregion

之后寻找文档中的占位符{1},全选文档,在选定范围内查找并选中。因Document.Range需传送两个object对象,故使用start和end对int进行封装。

#region 查找文档中的文字并选中
object FindText = "{1}";
object start = document.Content.Start;
object end = document.Content.End;
Word.Range range = document.Range(start, end);
range.Find.ClearFormatting();
if (range.Find.Execute(ref FindText))
{
    range.Select();
}
#endregion

替换文字,之前已从api中获取天气数据并存储在一个StringBuilder对象中。

#region 插入文字
Word.Selection currentSelection = application.Selection;
application.Options.Overtype = false;

currentSelection.TypeText(stringBuilder.ToString());
currentSelection.TypeParagraph();

#endregion

点击执行,效果良好。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Eric_Sun_Hello/article/details/82967805