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);
    }
  • 相关阅读:
    函数
    关联子查询
    子查询
    视图(VIEW)
    顺时针打印矩阵
    二叉树的镜像
    树的子结构
    将两个有序链表合并
    反转链表
    输出链表中倒数第k个结点
  • 原文地址:https://www.cnblogs.com/Linford-Xu/p/4450472.html
Copyright © 2011-2022 走看看