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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15021237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:48:57  来源:igfitidea点击:

How to check if the Worksheet already exist in Interop

c#excelexcel-interop

提问by Anand S

I want to check if the sheet exists before creating it.

我想在创建之前检查工作表是否存在。

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();

采纳答案by John Willemse

Create a loop like this:

创建一个这样的循环:

// 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
}

I'm not into Office Interop very much, but come to think of it, you could also try the following, much shorter way:

我不太喜欢 Office Interop,但仔细想想,你也可以尝试以下更短的方法:

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

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

But I'm not sure if that would simply return nullwithout throwing an exception; you would have to try the second method for yourself.

但我不确定这是否会简单地返回null而不抛出异常;你必须自己尝试第二种方法。

回答by Steven C. Britton

Why not just do this:

为什么不这样做:

try {

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

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

    // Create the worksheet
 }

 wks.Select();

The other way avoids throwing and catching exceptions, and certainly it's a legitimate answer, but I found this and wanted to put this up as an alternative.

另一种方式避免抛出和捕获异常,当然这是一个合理的答案,但我发现了这个并想把它作为替代方案。

回答by Charles HETIER

This extension method returns the worksheet if it exists, null otherwise:

此扩展方法返回工作表(如果存在),否则返回 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);
    }
}

The linq method .Any() can be used instead of FirstOrDefault to check whether the worksheet exists as well...

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