编程语言
首页 > 编程语言> > Excel自动化C#:如何删除多行?

Excel自动化C#:如何删除多行?

作者:互联网

我有以下代码,并且不删除行,它要求我保存当前工作簿,但未保存任何内容,并且EXCEL.EXE继续在任务管理器中运行:

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

解决方法:

我无法完全重现您的问题.但是,为了使EXCEL.EXE进程完全终止,您需要确保在所引用的每个COM对象上调用ReleaseComObject方法.

为此,您可以按以下方式更新代码:

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

}

标签:delete-row,c,excel
来源: https://codeday.me/bug/20191209/2097064.html