操作表格类型的见我的博客
http://ksca00130318.blog.163.com/blog/static/100661995201089010450/操作数据表类型的,见以下代码
string strCon = string.Empty;
if (type == 2003)
{
strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + filepath + ";Extended Properties=Excel 8.0";
}
if (type == 2007)
{//filepath为excel表的位置
strCon = " Provider = Microsoft.ACE.OLEDB.12.0 ; Data Source =" + filepath + ";Extended Properties=Excel 12.0";
}
DataSet ds;
int nameIndexCol = -1;
int mobilenumIndexCol = -1;
OleDbConnection conn = new OleDbConnection(strCon);
conn.Open();
//获取第一个工作簿的名称
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string tablename = dt.Rows[0][2].ToString().Replace("'","");//第二列是表名
string sql = "select * from ["+tablename+"]";
OleDbDataAdapter myCommand = new OleDbDataAdapter(sql, strCon);
ds = new DataSet();
myCommand.Fill(ds, "[Sheet1$]");
conn.Close();
DataTable dTable = ds.Tables[0];
for (int j = 0; j < dTable.Columns.Count; j++)
{
string colCap = dTable.Columns[j].Caption;
if (colCap == "姓名")
{
nameIndexCol = j;
if (mobilenumIndexCol != -1)
{
break;
}
}
if (colCap == "手机号")
{
mobilenumIndexCol = j;
if (nameIndexCol != -1)
{
break;
}
}
}
if (mobilenumIndexCol == -1 || nameIndexCol == -1)
{
MessageBox.Show("通讯录格式不正确!\n\r 未找到列标题为(姓名)和(手机号)的列", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
for (int i = 0; i < dTable.Rows.Count; i++)
{
string name = dTable.Rows[i][nameIndexCol].ToString();
string mobilenum = dTable.Rows[i][mobilenumIndexCol].ToString();
}
}
catch (System.Exception ee)
{
MessageBox.Show(ee.Message);
}
}