我在不同的工作簿中有一个工作表的名称。名称如下所示:'[Book.xlsx] Sheet1'。我如何从这个名字中获取Worksheet对象?
答案 0 :(得分:0)
试试这个:
/// <summary>
/// Get a worksheet by a uniqueSheetIdentifierString like "[WorkbookName]worksheetName".
/// </summary>
/// <param name="uniqueSheetIdentifierString"></param>
/// <returns>A worksheet</returns>
public Worksheet GetWorksheetByUniqueSheetIdentifier(string uniqueSheetIdentifierString)
{
const char OPENING_SQUARE_BRACKET = '[';
const char CLOSING_SQUARE_BRACKET = ']';
//Argument checks
if (string.IsNullOrEmpty(uniqueSheetIdentifierString)) throw new ArgumentNullException("The uniqueSheetIdentifierString must have the format '[WorkbookName]SheetName', but was empty!");
if (!uniqueSheetIdentifierString.StartsWith(OPENING_SQUARE_BRACKET.ToString())) throw new ArgumentException("The uniqueSheetIdentifierString must have the format '[WorkbookName]SheetName', but the opening square bracket could not be found: " + uniqueSheetIdentifierString);
//Try getting position of closing square bracket...
var indexOfClosingSquareBracket = uniqueSheetIdentifierString.IndexOf(CLOSING_SQUARE_BRACKET);
if (indexOfClosingSquareBracket < 2) throw new ArgumentException("The uniqueSheetIdentifierString must have the format '[WorkbookName]SheetName', but the closing square bracket could not be found or is not at a valid position: " + uniqueSheetIdentifierString);
//Extract workbook name and worksheet name out of a string like "[WorkbookName]worksheetName"
var workbookName = uniqueSheetIdentifierString.Substring(1, indexOfClosingSquareBracket - 1);
var worksheetName = uniqueSheetIdentifierString.Substring(indexOfClosingSquareBracket + 1);
//Return the worksheet
return Globals.ThisAddIn.Application.Workbooks[workbookName].Worksheets[worksheetName];
}