Yes, your code is missing something. If you run your code multiple times, this is what you will get in task manager:
http://www.prairiefyre.com/KB/Uploads/Images/excelprocesses.jpg
You end up running several
EXCEL.EXE in Task Manager.
So, this is what you can do:
Each process running in Windows will be assigned a
Process ID. Capture the Process ID of the excel that you are running, then kill it when you have done your job.
Making the variable like this won't kill the process:
oXL = null;
This is the sample codes:
using System.Diagnostics;
Create a Dictionary at top level of your class:
Dictionary<int,int> dicExcel = Dictionary(int,int>();
int MyExcelProcessId = 0;
Before you start creating an instance of
Microsoft.Office.Interop.Excel
object, you check for existing excel that are currently running:
private void WriteExcel()
{
CheckForExistingExcellProcesses();
oXL = new Microsoft.Office.Interop.Excel.Application();
}
void CheckForExistingExcellProcesses()
{
Process[] AllProcesses = Process.GetProcessesByName("excel");
foreach (Process ExcelProcess in AllProcesses)
{
dicExcel.Add(ExcelProcess.Id, 1);
}
}
After creating your instance of
Microsoft.Office.Interop.Excel
object, capture the process ID:
private void WriteExcel()
{
oXL = new Microsoft.Office.Interop.Excel.Application();
GetTheExcelProcessIdThatUsedByThisInstance();
}
void GetTheExcelProcessIdThatUsedByThisInstance()
{
Process[] AllProcesses = Process.GetProcessesByName("excel");
foreach (Process ExcelProcess in AllProcesses)
{
if (dicExcel == null)
return;
if (dicExcel.ContainsKey(ExcelProcess.Id) == false)
{
MyExcelProcessId = ExcelProcess.Id;
break;
}
}
AllProcesses = null;
}
After you have done everything with your Excel,
kill the process at the end:
void KillExcelProcessThatUsedByThisInstance()
{
Process[] AllProcesses = Process.GetProcessesByName("excel");
foreach (Process ExcelProcess in AllProcesses)
{
if (ExcelProcess.Id == MyExcelProcessId)
{
ExcelProcess.Kill();
break;
}
}
AllProcesses = null;
}
The final code will be something like this:
private void button3_Click(object sender, EventArgs e)
{
CheckForExistingExcellProcesses();
oXL = new Microsoft.Office.Interop.Excel.Application();
GetTheExcelProcessIdThatUsedByThisInstance();
KillExcelProcessThatUsedByThisInstance();
}
I was once faced the same problem as you. Some programmers around the world have shared the knowledge to me, and now my turn to share this.
I have written a freeware based on this, you may want to have a look:
The Source Code of Simple Microsoft Excel Documents Converter[
^]