引入命名空间
using System.Data;
using System.Data.OleDb;
对于Office2007和Office2003,连接字符串不同,自行添加一个DataGrid控件,代码如下:
private void importExcelToDataSet(string path)
{
//Office 2007 连接字符串
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + @path + ";" + "Extended Properties=Excel 12.0;";
//Office 98-2003 连接字符串
//string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + @path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
DataTable table1 = new DataTable();
myCommand.Fill(table1);
//DataGrid控件,填充table1内容
dataGrid1.DataSource = table1;
}