本文实例讲述了C#实现通过模板自动创建Word文档的方法,是非常实用的技巧。分享给大家供大家参考。具体实现方法如下:
引言:前段时间有项目要用c#生成Word格式的计算报告,通过网络查找到很多内容,但是都很凌乱,于是自己决定将具体的步骤总结整理出来,以便于更好的交流和以后相似问题可以迅速的解决!
现通过具体的示例演示具体的步骤:
第一步,制作模板
1.新建一个文档,设置文档内容。
2.在相应位置插入书签;将鼠标定位到要插入书签的位置,点击“插入”>“书签”,弹出对话框,输入书签名,点击“添加”按钮。
3.保存模板,命名为“模板1.dot”或者“模板1.doc”
第二步,设置项目中的引用
1.右击“解决方案资源管理器”中的项目目录下的“引用”,选择“添加引用”,打开“添加引用”对话框
2.在“添加引用”对话框中,选择“COM”>“Microsoft Word 11.0 Object Library”,点击“确定”按钮
3.相同操作打开“添加引用”对话框中,选择“浏览”项,查找到”Microsoft.Office.Interop.Word.dll”文件,选中它,点击“确定”按钮
注意:此处要查找的“Microsoft.Office.Interop.Word.dll”版本必须为“11.*.*.*”,“*”代表数字
第三步,编码
这一步分成两个部分
第一部分,Report类的编码
这部分我已经封装好,为文件“Report.cs”,可以直接使用
具体实现代码如下:(代码中有比较详细的注释)
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingMicrosoft.Office.Interop.Word; namespaceMYNAMESPACE //这边需要换成自己的命名空间名 { class Report { private _ApplicationwordApp= null; private _DocumentwordDoc= null; public _ApplicationApplication { get { returnwordApp; } set { wordApp = value; } } public_DocumentDocument { get { returnwordDoc; } set { wordDoc = value; } } //通过模板创建新文档 public void CreateNewDocument(stringfilePath) { killWinWordProcess(); wordApp = newApplicationClass(); wordApp.DisplayAlerts =WdAlertLevel.wdAlertsNone; wordApp.Visible =false; object missing =System.Reflection.Missing.Value; object templateName =filePath; wordDoc= wordApp.Documents.Open(ref templateName, refmissing, refmissing, refmissing,refmissing, refmissing, refmissing, refmissing, refmissing,refmissing, refmissing, refmissing, refmissing, refmissing,refmissing, refmissing); } //保存新文件 public void SaveDocument(stringfilePath) { object fileName =