簡體   English   中英

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

[英]How to check if the Worksheet already exist in 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();

此擴展方法返回工作表(如果存在),否則返回 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 來檢查工作表是否存在......

創建一個這樣的循環:

// 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而不會引發異常; 你必須自己嘗試第二種方法。

為什么不這樣做:

try {

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

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

    // Create the worksheet
 }

 wks.Select();

另一種方法避免拋出和捕獲異常,當然這是一個合理的答案,但我發現了這一點,並想把它作為替代方案。

在我看來,一個更優雅的解決方案是LINQ本身:

if (xl.Workbook.Worksheets.FirstOrDefault(s => s.Name == sheetname) == null) { xl.Workbook.Worksheets.Add(sheetname); }

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM