读Excel到DataTable

来源:互联网 发布:淘宝ps修图多少钱一张 编辑:程序博客网 时间:2024/06/05 20:55

 //读Excel到DataGridView
        private void RedExcel()
        {
           
string sPath = "F://excel名称.xls";
           
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sPath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";

           
string strSQL = "SELECT * FROM [sheet1$]";
            OleDbConnection excelConnection
= new OleDbConnection(connectionString);
            excelConnection.Open();

            OleDbCommand dbCommand
= new OleDbCommand(strSQL, excelConnection);
            OleDbDataAdapter dataAdapter
= new OleDbDataAdapter(dbCommand);

            DataTable dTable
= new DataTable();

            dataAdapter.Fill(dTable);

            dataGridView1.DataSource
= dTable;

            dTable.Dispose();
            dataAdapter.Dispose();
            dbCommand.Dispose();
            excelConnection.Close();
            excelConnection.Dispose();
        }

原创粉丝点击