日期:2014-05-20  浏览次数:20733 次

.net导出到以有的模版
公司已建好一个模版的word文档,如何把数据导出到这个模版文档中,而不是自己另外新建一个,然后把数据往里面添加  
------最佳解决方案--------------------
http://www.codeproject.com/Articles/20287/Generating-Word-Reports-Documents

根据word模板生成word表格报表文档(C#) 主要功能为根据word模板生成word报表文档,注意引用Interop.Word.dll;
首先要生成word程序对象
Word.Application app = new Word.Application();
根据模板文件生成新文件框架
File.Copy(TemplateFile, FileName);
生成documnet对象
ord.Document doc = new Word.Document();
        打开新文挡
        doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
            ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref Visible,
            ref missing, ref missing, ref missing,
            ref missing);
        doc.Activate();
将光标定位到新的书签(模板中定义了书签的位置),下面代码为在光标位置输出一行,然后回车
        //光标转到书签
        for (int bookIndex = 0; bookIndex < 5; bookIndex++)
        {
            object BookMarkName = "BookMark" + bookIndex.ToString();
            object what = Word.WdGoToItem.wdGoToBookmark;
            doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref BookMarkName);
            doc.ActiveWindow.Selection.TypeText("文明单位" + bookIndex.ToString() + "zaddd    25      大学");
            doc.ActiveWindow.Selection.TypeParagraph();
        }
输出完毕后,最后关闭doc对象
        object IsSave = true;
        doc.Close(ref IsSave, ref missing, ref missing);

完整事例代码如下:
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Word.Application app = new Word.Application();
        //模板文件
        string TemplateFile = @"D:\Mywork\ExcelReportsServer\ReportServer\Tempalte\SmallList.doc";