使用C#Interop从Excel获取明文中的所有工作表名称? [英] Get all worksheet names in plaintext from Excel with C# Interop?
问题描述
我使用VS2010 + Office Interop 2007尝试从Excel电子表格中获取一些具有5-6页的特定电子表格名称。所有我正在做的是在分页文本文件中保存我需要的几个电子表格以供进一步处理。因此,对于我获得的三个电子表格名称,每个电子表格将具有自己的制表符分隔文本文件。
I'm using VS2010 + Office Interop 2007 to attempt to get a few specific spreadsheet names from an Excel spreadsheet with 5-6 pages. All I am doing from there is saving those few spreadsheets I need in a tab delimited text file for further processing. So for the three spreadsheet names I get, each one will have its own tab delimited text file.
我可以通过Interop将文件保存为制表符分隔,但这是假设我知道给定的页面名称是什么。我已经被告知,每个页面名称都不会遵循严格的命名约定,但是当查找所需的名称时,我可以考虑多个名称,如RCP,rcp,收件人等。
I can save a file as tab delimited just fine through Interop, but that's assuming I know what the given page name is. I have been informed that each page name will not follow a strict naming convention, but I can account for multiple names like "RCP", "rcp", "Recipient", etc when looking for a desired name.
我的问题是,我可以在某种索引中获取所有电子表格页面名称,以便我可以遍历它们,并尝试找到我需要的三个名称比起试图抓住RCP,rcp,收件人页面,通过一个bajillion try / catches来获取更好的价格。
My question is, can I get all spreadsheet page names in some sort of index so I may iterate through them and try to find the three names I need? That would be so much nicer than trying to grab "RCP", "rcp", "Recipient" pages via a bajillion try/catches.
我很亲近,因为我可以通过以下方式获得Excel电子表格中的COUNT页:
I'm close, because I can get the COUNT of pages in an Excel spreadsheet via the following:
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
谢谢你的时间。
推荐答案
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 );
这篇关于使用C#Interop从Excel获取明文中的所有工作表名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!