public static DataTable ToDataTable(string filePath)
{
string connStr = "";
string tblName = "tb";
string fileType = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileType)) return null;
if (fileType == ".xls")
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
string sql_F = "Select * FROM [{0}]";
OleDbConnection conn = null;
OleDbDataAdapter da = null;
DataTable dtSheetName = null;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
try
{
// 初始化连接,并打开
conn = new OleDbConnection(connStr);
conn.Open();
// 获取数据源的表定义元数据
string SheetName = "";
dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
// 初始化适配器
da = new OleDbDataAdapter();
for (int i = 0; i < dtSheetName.Rows.Count; i++)
{
SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];
if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$"))
{
continue;
}
da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn);
// DataSet dsItem = new DataSet();
//DataTable dt = da.Fill();
dt.TableName = "xlsTable";
da.Fill(dt);
// da.Fill(dsItem, tblName);
//ds.Tables.Add(dt.Copy());
//ds.Tables.Add(dsItem.Tables[0].Copy());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
// 关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
da.Dispose();
conn.Dispose();
}
}
return dt;
}
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = "xls";
ofd.Filter = "Excel|*.xls;*.xlsx";
ofd.AddExtension = true;
//string strPath;
if (ofd.ShowDialog() == DialogResult.OK)
{
string text = ofd.FileName.ToString();
// string exl=text.Substring(text.LastIndexOf('\\')+1) ;
//string[] er = exl.Split('.');
// ex = ex.Substring(0,text.LastIndexOf('.'));
// MessageBox.Show(text);
// string[] excelName = GetExcelSheetNames(text);
// MessageBox.Show(excelName.Length.ToString());
if (string.Compare(Path.GetExtension(text), ".xls", true) != 0 && string.Compare(Path.GetExtension(text), ".xlsx", true) != 0)
{
MessageBox.Show("Load File Name Error !!");
}
else
{
try
{
/*
string strCon = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'", text);
OleDbConnection Con = new OleDbConnection(strCon);//建立连接
string strSql = "select * from ["+excelName[0]+"$]";//表名的写法也应注意不同,对应的excel表为sheet1,在这里要在其后加美元符号$,并用中括号
OleDbCommand Cmd = new OleDbCommand(strSql, Con);//建立要执行的命令
OleDbDataAdapter da = new OleDbDataAdapter(Cmd);//建立数据适配器 */
// DataSet ds = new DataSet();//新建数据集
// DataSet ds = ToDataTable(text);
DataTable dt = ToDataTable(text);
//da.Fill(ds, "dataExcel");//把数据适配器中的数据读到数据集中的一个表中(此处表名为shyman,可以任取表名)
//指定datagridview1的数据源为数据集ds的第一张表(也就是shyman表),也可以写ds.Table["shyman"]
dgData.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//捕捉异常
}
finally
{
}
}
}