C#根据默认Excel表中的名字是Sheet1读取内容,如果这个Sheet1改变了,我的代码怎么改呢?
下面是写读取Excel的一段代码----------------------------------------------------------------strin...
下面是写读取Excel的一段代码
----------------------------------------------------------------
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + ofd.FileName.ToString() + ";Extended Properties=Excel 8.0";
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = " SELECT * FROM [Sheet1$] ";
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
myDataSet = new DataSet();
myCommand.Fill(myDataSet, "[Sheet1$]");
dataGridView1.DataSource = myDataSet.Tables[0];
myConn.Close();
-----------------------------------------------------------------
这里string strCom = " SELECT * FROM [Sheet1$] ";
Sheet1$这个名字假如变了
比如用户自己改成了 page1
或者用户把内容写在了 Sheet2$ 中
怎么解决这几个问题呢??? 展开
----------------------------------------------------------------
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + ofd.FileName.ToString() + ";Extended Properties=Excel 8.0";
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = " SELECT * FROM [Sheet1$] ";
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
myDataSet = new DataSet();
myCommand.Fill(myDataSet, "[Sheet1$]");
dataGridView1.DataSource = myDataSet.Tables[0];
myConn.Close();
-----------------------------------------------------------------
这里string strCom = " SELECT * FROM [Sheet1$] ";
Sheet1$这个名字假如变了
比如用户自己改成了 page1
或者用户把内容写在了 Sheet2$ 中
怎么解决这几个问题呢??? 展开
1个回答
2013-07-27
展开全部
OleDbConnection conn = new OleDbConnection(sConnectionString);
conn.Open();
DataTable datatable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
foreach (DataRow row in datatable.Rows)
{
tablename = row["table_name"].ToString();
}
string select = "SELECT * FROM [" + datatable.Rows[0]["TABLE_NAME"].ToString() + "]";
datatable.Rows[0]["TABLE_NAME"].ToString() 代表第一个表单,datatable.Rows[1]["TABLE_NAME"].ToString() 代表第二个表单,tablename 是所以表单的集合
conn.Open();
DataTable datatable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
foreach (DataRow row in datatable.Rows)
{
tablename = row["table_name"].ToString();
}
string select = "SELECT * FROM [" + datatable.Rows[0]["TABLE_NAME"].ToString() + "]";
datatable.Rows[0]["TABLE_NAME"].ToString() 代表第一个表单,datatable.Rows[1]["TABLE_NAME"].ToString() 代表第二个表单,tablename 是所以表单的集合
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询