Thursday, December 25, 2008

How to create excel report in ASP.NET?

In web applications, the final reach is the client browser. So if the requirement says that it should display excel, it mean that client browser should display a file dialog to download/save/cancel the file.

It all depends upon the type of content written to browser. If content type is ”xls” then it is excel document or “doc” mean it is word document etc….
So depending upon the type of file we should set the content type.




Please find below example:-

In this case I am creating a file in server side and transmitting it to client browser

//Transmiting server side created file to browser where client can save or open file from dialog
Response.Clear();
//Setting the content type for response
Response.ContentType = "text/.xls”;
//Adding the attachement file name
Response.AppendHeader("Content-Disposition", "attachment; filename=Sample.xls”);
Response.TransmitFile(filepath);
Response.Flush();
Response.Close();


some times it is not required to create file but just create content and through the content


//Transmiting server side content to browser where client can save or open file from dialog
Response.Clear();
//Setting the content type for response
Response.ContentType = "text/.xls”;
//Adding the attachement file name
Response.AppendHeader("Content-Disposition", "attachment; filename=Sample.xls”);
Response.write(filecontent);
Response.Flush();
Response.Close();


Note :-
So when we say depending upon the content type it writes the required type.
In Excel document we can observe the data is in tabular format.
So to prepare such content, we should html table string in server side according to the display we expect and then write the prepared content to client browser.

No comments: