Generating Excel Files in C#

| 21 Comments

I have been investigating several ways of generating files suitable for use in Excel from a C# application.

As with most problems, there is more than one way to crack a nut. Various examples on the web show how to generate formatted sheets in Excel, either by controlling Excel from a C# application or by transforming XML data. The XML transformation has the disadvantage that is limits your clients to the most recent versions of Excel, whereas dire manipulation of Excel requires that you have it installed on the server. You also have to be very careful not to leave instances of Excel running in the background, eventually grinding your server to a halt.

This article provides a demonstration of a very simple method to generate a file that will load into Excel. It is a bit of a hack that I used from a java platform a few years ago, but it works if all you need is a simple data export (with less than 65536 rows). All you do is set the response stream to the mime type "application/vnd.ms-excel" and then pass a tab delimted set of data with new lines at the end of each row.

Below is a sample code snippet showing a method to generate a simple set of data that will load into Excel (should work with most versions including Excel 95 and above). The version below also highlights how to request that the browser treats the file as a download and forces the user to save to disk rather than load in the browser. This also has the advantage that the filename is easily controlled.

/// <summary>
/// Demo class showing how to generate an Excel Attachment
/// </summary>
public class XLWriter
{

  public static void Write(HttpResponse response)
  {

    // make sure nothing is in response stream
    response.Clear();
    response.Charset = "";

    // set MIME type to be Excel file.
    response.ContentType = "application/vnd.ms-excel";

    // add a header to response to force download (specifying filename)
    response.AddHeader("Content-Disposition""attachment; filename=\"MyFile.xls\"");

    // Send the data. Tab delimited, with newlines.
    response.Write("Col1\tCol2\tCol3\tCol4\n");

    response.Write("Data 1\tData 2\tData 3\tData 4\n");
    response.Write("Data 1\tData 2\tData 3\tData 4\n");
    response.Write("Data 1\tData 2\tData 3\tData 4\n");
    response.Write("Data 1\tData 2\tData 3\tData 4\n");

    // Close response stream.
    response.End();

  }

}

21 Comments

Why not just output a comma-seperate-values file?

Column 1, Column 2
Row 1, Row 2

...etc.

I wanted the file generated to load into excel and appear to the user like it was a native excel file. A CSV formatted file cannot be saved with the XLS extension (it needs to be CSV).

Our ActiveReports for .NET product (http://www.datadynamics.com) includes a component we call SpreadBuilder that provides a full API for creating binary excel files. If our customers continue to show interest in the product, we may improve this component even further in the future. Of course, ActiveReports can also export any of your reports to Excel automatically.

...and ActiveReports for .NET can be obtained for the sum of.... ;-)

Don't know ActiveReports price, but ExcelLite .NET component (http://www.gemboxsoftware.com/ExcelLite.htm) does the same and costs 160 EUR (~$190). You pay per developer; server or client deployment is royalty free.

Hi How can write the percentage sign % into excel using C# . Please respond

Hi,

How can I implement and use this xmlwriter class? I copy it to XMLWriter.cs but httpresponse gives error? I'm a beginner to c# and it would be really good if you help me. Thanks

Bibi,

If you post the error that may help. My guess is that you need the appropraite "using" statement at the top of the class. Also - the class is called XLWriter, XMLWriter.

Cheers,

Martin.

hi all...i have an excel image button when I click it will take the data from my page and download it as an excel file. When i drag and drop/or save it as a .txt file it shows all the crazy html/xml codes. I just want it to display as tab delimited contents. I am having very difficulty. can anyone help? thanks,
hafiz (guile786@aol.com)

Hi, I am not able to read data from excel cells if it contains errors. When the cell has data which has been converted from number to text, a green triangle appears on top left of the cell. It is then that the data reader reads a null value from that field. Using data set made no difference neither did disabling the background error checking of excel through code. Please help!!!

Hello .
Thanks about your sample code
this code is very well

Any tips on how to do simple formatting on the cells? Such as Bold and Italics?

Dear sir..
I am using Windows application.
i want to create Excel file, rename the Sheets and i want to add sheets...

Hey thnx......
This is great good stuff..
Only if you could have added how can one format the cell it would have been excellent

Neways a great help..

The type or namespace name 'HttpResponse' could not be found (are you missing a using directive or an assembly reference?)


This is the error that i encountered. What is the appropriate using statement that i'm missing here.

Thanks and regards
Akhil.

I need to format my Excel report which is being generated through C#. Please let me know how to format each cell, if i have a given format.

Also i want thatthe user should get a prompt or dialouge box to savethe excel. Please let me know how thse 2 functionality can be achieved.

Please can someone help me to do the export to excel but into differetn sheets.

Thanks for help
Joe Way

Hi
Can anyone tell how to remove '1' from excel work sheetname..
For eg: I want the worksheet name as 'project', not 'project 1'

thanks for your code but how can i create second worksheet from this code???????????????????

Leave a comment

Archives

Creative Commons License
This blog is licensed under a Creative Commons License.