views:

272

answers:

2

I am trying to export my repeater to excel and here is my code...

    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    string attachment = "attachment; filename=file.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/vnd.ms-excel";
    rpt.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.Flush();
    Response.End();

When I am trying to open file getting this error

The file you are trying to open, 'file.xls', is in a different format than specified 
by   the file extension. Verify that the file is not Corrupted and is from a trusted 
source   before opening the file. Do you want to open the file now?
Yes   No Help option are available

What's wrong in my code or What I have to do resolve this issue. Thanks

+2  A: 

You are setting the content type to application/vnd.ms-excel but you are sending HTML contents in the response stream when you call the RenderContents method. You might need a library to generate Excel files.

Darin Dimitrov
When I click yes option, it is opened fine and showing data properly. I found many articles from internet and found similar implementation. Plz check this article http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
Muhammad Akhtar
A: 

Try wrapping your content into this:

StringBuilder sb = new StringBuilder("");
sb.Append("<HTML xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><HEAD>");
sb.Append("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
sb.Append("<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>");
sb.Append(title);
sb.Append("</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> </HEAD><BODY>");
sb.Append(content);
sb.Append("</BODY></HTML>");
morsanu