10

我正在使用 VS2010 + Office Interop 2007 尝试从 5-6 页的 Excel 电子表格中获取一些特定的电子表格名称。我所做的只是将我需要的那几个电子表格保存在制表符分隔的文本文件中以供进一步处理。所以对于我得到的三个电子表格名称,每个都有自己的制表符分隔的文本文件。

我可以通过 Interop 将文件保存为制表符分隔,但前提是我知道给定的页面名称是什么。我被告知每个页面名称不会遵循严格的命名约定,但在查找所需名称时,我可以考虑多个名称,例如“RCP”、“rcp”、“收件人”等。

我的问题是,我可以在某种索引中获取所有电子表格页面名称,以便我可以遍历它们并尝试找到我需要的三个名称吗?这比尝试通过 bajillion try/catch 获取“RCP”、“rcp”、“Recipient”页面要好得多。

我很接近,因为我可以通过以下方式获取 Excel 电子表格中的 COUNT 页:

Excel.Application excelApp = new Excel.Application();  // Creates a new Excel Application
excelApp.Visible = true;  // Makes Excel visible to the user.           
// The following code opens an existing workbook
string workbookPath = path;
Excel.Workbook excelWorkbook = null;
try
{
    excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
    false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true,
    false, 0, true, false, false);
}
catch
{
    //Create a new workbook if the existing workbook failed to open.
    excelWorkbook = excelApp.Workbooks.Add();
}
// The following gets the Worksheets collection
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
Console.WriteLine(excelSheets.Count.ToString()); //dat count

感谢您的时间。

4

1 回答 1

16
foreach ( Worksheet worksheet in excelWorkbook.Worksheets )
{
   MessageBox.Show( worksheet.Name );
}

您可以使用字典:

Dictionary<string, Worksheet> dict = new Dictionary<string, Worksheet>();
foreach ( Worksheet worksheet in excelWorkbook.Worksheets )
{
   dict.Add( worksheet.Name, worksheet );
}
// accessing the desired worksheet in the dictionary
MessageBox.Show( dict[ "Sheet1" ].Name );
于 2013-09-13T13:56:42.187 回答