when I save the file that is returned by Handler and try to open it I get the following message:<b>"The file you trying to open, 'Users.xls', is in a different format than specified by the file extension. Verify that the file is not corrupt and is from a trusted source before opening the file. Do you want to open the file now?"</b>
How to fix this?
Here the code of the handler.
<code>using System.Web;
using System.Web.Services;
using System.IO;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Text;
namespace WebApplication1
{
public class Handler2 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string query = "SELECT FirstName, LastName, Email, Phone FROM tblUser WHERE IsSubscribed = 1";
// As QueryDataSql = New QueryDataSql(query)
DataTable dt = new DataTable();
GridView gv = new GridView();
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Email");
dt.Columns.Add("Phone");
DataRow dr = dt.NewRow();
dr["FirstName"] = "f";
dr["LastName"] = "l";
dr["Email"] = "e";
dr["Phone"] = "p";
dt.Rows.Add(dr);
gv.DataSource = dt;
ExportGridToExcel(gv, "Users.xls", context);
}
private void ExportGridToExcel(GridView grid, string filename, HttpContext context)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.AllowPaging = false;
grid.AllowSorting = false;
grid.DataBind();
context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.ContentEncoding = Encoding.Unicode;
context.Response.Charset = string.Empty;
context.Response.BinaryWrite(Encoding.Unicode.GetPreamble());
grid.RenderControl(htw);
context.Response.Write(sw.ToString());
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
</code>