Reputation: 33
This question has been asked a number of times but still I am not able to find a proper solution to it. I have two questions.
I am creating an excel file, writing data to it and then rendering it to the user for download. I have used microsoft.interop for the same.
The first problem is: I am trying to use a messagebox(javascript) to show how many rows were generated in the excel file after the user has downloaded the excel. This messagebox never shows, however the code is executed. How can i achieve this?
Secondly: After the excel has been created, an excel.exe process keeps running in the task manager, even after i have manually cleaned up the references.
This alert box does not show after the file is rendered.
flag = WriteDatasetToExcel(ds);
if (flag)
{
ClientScript.RegisterClientScriptBlock(GetType(), "Javascript", "<script>alert('Number of rows generated : " + ds.Tables[0].Rows.Count + "')</script>");
}
The relevant code is given
excelApp = new Excel.Application();
excelwrkbook = excelApp.Workbooks.Add(1);
excelwrksheet = (Excel.Worksheet)excelwrkbook.Sheets[1];
excelwrksheet.Name = "Application Data";
after writing data, saving and rendering is done like this:
excelwrkbook.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, false, true, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges, false, Missing.Value, Missing.Value, true);
excelwrkbook.Close(0, 0, 0);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.WriteFile(filepath);
excelApp.Quit();
flag = true;
and now finally the cleanup code:
ReleaseObjects(excelrange);
ReleaseObjects(excelwrksheet);
ReleaseObjects(excelwrkbook);
ReleaseObjects(excelApp);
the releaseobjects function is as follows:
private void ReleaseObjects(Object obj)
{
if (obj != null && Marshal.IsComObject(obj))
{
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) != 0) { }
}
}
Upvotes: 2
Views: 754
Reputation: 3057
First of all let me tell you that working in a web based environment with Microsoft Excel interop is not very efficient.
I use usually use the openXML approach for this needs. here
for your first question: Your response content type is application/vnd.ms-excel hence the browser will not execute any java script from this content. you must identify that the excel has been downloaded or make a prior call to get the rows and return the result in a java script or any other acceptable content type.
for your second question: just don't use it for web environment it was not designed for it.
Upvotes: 1