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

我想在创build之前检查表单是否存在。谢谢你

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

像这样创build一个循环:

 // 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而不抛出exception; 你将不得不为自己尝试第二种方法。

如果该扩展方法存在,则返回该工作表,否则返回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来检查工作表是否存在以及…

为什么不这样做:

 try { Excel.Worksheet wks = wkb.Worksheets["Example"]; } catch (System.Runtime.InteropServices.COMException) { // Create the worksheet } wks.Select(); 

另一种方式避免抛出和捕捉exception,当然这是一个合理的答案,但我find了这个,并希望把它作为替代。