读入Excel中的数据到DataSet

来源:互联网 发布:网上买书的软件 编辑:程序博客网 时间:2024/05/16 17:36
        public static DataSet LoadDataFromExcel(string filePath, string sheetName)        {            string strConn;            strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";Extended Properties=Excel 8.0;";            OleDbConnection conn = new OleDbConnection(strConn);            OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM  [" + sheetName + "$]", strConn);            DataSet myDataSet = new DataSet();            try            {                myCommand.Fill(myDataSet);            }            catch (Exception err)            {                MessageBox.Show("数据绑定Excel失败!失败原因:" + err.Message, "提示信息",                    MessageBoxButtons.OK, MessageBoxIcon.Information);                return null;            }            return myDataSet;        }

 

以上这段代码适用于Excel2007及2010,如果是2003,则需要吧Provider=Microsoft.ACE.OLEDB.12.0改为Provider=Microsoft.Jet.OLEDB.4.0。