3

I want to export my string html table to excel. When trying to export and when I click save I get the following exception

The server can not add the header after sending the HTTP headers

This is my html table :

string tab = "<table cellpadding='5' style='border:1px solid black; border-collapse:collapse'>";
tab += "<tr><td style=' border-width:1px;border-style:solid;border-color:black;'>NumClient</td><td style=' border-width:1px;border-style:solid;border-color:black;'>Raison Sociale</td></tr>";
tab += "<tr><td style='border-width:1px;border-style:solid;border-color:black;'>" + NumClient + "</td><td style='border-width:1px;border-style:solid;border-color:black;'>"
+ Rs + "</td><td style='border-width:1px;border-style:solid;border-color:black;text-align:right;'> </td></tr>";
tab += "</table>";

This is Controller code :

 Response.ClearContent();   
 Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat.csv");
 Response.ContentType = "text/csv";
 Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
 Response.Write(tab);
 Response.End(); 

And when I click continue I get an excel file that contains html code:

<table cellpadding='5' style='border:1px solid black; border-collapse:collapse'>";
tab += "<tr><td style=' border-width:1px;border-style:solid;border-color:black;'>NumClient</td><td style=' border-width:1px;border-style:solid;border-color:black;'>Raison Sociale</td></tr>

Does anyone have a solution for this?

Sarra
  • 99
  • 1
  • 2
  • 14
  • 1
    The content type is incorrect. You might want to change it to application/excel and use Reliquat.xslx as file name – Hatjhie May 20 '16 at 09:09
  • thank you Hatjhie but I got the same error – Sarra May 20 '16 at 09:21
  • Alright. I think the posted reply below would be able to answer your question. You could give it a try. – Hatjhie May 20 '16 at 09:32
  • 1
    Change your code to: Response.ClearContent(); Response.ClearHeaders(); Response.BufferOutput = true; Response.ContentType = "application/excel"; Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat.xslx"); Response.Write(tab); Response.Flush(); Response.Close(); Response.End(); – Hatjhie May 20 '16 at 09:34
  • 1
    Don't use Response.End() http://stackoverflow.com/questions/1087777/is-response-end-considered-harmful – StuperUser May 20 '16 at 09:59

1 Answers1

1

You might want to use the codes below. Hopefully, it works.

Response.ClearContent(); 
Response.ClearHeaders(); 
Response.BufferOutput = true; 
Response.ContentType = "application/excel"; 
Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat.xslx"); 
Response.Write(tab); 
Response.Flush(); 
Response.Close(); 
Response.End();

From here: http://www.codescratcher.com/asp-net/export-html-excel-asp-net/

chrki
  • 6,143
  • 6
  • 35
  • 55
Jernej Pirc
  • 504
  • 1
  • 4
  • 13