码迷,mamicode.com
首页 > Windows程序 > 详细

C# 导入Excel到DataSet中

时间:2014-12-19 14:20:52      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:

class Import
    {

        /// <summary>
        /// 导入Excel到DataSet中
        /// </summary>
        /// <param name="strFileSourse">文件的路径和文件全名,含扩展名</param>
        /// <returns></returns>
        public DataSet ExcelToDataSet(string strFileSourse)
        {
            DataSet ds = new DataSet();
            //Excel数据源(兼容03/10)
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strFileSourse + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
            //连接
            OleDbConnection conn = new OleDbConnection(strConn);
            try
            {
                conn.Open();
                //获取Excel中所有的sheet
                DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                //把Excel中所有的sheet数据读到一个Table中
                for (int i = 0; i < dtSheet.Rows.Count; i++)
                {
                    string strSheetName = dtSheet.Rows[i]["TABLE_NAME"].ToString();
                    OleDbDataAdapter OleDa = new OleDbDataAdapter("select * from [" + strSheetName + "]", conn);
                    OleDa.Fill(ds, "TableName");
                    conn.Close();
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }

            return ds;
        }


    }

C# 导入Excel到DataSet中

标签:

原文地址:http://www.cnblogs.com/anglee/p/4173779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!