Excel Automation C #: How to delete multiple rows?

I have the following code and it does not delete the lines, it asks me to save the current book, but nothing is saved, and EXCEL.EXE continues to work in the task manager:

protected void OpenExcelWorkbook(string fileName)
{
    _app = new Excel.Application();

    if (_book == null)
    {
        _books = _app.Workbooks;
        _book = _books.Open(fileName, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing);
        _sheets = _book.Worksheets;
    }
}

protected void CloseExcelWorkbook()
{
    _book.Save();
    _book.Close(false, Type.Missing, false);
}


protected void NAR(object o)
{
    try
    {
        if (o != null)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
    }
    finally
    {
        o = null;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    OpenExcelWorkbook(@"C:\Book2.xls");
    _sheet = (Excel.Worksheet)_sheets[1];
    _sheet.Select(Type.Missing);

    Excel.Range range = _sheet.get_Range("A1", "A3");            
    range.EntireRow.Delete(Type.Missing);            
    NAR(range);
    NAR(_sheet);
    CloseExcelWorkbook();
    NAR(_book);
    _app.Quit();

    NAR(_app);
}
+3
source share
1 answer

I could not accurately reproduce your problem. However, for the EXCEL.EXE process to complete completely, you need to make sure that you call the method ReleaseComObjecton each individual COM object that you reference.

To do this, you can update your code as follows:

private void button1_Click(object sender, EventArgs e)
{
    OpenExcelWorkbook(@"C:\Book2.xls");
    _sheet = (Excel.Worksheet)_sheets[1];
    _sheet.Select(Type.Missing);

    Excel.Range range = _sheet.get_Range("A1", "A3");
    Excel.Range entireRow = range.EntireRow; // update
    entireRow.Delete(Type.Missing);
    NAR(entireRow); // update
    NAR(range);
    NAR(_sheet);
    NAR(_sheets); // update
    CloseExcelWorkbook();
    NAR(_book);
    NAR(_books); // update
    _app.Quit();

    NAR(_app);

}
+3
source

Source: https://habr.com/ru/post/1761166/


All Articles