Reputation: 766
I am currently working on an application which inserts data into an Excel file and closes it afterwards. The Excel file already exists and is stored inside a directory in the server. Every time I run the application it goes to the directory, opens the Excel file, and inserts the data.
// The codes below are executed after opening the Excel file, inserting data, and saving it.
using xl = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
string report = "Report.XLSX";
object obj = Marshal.GetActiveObject("Excel.Application");
xl.Application application = obj as xl.Application;
xl.Workbooks workbooks = application.Workbooks;
foreach (xl.Workbook workbook in workbooks)
{
if (workbook.Name == report)
{
workbook.Close();
}
}
GC.WaitForPendingFinalizers();
if (workbooks != null)
Marshal.FinalReleaseComObject(workbooks);
Marshal.FinalReleaseComObject(application);
GC.Collect();
The Excel file is closed if it is stored in a local machine (client computer), however if the file is stored in the server it does not. The logs does not show that an exception is thrown which means that the codes ran just fine; it just was not able to close the Excel file. Thanks in advance for the help!
Upvotes: 0
Views: 519
Reputation: 495
Microsoft.Office.Interop.Word.Application WordApp;
Microsoft.Office.Interop.Word.Document WordDoc;
// coding here
WordDoc.Save();
WordApp.NormalTemplate.Saved = true;
WordDoc.Close(true);
WordApp.Quit();
WordDoc = null;
WordApp = null;
(Added null assignments thanks to bugfinder)
This can help, also maybe killing the excel process on the server may help. Careful, this kills all excel process and close all excel files.
Process[] processes = Process.GetProcessesByName("EXCEL");
Console.WriteLine("{0} Word processes", processes.Length);
foreach (var process in processes)
{
process.Kill();
}
Console.WriteLine("All word processes killed!");
Upvotes: 1