小弟再做个 word文档导出,
要求可以根据模版导出多条数据放在一个word中,但是替换标签时出现了 字符串过长的问题 有没有别的替换方式呢
   string templateFile = "E:\\dsc\\wwwroot\\download\\导出模版.doc";
        string fileNameWord = "E:\\dsc\\wwwroot\\download\\temp\\20140804110822.doc";
        DataTable dt = getDataTable();        bool ret = false;
        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
        object Obj_FileName = fileNameWord;
        object Visible = false;
        object ReadOnly = false;
        object missing = System.Reflection.Missing.Value;
        try
        {
            File.Copy(templateFile, fileNameWord, true);
            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();            doc.Tables[1].Select();//复制第一个表格,如果有多条粘贴到尾部
            app.Selection.Copy();//如果导入多条要把原来的模版粘贴下来            for (int i = 0; i < dt.Rows.Count; i++)
            {
                object replaceArea = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    object replaceKey = "$" + dt.Columns[j].ToString() + "$";
                    object replaceValue = dt.Rows[i][j].ToString();
                    doc.Tables[i + 1].Range.Find.Execute(ref replaceKey, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref  replaceValue, ref replaceArea, ref missing, ref missing, ref missing, ref missing);
                }
                if (i + 1 != dt.Rows.Count)//这里是导入多条把刚才的模版粘贴到尾部
                {
                    object mymissing = System.Reflection.Missing.Value;
                    object myunit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
                    app.Selection.EndKey(ref myunit, ref mymissing);
                    object pBreak = (int)Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
                    app.Selection.TypeParagraph();
                    app.Selection.Paste();
                }
            }
            doc.Save();
            ret = true;
        }
        catch (Exception)
        {
        }
        finally
        {
            object o = false;
            doc.Close(ref o, ref missing, ref missing);
            app.Quit(ref o, ref missing, ref missing);
        }
        return ret;

解决方案 »

  1.   

    在模板word里定义书签,然后要导出的时候,从模板copy一份,打开,在书签里插入内容,就OK了
    而不要把之前里面已经存在的内容复制来复制去的
      

  2.   

    namespace Exmaple
    {
        public partial class GvExprot2 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                //getData();
            }
            //public void getData()
            //{
            //    ////创建连接对象cn,准备好连接
            //    SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Person;Integrated Security=True");
            //    ////创建连接对象sqlcommand命令对象,准备好命令 
            //    SqlCommand cmd = new SqlCommand("SELECT * FROM [TStudent]", cn);
            //    //创建适配器对象da,其作用是真正的向数据库提交查询或更新
            //    SqlDataAdapter da = new SqlDataAdapter(cmd);
            //    ////创建数据集对象ds,实质是建立内存与数据库的一个映射
            //    DataSet ds = new DataSet();
            //    ////创建数据集对象ds,实质是建立内存与数据库的一个映射
            //    da.Fill(ds, "[TStudent]");
            //    //this.gvPersonList.DataSource = ds.Tables[0].DefaultView;
            //    ////给数据源赋值 
            //    this.gvPersonList.DataSource = ds;
            //    //绑定数据
            //    this.gvPersonList.DataBind();
            //}
            /// <summary>  
            /// 导出数据函数  
            /// </summary>  
            /// <param name="FileType">导出文件MIME类型</param>  
            /// <param name="FileName">导出文件的名称</param>  
            private void Exprot(String FileType, String FileName)
            {
                //恢复分页  
                gvPersonList.AllowPaging = false;
                //为GridView重新绑定数据源  
                gvPersonList.DataBind();
                //getData();
                Response.Clear();
                Response.BufferOutput = true;
                //设定输出字符集  
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.AppendHeader("Content-Disposition", "attachment;filename="
                + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
                //设置输出流HttpMiME类型(导出文件格式)  
                Response.ContentType = FileType;
                //关闭ViewState  
                Page.EnableViewState = false;
                System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);
                System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
                HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
                gvPersonList.RenderControl(textWriter);
                //把HTML写回游览器  
                Response.Write(stringWriter.ToString());
                Response.End();
                Response.Flush();
                //恢复分页  
                gvPersonList.AllowPaging = true;
                //为GridView重新绑定数据源 
                gvPersonList.DataBind();
                //getData();
            }        //导出Excel  
            protected void btnToExcel_Click(object sender, EventArgs e)
            {
                Exprot("application/ms-excel", "Employee.xls");
            }        //导出Word  
            protected void btnToWord_Click(object sender, EventArgs e)
            {
                //这里将导出的方法抽取了出来使用  
                Exprot("application/ms-word", "Employee.doc");
            }        //确认在运行时为指定的 ASP.NET 服务器控件呈现在 HtmlForm 控件中。  
            //(检验Asp.Net服务器空间是否呈现在HTMLForm控件中)  
            public override void VerifyRenderingInServerForm(Control control)
            {
                #region
                /* 对程序说明,在asp.net 1.1中由于对控件呈现不是很严格, 
                * 所以无需override void VerifyRenderingInServerForm(Control control)这个方法 
                * 但在asp.net2.0中,控件的校验严格了,RenderControl代码只有走正常流程在render方法 
                * 中它自己调用才能成功,在你自己写的事件方法中调用就会出现这个错误。这个错误信息有点误导, 
                * 你明明写在服务器控件Form内,它照样会这样提醒你, 
                * 实际上是asp.net2.0设置了内部变量控制RenderControl不允许在Render方法之外被轻易调用。 
                * 如果不override VerifyRenderingInServerForm就会报错。 
                * 我们override void VerifyRenderingInServerForm(Control control)这个方法, 
                * 里面不写任何代码即可*/
                //base.VerifyRenderingInServerForm(control);  
                #endregion
            }        /// <summary>  
            /// 分页  
            /// </summary>  
            protected void gvPersonList_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                gvPersonList.PageIndex = e.NewPageIndex;
                //BindGridView();
            }
        }
    }
      

  3.   

    嗯 我的模版是这样的  
    如果这个数据是多条的话  程序需要 copy 模版中的 表格 粘贴到文档的尾部,这个是copy过的替换书签的方法好像,书签不能重名
      

  4.   

    将多个word文档导出到一个word文档
     private Word.Application G_wa;//定义Word应用程序
            private object G_missing = //定义G_missing字段并添加引用
                System.Reflection.Missing.Value;
            private OpenFileDialog G_OpenFileDialog;//定义打开文件对话框
            private SaveFileDialog G_SaveFileDialog;//定义保存文件对话框
            private List<string> G_Str_Files = new List<string>();//定义字符串集合        private void btn_split_Click(object sender, EventArgs e)
            {
                btn_Merge.Enabled = false;//停用合并按钮
                ThreadPool.QueueUserWorkItem(//开始线程池
                    (pp) =>//使用lambda表达式
                    {
                        G_wa = new Microsoft.Office.Interop.Word.Application();//创建应用程序对象
                        Word.Document P_MainDocument =//新建合并文档对象
                            G_wa.Documents.Add(ref G_missing, ref G_missing
                            , ref G_missing, ref G_missing);
                        foreach (string P_Str in G_Str_Files)//遍历文档的集合
                        {
                            object P_strs = P_Str;//创建object对象
                            Word.Document P_Document = G_wa.Documents.Open(//打开Word文档
                                ref P_strs, ref G_missing, ref G_missing, ref G_missing
                                , ref G_missing, ref G_missing, ref G_missing, ref G_missing
                                , ref G_missing, ref G_missing, ref G_missing, ref G_missing
                                , ref G_missing, ref G_missing, ref G_missing, ref o);
                            Word.Range P_Range_temp = //得到文档全部范围
                                P_Document.Range(ref G_missing, ref G_missing);
                            P_Range_temp.Select();//选择文档全部范围
                            P_Range_temp.Copy();//复制文档全部范围
                            Word.Range P_Range_temp2 =//得到文档的范围
                                P_MainDocument.Range(ref G_missing, ref G_missing);
                            object P_end= Word.WdCollapseDirection.wdCollapseEnd;//创建object对象
                            P_Range_temp2.Collapse(ref P_end);//折叠文档范围
                            P_Range_temp2.Select();//选择档的最后位置
                            P_Range_temp2.Paste();//粘贴文档内容
                            ((Word._Document)P_Document).Close(ref G_missing, ref G_missing,//关闭文档
                                ref G_missing);
                        }
                        object P_SavePath=G_SaveFileDialog.FileName;//创建object对象
                        P_MainDocument.SaveAs(//保存合并后的文档
                            ref P_SavePath, ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                            ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                            ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                            ref G_missing);
                        ((Word._Application)G_wa.Application).Quit(//退出应用程序
                            ref G_missing, ref G_missing, ref G_missing);
                        this.Invoke(//调用窗体线程
                            (MethodInvoker)(() =>//使用lambda表达式
                            {
                                Clipboard.Clear();//清空剪切板
                                MessageBox.Show(//提示已经创建Word
                                    "成功合并Word文档!", "提示!");
                                btn_Merge.Enabled = true;//启用合并按钮
                            }));
                    });
            }