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

 

相关文章:

  • 2021-06-17
  • 2021-10-22
  • 2022-12-23
  • 2021-08-23
  • 2021-07-26
  • 2022-12-23
  • 2022-12-23
  • 2022-01-12
猜你喜欢
  • 2021-05-28
  • 2022-12-23
  • 2021-05-17
  • 2021-11-06
  • 2022-12-23
  • 2021-12-29
  • 2021-05-27
相关资源
相似解决方案