Hi , I'm having a little trouble with exporting my gridview
to Excel using the code below. It appears to work OK, apart from when i come to open the file it tells me that its not in the specified format for the extension, however if ignore it it opens anyway. I'm newish to coding and am not sure of the best approach to get it in to an xl
format properly (the above happens on the live or MO server).
Also on my local VS2012
when i run in debug mode (local host) and click the button, i seem to get the program throw and exception
sender {Text = Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.} object {System.Web.UI.WebControls.Button}
#region Event to Export the table to MS Excel when the export button is clicked
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
try
{
DataTable dt1 = (DataTable)ViewState["dtList"];
if (dt1 == null)
{
throw new Exception("No Records to Export");
}
string Path = "c:\\OrderTrackerExportsFromTP\\CircuitsOrderTrackFor_" + DateTime.Now.ToString("yyyyMMdd Hmmss") + ".xls";
FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1;
DataGrd.DataBind();
DataGrd.RenderControl(htmlWrite);
string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
stringWriter.ToString().Normalize();
vw.Write(stringWriter.ToString());
vw.Flush();
vw.Close();
WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//Push the attachment to the user with the response object from the button click event
public static void WriteAttachment(string FileName, string FileType, string content)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
Response.End();
}
#endregion