Hi,
I recently had this problem. I found a solution from fitting together a lot of other forum posts which I can't remember off the top of my head to credit.
My final stitched together solution will work, and is as follows:
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using System.IO;
namespace ExcelExample
{
class CreateExcelDoc
{
Microsoft.Office.Interop.Excel.Application oXL;
_Workbook oWB;
_Worksheet oSheet;
Range oRng;
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
Hashtable myHashtable = new Hashtable();
public CreateExcelDoc()
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oWB = (_Workbook)(oXL.Workbooks.Add( Type.Missing ));
oSheet = (_Worksheet)oWB.ActiveSheet;
}
public void SaveDocument()
{
try
{
oWB.SaveAs(@"Filename", XlFileFormat.xlWorkbookNormal,
Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close(null, null, null);
oXL.Quit();
KillApplicationProcess(oXL);
}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat( errorMessage, theException.Message );
errorMessage = String.Concat( errorMessage, " Line: " );
errorMessage = String.Concat( errorMessage, theException.Source );
}
}
public static void KillApplicationProcess(Microsoft.Office.Interop.Excel.Application oXL)
{
int hWnd = oXL.Application.Hwnd;
uint processID;
GetWindowThreadProcessId((IntPtr)hWnd, out processID);
Process.GetProcessById((int)processID).Kill();
}
public void AddData(int row, int col, string data)
{
oSheet.Cells[row, col] = data;
}
}
}
Hope that helps :)