[英]C# Excel Interop: how can I “get” a table that is already in a worksheet?
[英]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.