zoukankan      html  css  js  c++  java
  • 解决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);
    }
  • 相关阅读:
    sql 将某列转换成一个字符串 for xml path用法
    IAsyncResult 接口异步 和 匿名委托
    存储过程和sql语句的优缺点
    ADO.net中常用的对象有哪些?分别描述一下。
    ASP.Net页面生命周期
    请说明在.net中常用的几种页面间传递参数的方法,并说出他们的优缺点。
    .net常用的传值的方法
    SQL列合并
    程序员的情书!
    程序员的表达!
  • 原文地址:https://www.cnblogs.com/Linford-Xu/p/4450472.html
Copyright © 2011-2022 走看看