相关疑难解决方法(0)

如何正确清理Excel互操作对象?

我在C#(ApplicationClass)中使用Excel互操作,并在我的finally子句中放置了以下代码:

while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }
excelSheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Run Code Online (Sandbox Code Playgroud)

虽然这种工作,Excel.exe即使我关闭Excel后,该过程仍然在后台.只有在我的应用程序手动关闭后才会发布.

我做错了什么,或者是否有其他方法可以确保互操作对象得到妥善处理?

c# excel interop com-interop

733
推荐指数
20
解决办法
30万
查看次数

Interop进程后无法关闭Excel.exe

我遇到了Excel Interop的问题.

即使我重新发布实例,Excel.exe也不会关闭.

这是我的代码:

using xl = Microsoft.Office.Interop.Excel;


xl.Application excel = new xl.Application();
excel.Visible = true;
excel.ScreenUpdating = false;
if (wordFile.Contains(".csv") || wordFile.Contains(".xls"))
{
   //typeExcel become a string of the document name
   string typeExcel = wordFile.ToString();
   xl.Workbook workbook = excel.Workbooks.Open(typeExcel,
                                                oMissing,  oMissing,  oMissing,  oMissing,
                                                oMissing,  oMissing,  oMissing,  oMissing,
                                                oMissing,  oMissing,  oMissing,  oMissing,
                                                oMissing,  oMissing);
   object outputFileName = null;
   if (wordFile.Contains(".xls"))
   {
     outputFileName = wordFile.Replace(".xls", ".pdf");
   }
   else if (wordFile.Contains(".csv"))
   {
     outputFileName = wordFile.Replace(".csv", ".pdf");
   }

   workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, outputFileName, 
                                 XlFixedFormatQuality.xlQualityStandard, oMissing,
                                 oMissing, …
Run Code Online (Sandbox Code Playgroud)

c# excel-interop winforms

28
推荐指数
6
解决办法
5万
查看次数

在C#中安全地处理Excel互操作对象?

我正在开发一个winforms c#visual studio 2008应用程序.该应用程序与excel文件对话,我正在使用Microsoft.Office.Interop.Excel;这个.

我想知道即使出现错误,如何确保对象被释放?

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    string myBigFile="";
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
    if (result == DialogResult.OK) // Test result.
        myBigFile=openFileDialog1.FileName;

    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    Excel.Range range;

    string str;
    int rCnt = 0;
    int cCnt = 0;

    xlApp = new Excel.ApplicationClass();
    xlWorkBook = xlApp.Workbooks.Open(myBigFile, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 1, 0);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); …
Run Code Online (Sandbox Code Playgroud)

c# excel interop dispose excel-interop

14
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×3

excel ×2

excel-interop ×2

interop ×2

com-interop ×1

dispose ×1

winforms ×1