解决C#使用Microsoft.Office.Interop.Excel操作Excel后进程一直存在的问题

This resolved the issue for me. Your code becomes:

public Excel.Application excelApp = new Excel.Application();
public Excel.Workbooks workbooks;
public Excel.Workbook excelBook;
workbooks = excelApp.Workbooks;
excelBook = workbooks.Add(@"C:/pape.xltx");

  

... 
Excel.Sheets sheets = excelBook.Worksheets; 
Excel.Worksheet excelSheet = (Worksheet)(sheets[1]); excelSheet.DisplayRightToLeft = true;
 Range rng; 
rng = excelSheet.get_Range("C2"); 
rng.Value2 = txtName.Text;

And then release all those objects, (Note: All the com object should be release, othewise the excel process won't be closed.)

System.Runtime.InteropServices.Marshal.ReleaseComObject(rng);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
excelBook .Save();
excelBook .Close(true);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);

I wrap this in a try {} finally {} to ensure everything gets released even if something goes wrong (what could possibly go wrong?) e.g.

public Excel.Application excelApp = null;
public Excel.Workbooks workbooks = null;
...
try
{
    excelApp = new Excel.Application();
    workbooks = excelApp.Workbooks;
    ...
}
finally
{
    ...
    if (workbooks != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
    excelApp.Quit();
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
}
原文地址:https://www.cnblogs.com/Linford-Xu/p/4450472.html