2

我正在尝试通过这种方式从列表中的 Excel 文件中获取列数据:

private void Form1_Load(object sender, EventArgs e)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/test.xlsx");
            Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            List<string> FirstColumnValues = new List<string>();
            List<string> SecondColumnValues = new List<string>();

            for (int row=1; row <= rowCount; row++)
            {
                for (int col = 1; col <= colCount; col++)
                {
                    switch (col)
                    {
                        case 1:
                            FirstColumnValues.Add(xlRange.Cells[row, col].Value2.ToString());
                            break;
                        case 2:
                            SecondColumnValues.Add(xlRange.Cells[row, col].Value2.ToString());
                            break;
                    }
                }
            }

            if (FirstColumnValues.Count != 0 && SecondColumnValues.Count != 0)
            {
                xlWorkbook.Close();
                xlApp.Quit();
                MessageBox.Show("Completed");
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);
                Marshal.ReleaseComObject(xlWorkbook);
                Marshal.ReleaseComObject(xlApp);
                xlApp = null;
            }
        }

EXCEL.EXE问题是,即使我已经尝试了所有方法来正确关闭它,该过程也没有关闭。我知道这里发布了很多关于正确关闭 excel 流程的问题。但我不是专业人士,我已经尝试了几乎所有我能做的事情。仍然没有运气。

那么,有人可以告诉我这段代码有什么问题吗?当所有数据都存储在列表中时,如何关闭进程一次?

4

4 回答 4

4

我知道这个问题已经得到解答,但我想我会分享我在尝试解决相同问题时的发现。希望有人会发现这很有用。这是在 vb.net 中,但我确信它可以被翻译。

Dim proc As System.Diagnostics.Process
        For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
            If proc.MainWindowTitle.ToString = "" Then
                proc.Kill()
            End If
        Next

我发现当我通过我的应用程序打开 Excel 文件时,窗口标题为空,因此我没有关闭每个正在运行的 Excel 进程,而是关闭了没有标题的那些。

编辑:

如果您要终止该过程,因为您找不到尚未清理的剩余变量(基本上是您使用两个点设置的任何变量),那么至少杀死正确的 Excel 实例:

[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr hwnd, ref int lpdwProcessId);

...

if (xlApp != null)
{
  GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), ref excelProcessId);

  Process ExcelProc = Process.GetProcessById(excelProcessId);
  if (ExcelProc != null)
  {
    ExcelProc.Kill();
  }

我不提倡杀死进程,你应该用 VSTO Contrib 正确清理,例如:

using (var xlApp = new Microsoft.Office.Interop.Excel.Application().WithComCleanup())
于 2012-11-06T00:08:05.860 回答
1

我以前去过那里。这是一篇真正帮助我解决问题的文章:

http://devcity.net/Articles/239/1/article.aspx

Excel 似乎对终止进程非常固执。您很可能最终会使用 System.Diagnostics.Process 终止进程。

于 2012-09-21T12:12:25.933 回答
1

也许,您可能会考虑使用try{}catch{}finally{}并尝试Marshal.FinalReleaseComObject

不确定你是否看过这篇文章,它也可能会给你一些见解。

于 2012-09-21T12:18:01.727 回答
1

确保您正在运行的 Excel 实例最终终止(即当您的应用程序退出时)的最简单方法是将顶级对象包装在 try/finally 块中。

Excel.Application xlApp;  
try{  
   xlApp = new Excel.Application();  
   ...do some work...  
}  
finally{  
   xlApp.DisableAlerts=True;  
   xlApp.Quit();  
   xlApp.DisableAlerts=False;  
   Marshal.ReleaseComObject(xlApp);  
}  

//If you don't mind having the Excel process kept alive for a while,  
//you don't even have to call ReleaseComObject() on the intermediate objects.  
//The runtime will eventually free the underlying COM objects.  

//If you want to clean up right away, your bookkeeping needs to be more thorough.  
//Every time you access a method or property that returns a runtime callable wrapper  
//(System.__ComObject), you'll need to assign them to a variable  
//and make sure Marshal.ReleaseComObject() is called.  

// More thorough bookkeeping...    
Excel.Application xlApp;  
try{  
   xlApp = new Excel.Application();  

   Excel.Workbooks xlWorkbooks = xlApp.Workbooks;  
   Excel.Workbook xlWorkbook = xlWorkbooks.Open(@"D:/test.xlsx");  
   Excel.Sheets xlSheets = xlWorkbook.Sheets;  
   Excel.Worksheet xlWorksheet = xlSheets[1];  
   Excel.Range xlRange = xlWorksheet.UsedRange;  

   ...inside the loop...  
   Excel.Range xlCell = xlRange.Cells[row, col];  
   FirstColumnValues.Add(xlCell.Value2.ToString());  
   Marshal.ReleaseComObject(xlCell);  

   ...inside the loop...  
   Excel.Range xlCell = xlRange.Cells[row, col];  
   SecondColumnValues.Add(xlCell.Value2.ToString());  
   Marshal.ReleaseComObject(xlCell);  

   ...do more work...  

   ...clean up...  
   Marshal.ReleaseComObject(xlRange);  
   Marshal.ReleaseComObject(xlWorksheet);  
   Marshal.ReleaseComObject(xlSheets);  
   Marshal.ReleaseComObject(xlWorkbook);  
   Marshal.ReleaseComObject(xlWorkbooks);  
}  
finally{  
   xlApp.DisableAlerts=True;  
   xlApp.Quit();  
   xlApp.DisableAlerts=False;  
   Marshal.ReleaseComObject(xlApp);  
}  
于 2013-03-15T23:35:12.517 回答