gpt4 book ai didi

c# - 使用 Excel OleDb 以工作表顺序获取工作表名称

转载 作者:IT王子 更新时间:2023-10-29 03:35:44 25 4
gpt4 key购买 nike

我正在使用 OleDb 从包含许多工作表的 Excel 工作簿中读取数据。

我需要读取工作表名称,但我需要按照它们在电子表格中定义的顺序进行读取;所以如果我有一个看起来像这样的文件;

|_____|_____|____|____|____|____|____|____|____|
|_____|_____|____|____|____|____|____|____|____|
|_____|_____|____|____|____|____|____|____|____|
\__GERMANY__/\__UK__/\__IRELAND__/

然后我需要得到字典

1="GERMANY", 
2="UK",
3="IRELAND"

我试过使用 OleDbConnection.GetOleDbSchemaTable(),这给了我名称列表,但它按字母顺序对它们进行了排序。 alpha 排序意味着我不知道特定名称对应于哪个工作表编号。所以我明白了;

GERMANY, IRELAND, UK

改变了UKIRELAND的顺序。

我需要对它进行排序的原因是我必须让用户按名称或索引选择一个数据范围;他们可以要求“从德国到爱尔兰的所有数据”或“从表 1 到表 3 的数据”。

任何想法将不胜感激。

如果我可以使用 office 互操作类,这会很简单。不幸的是,我不能,因为互操作类在非交互式环境(例如 Windows 服务和 ASP.NET 站点)中不能可靠地工作,所以我需要使用 OLEDB。

最佳答案

你不能只循环从 0 到 Count of names -1 的工作表吗?这样你应该以正确的顺序得到它们。

编辑

我通过评论注意到,对于使用 Interop 类检索工作表名称存在很多顾虑。因此,这是一个使用 OLEDB 检索它们的示例:

/// <summary>
/// This method retrieves the excel sheet names from
/// an excel workbook.
/// </summary>
/// <param name="excelFile">The excel file.</param>
/// <returns>String[]</returns>
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();
}
}
}

摘自Article在 CodeProject 上。

关于c# - 使用 Excel OleDb 以工作表顺序获取工作表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1164698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com