导出DataGridView显示列数据到Excel中:)

被刻印的时光 ゝ 提交于 2020-03-12 09:26:51
    /// <summary>
    /// DataToExcel 的摘要说明。
    ///代码很简单就不多说什么了。:)大家自己看吧
    ///参考了堂子里一个大侠的代码,具体地址忘记了。这里说声不好意思。
    /// </summary>
    public class DataToExcel
    {
        const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;";

        public DataToExcel()
        {
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="excelPath"></param>
        /// <returns></returns>
        public string DataGridViewToExcel(System.Windows.Forms.DataGridView dgv, string excelPath)
        {
            if (dgv == null)
            {
                return "DataGridView不能为空";
            }

            object[] os = (object[])dgv.DataSource;

            int cols = dgv.Columns.Count;
            StringBuilder sb;
            string connString;

            if (os.Length == 0)
            {
                return "没有数据";
            }

            sb = new StringBuilder();
            connString = string.Format(ConnectionString, excelPath);

            //生成创建表的脚本
            sb.Append("CREATE TABLE ");
            sb.Append(dgv.Name + " ( ");

            for (int i = 0; i < cols; i++)
            {
                if (i < cols - 1)
                {
                    if (dgv.Columns[i].Visible)
                    {
                        sb.Append(string.Format("{0} varchar,", dgv.Columns[i].HeaderText));
                    }
                }
                else
                {
                    if (dgv.Columns[i].Visible)
                    {
                        sb.Append(string.Format("{0} varchar)", dgv.Columns[i].HeaderText));
                    }
                }
            }

            using (OleDbConnection objConn = new OleDbConnection(connString))
            {
                OleDbCommand objCmd = new OleDbCommand();
                objCmd.Connection = objConn;

                objCmd.CommandText = sb.ToString();

                try
                {
                    objConn.Open();
                    objCmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    return "在Excel中创建表失败,错误信息:" + e.Message;
                }

                #region 生成插入数据脚本
                sb.Remove(0, sb.Length);
                sb.Append("INSERT INTO ");
                sb.Append(dgv.Name + " ( ");

                for (int i = 0; i < cols; i++)
                {
                    if (i < cols - 1)
                    {
                        if (dgv.Columns[i].Visible)
                            sb.Append(dgv.Columns[i].HeaderText + ",");
                    }
                    else
                    {
                        if (dgv.Columns[i].Visible)
                            sb.Append(dgv.Columns[i].HeaderText + ") values (");
                    }
                }

                for (int i = 0; i < cols; i++)
                {
                    if (i < cols - 1)
                    {
                        if (dgv.Columns[i].Visible)
                            sb.Append("@" + dgv.Columns[i].HeaderText + ",");
                    }
                    else
                    {
                        if (dgv.Columns[i].Visible)
                            sb.Append("@" + dgv.Columns[i].HeaderText + ")");
                    }
                }
                #endregion


                //建立插入动作的Command
                objCmd.CommandText = sb.ToString();
                OleDbParameterCollection param = objCmd.Parameters;

               

                //遍历DataTable将数据插入新建的Excel文件中
                foreach (Object obj in os)
                {
                    for (int i = 0; i < cols; i++)
                    {
                        if (dgv.Columns[i].Visible)
                        {
                            OleDbParameter oParam = new OleDbParameter("@" + dgv.Columns[i].HeaderText, OleDbType.VarChar);
                            Type t = obj.GetType();
                            oParam.Value = t.GetProperty(dgv.Columns[i].DataPropertyName).GetValue(obj, null);
                            param.Add(oParam);
                        }
                    }
                    objCmd.ExecuteNonQuery();
                }

                return "";
            }//end using
        }
    }//end class
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!