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

posted on 2015-09-01 14:51  andywangguanxi  阅读(3607)  评论(0编辑  收藏  举报