我想创建一个方法来获取工作簿中所有工作表的名称。我的工作簿有7张。如果我想读取并保存工作表名称到变量excelSheets,我会收到9个名字,其中两个名字响应不存在的工作表("列出$"和" TYPAB")
我不明白问题出在哪里?我怎样才能获得现有床单的名称?
public List<string> NamesOfSheets(string filename)
{
string con = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0;HDR=Yes;'";
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
List<string> excelSheets;
try
{
DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
excelSheets = dt.Rows.Cast<DataRow>()
.Select(i => i["TABLE_NAME"].ToString()).ToList();
return excelSheets;
}
catch (Exception)
{
throw new Exception("Failed to get SheetName");
}
}
}
答案 0 :(得分:1)
所以我添加了子句,问题解决了。 :)
public List<string> NamesOfSheets(string filename)
{
string con = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0;HDR=Yes;'";
List<string> excelSheets;
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
try
{
DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
excelSheets = dt.Rows.Cast<DataRow>()
.Where(i => i["TABLE_NAME"].ToString().EndsWith("$") || i["TABLE_NAME"].ToString().EndsWith("$'"))
.Select(i => i["TABLE_NAME"].ToString()).ToList();
return excelSheets;
}
catch (Exception)
{
throw new Exception("Failed to get SheetName");
}
}
}
答案 1 :(得分:0)
为什么不使用Office Interop?
foreach (Excel.Worksheet displayWorksheet in Globals.ThisWorkbook.Worksheets)
{
Debug.WriteLine(displayWorksheet.Name);
}
{{3}}