开发者

How to get Worksheet object from textual reference?

开发者 https://www.devze.com 2023-03-24 00:46 出处:网络
I have a name of worksheet in a different workbook. Name looks like this: \'[Book.xlsx]开发者_如何学JAVASheet1\'. How I can get Worksheet object from this name?Try this:

I have a name of worksheet in a different workbook. Name looks like this: '[Book.xlsx]开发者_如何学JAVASheet1'. How I can get Worksheet object from this name?


Try this:

    /// <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];
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消