Home » excel » c# – How to get Excel Worksheet from sheets when a sheetname has spaces programatically

c# – How to get Excel Worksheet from sheets when a sheetname has spaces programatically

Posted by: admin May 14, 2020 Leave a comment

Questions:

I try to

var tempSheet = wrksheets[sheetName] as Worksheet;  

where wrksheets is of type sheets
sheetName is “sheet name with spaces”

If sheetName has no space, it works fine, but if it has space, I get an exception saying invalid index. I only know the name of work sheet, do not know its index. The only thing I can think of is to loop through sheets and compare name of each sheet with sheetName. Not efficient but is there a better way? thanks

Edit
say sheet name is ‘sheet name with spaces’
When I refer a cell in the sheet say A1, it will be ‘sheet name with spaces’!A1
when I use “‘sheet name with spaces'” in wrksheets[sheetName], I get an invalid index exception
I found the issue is I should use “sheet name with spaces” as sheetName instead of the original sheetname with single quotes.
So I write a function to remove invalid/escape chars in sheet name before getting sheet from wrksheets, then it works fine.

    private string RemoveEscapeCharsFromSheetName(string sheetName)
    {
        //TODO: should remove all chars that are not allowed in Excel Sheet Name
        sheetName = sheetName.Trim(new char[] { ' ', '\'' });
        return sheetName;
    }


        sheet = RemoveEscapeCharsFromSheetName(sheet);
        var tempSheet = wrksheets[sheet] as Worksheet;
How to&Answers:

Surround the worksheet name with quotes.

var tempSheet = wrksheets["\"" + sheetName + "\""] as Worksheet;