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

Ana*_*d S 3 c# excel excel-interop

我想在创建之前检查表格是否存在.谢谢你提前

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();
Run Code Online (Sandbox Code Playgroud)

Cha*_*IER 12

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

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

  • 只是我在 lamda 表达式中使用了 ws.Name.Equals(...) 方法来允许与忽略大小写进行比较。 (2认同)

Joh*_*mse 11

创建一个这样的循环:

// 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
}
Run Code Online (Sandbox Code Playgroud)

我不是非常喜欢Office Interop,但是想到它,你也可以尝试以下更短的方式:

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

if (mySheet == null)
    // Create a new sheet
Run Code Online (Sandbox Code Playgroud)

但我不确定这是否会在null没有抛出异常的情况下返回; 你必须自己尝试第二种方法.

  • 谢谢你它解决了我的问题:),第二种方法抛出一个异常 (6认同)

Ste*_*ton 5

为什么不这样做:

try {

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

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

    // Create the worksheet
 }

 wks.Select();
Run Code Online (Sandbox Code Playgroud)

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