C# 后台生成Word表单

背景:C#web程序。
需求:程序的某个表单需要打印出来,又不能直接打印网页,因此需要后台先生成word文件。
准备:
        1.做一个word模板,要生成的样式,在要填写数据的位置加上书签(word内实现)
        2.引用word的服务引用office.dll、Microsoft.Office.Interop.Word.dll、Microsoft.Vbe.Interop.dll
        3.程序的web.config的<system.web>中添加<identity impersonate="true" userName="***" password="**" />计算机账号和密码,这个是为了发布后别人可以调用,否则只能本机使用了。
程序逻辑:
        1.复制生成一个新的word文件。
        2.把数据填写到新的word文件内。
        3.当有子表的时候(如下图1),获取第四行的对象,然后添加的word内,然后再原来的行填写数据,循环执行,最后删掉最后一行
        4.保存新的word文件,然后将新的word文件的地址返回给用户,用户直接下载。
      

                                                                                                               图一:模板表单
                                                                                                                         图二:生成的打印表单

代码(只填写数据部分):
// entity 需要填写的对象,因为改对象不完整,所以需要关联其他对象才能完整填写
public ActionResult ExecuteExportWord(InvoiceEntity entity)
        {
            ProjectApproveBLL projectbll = new ProjectApproveBLL();
            ProjectApproveEntity project = projectbll.GetEntity(entity.ProjectId);
            InvoiceBLL invoicebll = new InvoiceBLL();
            IEnumerable<InvoiceNoticeEntity> iNoticeList = invoicebll.GetNoticeDetail(entity.ID);
            DataItemCache dataItemCache = new DataItemCache();

            string oFileName = Server.MapPath("~" + string.Format("/Resource/WordModel/NKP20170118.doc"));//用object
            //复制新的文件
            string date = DateTime.Now.ToString("yyyy-MM-dd");
            string fileName = entity.BillNumber + ".doc";

            string strFileName = Server.MapPath("~" + string.Format("/Resource/WordModel/")) + date + "/" + fileName;
            if (!System.IO.File.Exists(strFileName))
            {
                if (!Directory.Exists(Server.MapPath("~" + string.Format("/Resource/WordModel/")) + date))
                {
                    Directory.CreateDirectory(Server.MapPath("~" + string.Format("/Resource/WordModel/")) + date);
                }
                System.IO.File.Copy(oFileName, strFileName, true);
            }
            else
            {
                System.IO.File.Delete(strFileName);//如果已有,删除原来的
                System.IO.File.Copy(oFileName, strFileName, true);
            }
            object file = Server.MapPath("~" + string.Format("/Resource/WordModel/")) + date + "/" + fileName;

            Microsoft.Office.Interop.Word.Application oWord;
            Microsoft.Office.Interop.Word.Document oDoc;
            Microsoft.Office.Interop.Word.Table pTable;

            object missing1 = Missing.Value;
            oWord = new Microsoft.Office.Interop.Word.Application();
            oDoc = oWord.Documents.Open(ref file, ref missing1, ref missing1,
                ref missing1, ref missing1, ref missing1, ref missing1, ref missing1,
                ref missing1, ref missing1, ref missing1, ref missing1, ref missing1,
                ref missing1, ref missing1, ref missing1);
            pTable = oDoc.Tables[1];
            try
            {
                #region 填属性
                //开票编号
                object tmp1 = "kpbh";
                Microsoft.Office.Interop.Word.Range startKobh = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp1).Range;
                startKobh.Text = entity.BillNumber;

                //项目名称
                object tmp2 = "xmmc";
                Microsoft.Office.Interop.Word.Range startXmmc = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp2).Range;
                startXmmc.Text = project.ProjectName;
                //付款单位
                object tmp3 = "fkdw";
                Microsoft.Office.Interop.Word.Range startFkdw = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp3).Range;
                startFkdw.Text = entity.ClientCompany;
                //联系人
                object tmp4 = "lxr";
                Microsoft.Office.Interop.Word.Range startLxr = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp4).Range;
                startLxr.Text = entity.ClientName;
                //联系电话
                object tmp5 = "lxdh";
                Microsoft.Office.Interop.Word.Range startLxdh = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp5).Range;
                startLxdh.Text = entity.ClientMobile;

                //票据种类
                object tmp6 = "pjzl";
                Microsoft.Office.Interop.Word.Range startPjzl = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp6).Range;
                startPjzl.Text = entity.NoteType;
                //发票类别
                object tmp7 = "fplb";
                Microsoft.Office.Interop.Word.Range startFplb = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp7).Range;
                IEnumerable<DataItemModel> dataItem = dataItemCache.GetDataItemList("InvoiceType");
                foreach (DataItemModel model in dataItem)
                {
                    if (model.ItemValue.Equals(entity.InvoiceType))
                    {
                        startFplb.Text = model.ItemName;
                        break;
                    }
                }
                //发票明细
                object tmp8 = "fpmx";
                Microsoft.Office.Interop.Word.Range startFpmx = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp8).Range;
                startFpmx.Text = "";//entity.InvoiceDetail;                    
                //收款类型
                object tmp9 = "sklx";
                Microsoft.Office.Interop.Word.Range startSklx = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp9).Range;
                startSklx.Text = entity.Receivables;

                //开票详情子表List
                //iNoticeList
                int i =0;             
                foreach (InvoiceNoticeEntity notice in iNoticeList)
                {
                    i++;
                    //添加单元格
                    object beforeRow = oDoc.Tables[1].Rows[3 + i];//此行是先获取到第4行
                    oDoc.Tables[1].Rows.Add(ref beforeRow);
                   
                    pTable.Cell(3 + i, 1).Range.Text = i.ToString();
                    pTable.Cell(3 + i, 2).Range.Text = notice.InvoiceProject;
                    pTable.Cell(3 + i, 3).Range.Text = notice.Quantity.ToString();
                    pTable.Cell(3 + i, 4).Range.Text = notice.UnitPrice.ToString();
                    pTable.Cell(3 + i, 5).Range.Text = notice.Total.ToString();                 
                }
                oDoc.Tables[1].Rows[4+i].Delete();//多出来的复制行去掉
                //开票备注
                object tmp10 = "kpbz";
                Microsoft.Office.Interop.Word.Range startKpbz = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp10).Range;
                startKpbz.Text = entity.InvoiceComment;
                //小计
                object tmp11 = "xj";
                Microsoft.Office.Interop.Word.Range startXj = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp11).Range;
                startXj.Text = entity.InvoiceSumA.ToString();

                //下达者
                object tmp12 = "xdz";
                Microsoft.Office.Interop.Word.Range startXdz = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp12).Range;
                startXdz.Text = entity.UserName;
                //下达日期
                object tmp13 = "xdrq";
                Microsoft.Office.Interop.Word.Range startXdrq = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp13).Range;
                startXdrq.Text = DateTime.Parse(entity.ApplyDate.ToString()).ToString("yyyy年MM月dd日");

                //发票号
                object tmp14 = "fph";
                Microsoft.Office.Interop.Word.Range startFph = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp14).Range;
                startFph.Text = entity.InvoiceNumber;
                //开票日期
                object tmp15 = "kprq";
                Microsoft.Office.Interop.Word.Range startKprq = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp15).Range;
                startKprq.Text = DateTime.Parse(entity.InvoiceDate.ToString()).ToString("yyyy年MM月dd日");

                //经办人
                object tmp16 = "jbr";
                Microsoft.Office.Interop.Word.Range startJbr = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp16).Range;
                startJbr.Text = entity.InvoiceOperator == null ? OperatorProvider.Provider.Current().UserName : entity.InvoiceOperator;
                //经办日期
                object tmp17 = "jbrq";
                Microsoft.Office.Interop.Word.Range startJbrq = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp17).Range;
                startJbrq.Text = entity.InvoiceDate == null ? DateTime.Now.ToString("yyyy年MM月dd日") : DateTime.Parse(entity.InvoiceDate.ToString()).ToString("yyyy年MM月dd日");

                object tmp18 = "bz";
                Microsoft.Office.Interop.Word.Range startBz = oWord.ActiveDocument.Bookmarks.get_Item(ref tmp18).Range;
                startBz.Text = entity.Comment;
                #endregion

                //将WordDoc文档对象的内容保存为DOC文档      
                oDoc.SaveAs(ref file, ref missing1, ref missing1,
                   ref missing1, ref missing1, ref missing1, ref missing1, ref missing1,
                   ref missing1, ref missing1, ref missing1, ref missing1, ref missing1,
                   ref missing1, ref missing1, ref missing1);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                //关闭WordDoc文档对象      
                oDoc.Close(ref missing1, ref missing1, ref missing1);
                //关闭WordApp组件对象      
                oWord.Quit(ref missing1, ref missing1, ref missing1);
            }
            var data = new DataTable();
            data.Columns.Add("name", Type.GetType("System.String"));
            data.Columns.Add("url", Type.GetType("System.String"));
            DataRow row = data.NewRow();
            //下载需要name 和url
            row["url"] = "../../Resource/WordModel/" + date + "/" + fileName;
            row["name"] = fileName;
            data.Rows.Add(row);
            return Content(data.ToJson());
        }







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值