c# 使用模板导出word

c#使用的word 是 Microsoft.Office.Interop.Word

1.前台使用extjs ,直接跳转后台,method 使用的是get,post 发现不会跳转。

 Ext.Ajax.request({
    url: "/XXX/XXXX/",
    method: "get",
    params: {
        GuidS: json,
        danwei: text
    },
    success: function (responce) {
        console.log("responce", responce);
        myMask.hide();

        var delresult = Ext.decode(responce.responseText);
        if (delresult.success) {
            Ext.example.msg("提示信息", delresult.msg);
            var currentPage = store.currentPage;//Store 最后一次load的页
            store.loadPage(currentPage);
        } else {
            Ext.example.msg("提示信息", delresult.msg);
        }
    }
});

2.C# 后台
savePath自己定义的文件保存位置
mobanFile 模板的位置

    String mobanFile = "~\\Resources\\word\\gonggaomoban.doc";//模版路径
   //保存文件到指定位置
        public string GonggaoReceipt(string savePath, zh_gonggao gg, string GuidS)
        {

            object outputFile = null;
            string msg = "";
            try
            {
                var uploadPath = Server.MapPath(savePath);
                //判断文件是否存在
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                //初始化
                object typeMissing = Type.Missing;
                object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                object readOnlyRecommended = false;
                wordApp = new Microsoft.Office.Interop.Word.Application();
                string guid = gg.gonggao_id;


                object templateFile = Server.MapPath(mobanFile);
                wordDoc = wordApp.Documents.Add(ref templateFile, ref typeMissing, ref typeMissing, ref typeMissing);
                wordDoc.SpellingChecked = false;
                wordDoc.ShowSpellingErrors = false;



                //table1书签 绑定字段
                #region 插入文本
                //文本标题
                var titleText = gg.quyu;

                //查询道路数据
                string sql = " XXX";
                MySqlParameter[] parameter = {
                                                     new MySqlParameter("@gonggao_id",gg.gonggao_id ),
                                                     new MySqlParameter("@jcGuid",GuidS ),
                                                };
                DataTable dt = dbHelper.ExecuteSelDataTable(sql.ToString(), parameter.ToArray());

              
                string biaozhunText = "本次新增的 xxxx的收费标准和计费规定执行如下";

                //查询智慧道路
                string sqlroad = " xxxxx ";
                MySqlParameter[] parameter_road = {
                                                     new MySqlParameter("@Quxian",gg.quId  ),
                                                };
                DataTable dt_road = dbHelper.ExecuteSelDataTable(sqlroad.ToString(), parameter_road.ToArray());
                int qingdanCount = dt_road.Rows.Count;

                //table1书签 绑定字段
                foreach (Microsoft.Office.Interop.Word.Bookmark bm in wordDoc.Bookmarks)
                {
                    if (bm.Name == "titleText")
                    {
                        bm.Select();
                        bm.Range.Text = titleText;
                    }
                    else if (bm.Name == "roadText")
                    {
                        bm.Select();
                        bm.Range.Text = roadText;
                    }
                    else if (bm.Name == "roadCount")
                    {
                        bm.Select();
                        bm.Range.Text = roadCount.ToString();
                    }
                    else if (bm.Name == "biaozhunText")
                    {
                        bm.Select();
                        bm.Range.Text = biaozhunText;
                    }
                    else if (bm.Name == "danwei")
                    {
                        bm.Select();
                        bm.Range.Text = gg.danwei;
                    }
                    else if (bm.Name == "qingdanCount")
                    {
                        bm.Select();
                        bm.Range.Text = qingdanCount.ToString();
                    }
                }
                #endregion

                #region 遍历表格
                //DataSet ds = GetDataSet();//获取程序集合
                //开始判断里面有几个表格/因为模板里面有三张表
                //需要填充第一张表和第三张表
                for (int tablePos = 1; tablePos <= wordDoc.Tables.Count; tablePos++)
                {
                    //都一张表的时候
                    if (tablePos == 1)
                    {
                        int dsCount = dt.Rows.Count;//得到数据库表中的数据
                        int docCount = wordDoc.Tables[1].Rows.Count; //得到文档中表格的数据,减去标题行
                        if (dsCount >= docCount) //当实际数据大约表格数据的时候创建行
                        {
                            //开始增加行
                            Microsoft.Office.Interop.Word.Table newTable = wordDoc.Tables[1];
                            for (int row = 0; row < (dsCount - docCount) + 1; row++)
                            {
                                object beforeRow = newTable.Rows[docCount];
                                newTable.Rows.Add(ref beforeRow); // 行添加到表格中
                            }
                        }
                        //表格完成之后开始增加数据,为单元格赋值
                        for (int rcount = 0; rcount < dt.Rows.Count; rcount++)
                        {
                            for (int ccount = 0; ccount < dt.Columns.Count; ccount++)
                            {
                                //doc.Tables[1].Rows[rowPos].Cells[columPos].Range.Text
                                string strText = dt.Rows[rcount][ccount].ToString();
                                wordDoc.Tables[1].Rows[rcount + 2].Cells[ccount + 1].Range.Text = strText;//从第二行开始算起
                                if (strText == "r")
                                {
                                    wordDoc.Tables[1].Rows[rcount + 2].Cells[ccount + 1].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
                                }
                            }
                        }
                    }
                    else if (tablePos == 3)
                    {
                        int dsCount = dt_road.Rows.Count;//得到数据库表中的数据
                        int docCount = wordDoc.Tables[3].Rows.Count; //得到文档中表格的数据
                        if (dsCount >= docCount) //当实际数据大约表格数据的时候创建行
                        {
                            //开始增加行
                            Microsoft.Office.Interop.Word.Table newTable = wordDoc.Tables[3];
                            for (int row = 0; row < (dsCount - docCount) + 1; row++)
                            {
                                object beforeRow = newTable.Rows[docCount];
                                newTable.Rows.Add(ref beforeRow); // 行添加到表格中
                            }
                        }
                        //表格完成之后开始增加数据,为单元格赋值
                        for (int rcount = 0; rcount < dt_road.Rows.Count; rcount++)
                        {
                            for (int ccount = 0; ccount < dt_road.Columns.Count; ccount++)
                            {
                                //doc.Tables[1].Rows[rowPos].Cells[columPos].Range.Text
                                string strText = dt_road.Rows[rcount][ccount].ToString();
                                wordDoc.Tables[3].Rows[rcount + 2].Cells[ccount + 1].Range.Text = strText;//从第二行开始算起
                                if (strText == "r")
                                {
                                    wordDoc.Tables[3].Rows[rcount + 2].Cells[ccount + 1].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
                                }
                            }
                        }
                    }
                }

                #endregion
                outputFile = Server.MapPath(String.Format(savePath + "\\{0}.doc", guid));

                wordDoc.SaveAs(ref outputFile, ref FileFormat, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref readOnlyRecommended, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing);
                wordDoc.Close(ref typeMissing, ref typeMissing, ref typeMissing);
                wordApp.Quit(ref typeMissing, ref typeMissing, ref typeMissing);//最后关闭

            
            }
            catch (Exception ex)
            {
                object typeMissing = Type.Missing;
                if (wordDoc != null)
                    wordDoc.Close(ref typeMissing, ref typeMissing, ref typeMissing);
                if (wordApp != null)
                    wordApp.Quit(ref typeMissing, ref typeMissing, ref typeMissing);
                msg= ex.Message;
            }
            finally
            {
                GC.Collect();
            }
            return msg;

        }


3.如果需要下载,加入下面的方法

  public string  ToDownload(string savePath, zh_gonggao gg, string GuidS)
        {
            //生成word
           // string guid = GonggaoReceipt(savePath, gg, GuidS);


            string FilePath = Server.MapPath(String.Format(ZHRoadggFile + "\\{0}.doc", gg.gonggao_id));


            string FileName = String.Format("{0}.doc", gg.gonggao_id);
            FileStream fileStream = new FileStream(FilePath, FileMode.Open);
            long fileSize = fileStream.Length;
            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + FileName + "");

            System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
            byte[] fileBuffer = new byte[fileSize];
            fileStream.Read(fileBuffer, 0, (int)fileSize);
            System.Web.HttpContext.Current.Response.OutputStream.Write(fileBuffer, 0, (int)fileSize);
            fileStream.Close();
            System.Web.HttpContext.Current.Response.End();
            return FilePath ;
        }

4.给word 模板加书签,发现时间长了容易忘,记录一下,在需要填充数据的位置插入书签,然后起个名字便于绑定。
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值