I want to export DataTable data to excel and download it to a client drive location. My code is as follows:
protected void ExportDatatable()
{
DataTable dt = new DataTable();
string errorMsg = string.Empty;
dt = null;
CnSServer cnsServer = new CnSServer();
string str = string.Empty;
try
{
string query = @"SELECT * FROM Products";
dt = cnsServer.GetShortSaleReport(query, out errorMsg);
Response.ClearContent();
Response.AddHeader("content-disposition", string.Format("attachment;filename=MyExcellData.xls", DateTime.Now.ToString("yyyy-MM-dd")));
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dataColumn in dt.Columns)
{
str += dataColumn.ColumnName + "\t";
}
str += "\n";
int i;
foreach (DataRow dataRow in dt.Rows)
{
str += dataRow["ID"] + "\t";
str += dataRow["ProductCode"] + "\t";
str += dataRow["ProductName"] + "\t";
str += "\n";
}
Response.Write(str);
Response.End();
}
catch (Exception e)
{
errorMsg = e.ToString();
}
return dt;
}
This gives me error message ''unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.' No file is downloaded. But DataTable has data inside it. I have don't find any proper solution in this regard. Any suggestions. Thanks in advance.