导入excel文件到datagridview
private DataSet ImportExcel(string filename, string sheet) //自定义函数
{
DataSet ds = new DataSet();
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=0\";Data Source=" + filename))
{
conn.Open();
string strGetDataFromExcel = "SELECT * FROM ["+sheet+"$] "; //此处的$不可缺少
OleDbCommand oleDbCmdExcel = new OleDbCommand(strGetDataFromExcel, conn);
OleDbDataAdapter da = new OleDbDataAdapter(oleDbCmdExcel);
DataTable FromExcel = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Columns, new object[] { null, null, sheet, null });
da.Fill(ds);
conn.Close();
}
return ds;
}
private void button1_Click(object sender, EventArgs e)
{
string filePath;
static string file;
DataSet ds = new DataSet();
ds = ImportExcel(filePath, file);//调用函数
DataTable dt = ds.Tables["Table"];
}
private DataSet ImportExcel(string filename, string sheet) //自定义函数
{
DataSet ds = new DataSet();
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=0\";Data Source=" + filename))
{
conn.Open();
string strGetDataFromExcel = "SELECT * FROM ["+sheet+"$] "; //此处的$不可缺少
OleDbCommand oleDbCmdExcel = new OleDbCommand(strGetDataFromExcel, conn);
OleDbDataAdapter da = new OleDbDataAdapter(oleDbCmdExcel);
DataTable FromExcel = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Columns, new object[] { null, null, sheet, null });
da.Fill(ds);
conn.Close();
}
return ds;
}
private void button1_Click(object sender, EventArgs e)
{
string filePath;
static string file;
DataSet ds = new DataSet();
ds = ImportExcel(filePath, file);//调用函数
DataTable dt = ds.Tables["Table"];
}