怎么读取excel文件中的所有sheet名称?

programmeraaron 2004-10-28 11:54:28
DataSet ds = new DataSet();
OleDbDataAdapter ad;
string strDbPath = strExcelFilePath;
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelFilePath + ";Extended Properties=Excel 8.0;";
OleDbConnection Conn = new OleDbConnection(strConn);
Conn.Open();
string strSQL = "SELECT * FROM [sheet1$]";
ad = new OleDbDataAdapter(strSQL, Conn);
ad.Fill(ds);
Conn.Close();
Conn.Dispose();
return ds;

这是我读取“sheet1”时用的,如何得到当前excel文件中的所有sheet?
...全文
321 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
孟子E章 2004-10-28
  • 打赏
  • 举报
回复
也可以

private String[] GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;

try
{
// Connection String. Change the excel file to the file you
// will search.
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(connString);
// Open connection with the database.
objConn.Open();
// Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

if(dt == null)
{
return null;
}

String[] excelSheets = new String[dt.Rows.Count];
int i = 0;

// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}

// Loop through all of the sheets if you want too...
for(int j=0; j < excelSheets.Length; j++)
{
// Query each excel sheet.
}

return excelSheets;
}
catch(Exception ex)
{
return null;
}
finally
{
// Clean up.
if(objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if(dt != null)
{
dt.Dispose();
}
}
}
孟子E章 2004-10-28
  • 打赏
  • 举报
回复
int totalSheets = ThisWorkbook.Sheets.Count;
for(int i=0;i<totalSheets;i++)
Response.Write(ThisWorkbook.Sheets[i].Name);
cocoguo 2004-10-28
  • 打赏
  • 举报
回复
bConnection.Open();
DataTable dt=bConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"TABLE"});
foreach(DataRow dr in dt.Rows)
{
MessageBox.Show(dr["TABLE_NAME"].ToString());
}

62,047

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧