如何检查Interop中是否已存在工作表

5

在创建表格之前,我想要检查表格是否存在。

using Excel = Microsoft.Office.Interop.Excel;

Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook wb = excel.Workbooks.Open(@"C:\"Example".xlsx");


Excel.Worksheet sh = wb.Sheets.Add();
int count = wb.Sheets.Count;

sh.Name = "Example";
sh.Cells[1, "A"].Value2 = "Example";
sh.Cells[1, "B"].Value2 = "Example"
wb.Close(true);
excel.Quit();
3个回答

16

如果存在工作表,则此扩展方法返回该工作表;否则返回 null:

public static class WorkbookExtensions
{
    public static Excel.Worksheet GetWorksheetByName(this Excel.Workbook workbook, string name)
    {
        return workbook.Worksheets.OfType<Excel.Worksheet>().FirstOrDefault(ws => ws.Name == name);
    }
}

可以使用Linq方法.Any()来代替FirstOrDefault来检查工作表是否存在...


2
我在Lambda表达式中使用了ws.Name.Equals(...)方法,以允许忽略大小写进行比较。 - Asereware

13
创建一个如下所示的循环:
// Keeping track
bool found = false;
// Loop through all worksheets in the workbook
foreach(Excel.Worksheet sheet in wb.Sheets)
{
    // Check the name of the current sheet
    if (sheet.Name == "Example")
    {
        found = true;
        break; // Exit the loop now
    }
}

if (found)
{
    // Reference it by name
    Worksheet mySheet = wb.Sheets["Example"];
}
else
{
    // Create it
}

我不是很了解Office Interop,但是想一想,你也可以尝试以下更短的方法:

Worksheet mySheet;
mySheet = wb.Sheets["NameImLookingFor"];

if (mySheet == null)
    // Create a new sheet

但我不确定这是否只会返回null而不抛出异常;你需要自己尝试第二种方法。


你好,谢谢。如果可能的话,您能告诉我如何选择现有的工作表,以便可以对该工作表进行操作吗? - Anand S
7
谢谢,这解决了我的问题 :) 第二种方法抛出了异常。 - Anand S

5
为什么不这样做:
try {

    Excel.Worksheet wks = wkb.Worksheets["Example"];

 } catch (System.Runtime.InteropServices.COMException) {

    // Create the worksheet
 }

 wks.Select();

另一种方法避免了抛出和捕获异常,这当然是一个合法的答案,但我发现了这个方法,并想把它作为另一种选择提供。

1
非常老的回答,但对于任何遇到这个问题的人来说:捕捉错误是一个非常昂贵的过程,应尽可能避免。 - Tiebe Groosman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接