-1

I usually use Response.Write to export my reports to an excel file.

E.g

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyFile.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
Response.Write("<table>");
Response.Write("<tr>");
Response.Write("<td>");
Response.Write("Hello");
Response.Write("</td>");
Response.Write("</tr>");
Response.Write("</table>");
Response.End();

Now i want to export an excel file with multiple sheets. How can i accomplish this?

chosenOne Thabs
  • 1,480
  • 3
  • 21
  • 39
  • 1
    How does that code relate to creating an Excel file? – Widor Apr 20 '12 at 10:23
  • I'm having a table on my webpage with a list of users. Each user has his/her own profile(name,surname,age etc). So i want to export profiles for the users that are shown in my table. So this means if i'm having user(A,B,C), then in my exported excel file i'm gonna have sheet(A,B,C) and each sheet contains a profile for a specific user. – chosenOne Thabs Apr 20 '12 at 11:03
  • You should write that in question, your code does not export to excel, it writes HTML table and send wrong content type in request. – Antonio Bakula Apr 20 '12 at 11:28
  • Okay. This code you see here is executed by my asp.net button(sever side button). So if i click this button, then i will see a pop up dialog asking me to select a location where i want to save my file. – chosenOne Thabs Apr 20 '12 at 11:37
  • Yes I am aware of that, there is a ASP.NET tag. There will be no dialog or anything similar, I will update my answer with example of exporting DataTable in excel with EPPlus – Antonio Bakula Apr 20 '12 at 11:48

1 Answers1

2

Tehnically speaking this is not export to excel, but you send a html with a wrong headers to trick browser to open this content with excel.

Better use NPOI (xls) or / and EPPlus (xlsx) and fully control your excel export and then you can create new sheets and more.

Update: In this SO answer you can see example of ashx handler that returns excel file that is created from DataTable :

C# create/modify/read .xlsx files

Community
  • 1
  • 1
Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102
  • 1
    Okay thank you. I just hope that this libraries won't slow my down my web server, because i have already tried Microsoft's API library (Microsoft.Office.Interop.Excel) and i heard a lot of guys criticizing it, saying it slows down the web server. – chosenOne Thabs Apr 20 '12 at 11:46
  • They were right, Interop to excel on server is even not supported by MS, these are pure c# libraries and quite fast. – Antonio Bakula Apr 20 '12 at 11:53
  • Okay. I liked your first explanation("tricking the browser") was quite clear. Thanks a lot. – chosenOne Thabs Apr 20 '12 at 11:59