5

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

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

3 回答 3

14

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

于 2015-06-11T14:51:39.497 回答
13

创建一个这样的循环:

// 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而不抛出异常;您必须自己尝试第二种方法。

于 2013-02-22T09:53:47.443 回答
5

为什么不这样做:

try {

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

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

    // Create the worksheet
 }

 wks.Select();

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

于 2014-05-25T20:49:23.737 回答