简体   繁体   English

如果工作表名称以编程方式包含空格,如何从工作表中获取Excel工作表

[英]How to get Excel Worksheet from sheets when a sheetname has spaces programatically

I try to 我试着

var tempSheet = wrksheets[sheetName] as Worksheet;  

where wrksheets is of type sheets sheetName is "sheet name with spaces" 其中wrksheets属于sheet SheetName是“带有空格的工作表名称”

If sheetName has no space, it works fine, but if it has space, I get an exception saying invalid index. 如果sheetName没有空格,它可以正常工作,但如果它有空格,我会得到一个说无效索引的异常。 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. 我唯一能想到的是循环使用工作表并将每个工作表的名称与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. 编辑说工作表名称是'带有空格的工作表名称'当我将工作表中的单元格称为A1时,它将是'带有空格的工作表名称'!A1,当我在wrksheets [sheetName]中使用“'工作表名称带空格'”时,我得到一个无效的索引异常我发现问题是我应该使用“带有空格的工作表名称”作为sheetName而不是带有单引号的原始工作表名称。
So I write a function to remove invalid/escape chars in sheet name before getting sheet from wrksheets, then it works fine. 所以我在从wrksheets获取工作表之前写了一个函数来删除工作表名称中的无效/转义字符,然后它工作正常。

    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;

使用引号括起工作表名称。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM