C#依據word模版動態生成文檔


新生開學,各院系輔導員代領校園卡。需要打印一份領取卡的協議,協議模版固定,但各院系卡的數量不同。需要從excel表格中抽取數據往word文件中填,同事咨詢是否可以用word中的郵件合並功能,心想有這功夫研究還不如自己寫代碼實現。一共三個問題:1)讀取Excel表格數據,2)往word模板文件中寫數據,3)生成word文件。

1)C#讀取Excel文件中的數據:創建OleDb連接,將Excel作為數據源,讀取至DataTable中,待使用

     private static DataSet LoadDataFromExcel(string filePath)
        {
            try
            {
                string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filePath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                String sql = "SELECT * FROM  [本科生$]"; //根據自己要讀取的Excel中的Sheet改名字

                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet OleDsExcle = new DataSet();
                OleDaExcel.Fill(OleDsExcle, "Sheet1");
                OleConn.Close();
                return OleDsExcle;
            }
            catch (Exception err)
            {
                MessageBox.Show("讀取Excel數據失敗:" + err.Message, "提示信息",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return null;
            }
        }

2)創建好word的模版文件(.dot),並在需要動態寫入數據的地方插入標簽。

創建好如上圖唆使的模板文檔,保存為master.dot。接下來就開始寫文件了,在這之前,先看看Excel表格內的數據結構是怎樣的。如下圖,我們只需要用到前四列的數據,往word文檔中寫入。院系標簽的值由1、2兩列合並構成,卡數量和卡套數量均取自校園卡數一列,報到證數量則取自報到證數列。

3)寫數據並生成word文檔,代碼如下。需要在項目中引用Com組建,右鍵項目,“添加引用” --> “COM” --> “MicroSoft Office 15 Object Library”。

    private void button3_Click(object sender, EventArgs e)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt = LoadDataFromExcel(dataSourceText.Text.Trim()).Tables[0];
            try
            {
                for (int i = 2; i < dt.Rows.Count; i++)
                {
                    object oMissing = System.Reflection.Missing.Value;
                    //創建一個Word應用程序實例  
                    Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();
                    //設置為不可見  
                    oWord.Visible = false;
                    //模板文件地址,這里假設在X盤根目錄  
                    object oTemplate = dataDestinationText.Text.Trim();
                    //以模板為基礎生成文檔  
                    Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
                    //聲明書簽數組  
                    object[] oBookMark = new object[5];
                    //賦值書簽名  
                    oBookMark[0] = "department";
                    oBookMark[1] = "cardno";
                    oBookMark[2] = "cardskinno";
                    oBookMark[3] = "registration";

                    //賦值任意數據到書簽的位置  
                    oDoc.Bookmarks.get_Item(ref oBookMark[0]).Range.Text = dt.Rows[i][0].ToString() + dt.Rows[i][1].ToString();
                    oDoc.Bookmarks.get_Item(ref oBookMark[1]).Range.Text = dt.Rows[i][2].ToString();
                    oDoc.Bookmarks.get_Item(ref oBookMark[2]).Range.Text = dt.Rows[i][2].ToString();
                    oDoc.Bookmarks.get_Item(ref oBookMark[3]).Range.Text = dt.Rows[i][3].ToString();

                    //設置文件保存路徑
                    string savePath = saveAsText.Text.Trim();
                    object fileName;
                    fileName = savePath + "\\" + dt.Rows[i][0].ToString() + dt.Rows[i][1].ToString();
                    oDoc.SaveAs(ref fileName, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing);
                    oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                    //關閉word  
                    oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                }
                MessageBox.Show("生成文件完成!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("錯誤,請截圖發至xxxx" + ex.Message);
            }
        }

至此,構建了一個小小工具,以后再有這類工作,直接拿來使用,省事許多。

本文參考博客:http://blog.csdn.net/fujie724/article/details/5443322


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM