读到DataSet里,再DataGridView.dataSource = DataSet就行
给个函数:
//定义ReadExcel函数,用该函数从Excel表中读取数据到datable中。
private DataSet ReadExcel(string strFileName, string sheetName)
{ string strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + strFileName + ";Extended Properties = Excel 8.0";
OleDbConnection oleConnection = new OleDbConnection(strConnection);
try
{
oleConnection.Open();
DataSet dsRead = new DataSet();
OleDbDataAdapter oleAdper = new OleDbDataAdapter(" SELECT * FROM [" + sheetName + "$]", oleConnection);
oleAdper.Fill(dsRead, "result");
return dsRead;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return null;
}
finally
{
oleConnection.Close();
}
}
给个函数:
//定义ReadExcel函数,用该函数从Excel表中读取数据到datable中。
private DataSet ReadExcel(string strFileName, string sheetName)
{ string strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + strFileName + ";Extended Properties = Excel 8.0";
OleDbConnection oleConnection = new OleDbConnection(strConnection);
try
{
oleConnection.Open();
DataSet dsRead = new DataSet();
OleDbDataAdapter oleAdper = new OleDbDataAdapter(" SELECT * FROM [" + sheetName + "$]", oleConnection);
oleAdper.Fill(dsRead, "result");
return dsRead;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return null;
}
finally
{
oleConnection.Close();
}
}
http://blog.csdn.net/chengking/archive/2005/11/29/539514.aspx
{
DataTable myT = ExcelToDataTable("C:/Inetpub/wwwroot/test.xls", "sheet1");
String mystr = myT.Rows[0][0].ToString();
dataGridView1.DataSource = myT; } public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
{
//源的定义
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; //Sql语句
//string strExcel = string.Format("select * from [{0}$]", strSheetName); 这是一种方法
string strExcel = "select * from [sheet1$]"; //定义存放的数据表
DataSet ds = new DataSet(); //连接数据源
OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); //适配到数据源
OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
adapter.Fill(ds, strSheetName); conn.Close(); return ds.Tables[strSheetName];
} }