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());
        }







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章