Duncan Allen said:
I've been using excel within VB.NET applications and I can't get it to close down and remove itself from memory.
I ran into this in c#. I found a ms web page with a great example on
this but can't find it again now.
You are probably creating some objects implicitly by doing something
like xlApp.Workbook.Worksheet and these objects are not getting freed.
Here are some tips :
1) Create all excel ojbects explicitly
2) Quit Excel
3) Use Marshal.ReleaseComObject on all excel objects
4) Set all excel objects to null
The instance of Excel your code creates should then terminate as you
expect it to.
I hope that helps.
Bob
Here is some sample (c# code)
using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Runtime.InteropServices;
private void Export(string saveToName)
{
//Create all Excel objects
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRng;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.DisplayAlerts = false;
oXL.ScreenUpdating = false;
//Make sure Excel is hidden
oXL.Visible = false;
oXL.UserControl = false;
//Open the workbook.
oWB = oXL.Workbooks.Open(excelFileName,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oSheet = (Excel.Worksheet) oWB.Worksheets.get_Item(1);
oSheet.Activate();
//Copy data from data reader to excel
string[] cell = new
string[30]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD"};
int row = 2;
while (dReader.Read())
{
for (int index = 0; index < 30; index++)
{ {
oRng = oSheet.get_Range(cell[index] + row.ToString(),
cell[index] + row.ToString());
if (dReader[index].ToString() == "")
{
oRng.Value2 = "0";
}
else
{
oRng.Value2 = dReader[index].ToString();
}
//Release the range object
Marshal.ReleaseComObject(oRng);
}
row++;
}
//Save the file
object fileName = saveToName;
oWB.SaveAs(fileName,
Excel.XlFileFormat.xlExcel9795,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oXL.Quit();
//Free the remaining excel resources
Marshal.ReleaseComObject(oRng);
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oXL = null;
oWB = null;
oSheet = null;
oRng = null;
}
catch( Exception theException )
{
String errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}