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

FirstOrDefaultの代わりにlinqメソッド.Any()を使用して、ワークシートも存在するかどうかを確認できます。

于 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
}

私はOfficeInteropにはあまり興味がありませんが、考えてみると、次のはるかに短い方法を試すこともできます。

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

if (mySheet == null)
    // Create a new sheet

nullしかし、それが例外をスローせずに単に戻るかどうかはわかりません。2番目の方法を自分で試す必要があります。

于 2013-02-22T09:53:47.443 に答える
5

なぜこれをしないのですか?

try {

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

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

    // Create the worksheet
 }

 wks.Select();

もう1つの方法は、例外をスローしてキャッチすることを回避し、確かにそれは正当な答えですが、私はこれを見つけて、代替手段としてこれを提示したいと思いました。

于 2014-05-25T20:49:23.737 に答える