Click here to Skip to main content
Click here to Skip to main content

Generating Excel (XML Spreadsheet) in C#

By , 9 Oct 2005
 

Recently, I was working on a web based report in ASP.NET. The report had to be generated in MS Excel format and the data was too much. To give you an idea, I had to generate more than 300 worksheets and the file size was more than 5 MB. I tried the Office PIAs but I was not happy with the Excel object. One day while I was playing with Excel trying to save data, I came across an option "XML Spreadsheet(*.xml)" in Office and after some careful observation of the XML code generated by Excel, I decided to generate the XML string using C# and save the content as a .xls file.

The structure of a XML spreadsheet

<Workbook>
    <Styles>
    </Styles>
    <Worksheet ss:Name="Sheet1">
        <Table>
            <Row>
                <Cell>Data</Cell>
                <Cell>Data</Cell>
            </Row>
        </Table> 
        <WorksheetOptions> </WorksheetOptions>
    </Worksheet> 
    <Worksheet ss:Name="Sheet2">
        <Table>
            <Row>
                <Cell>Data</Cell>
                <Cell>Data</Cell>
            </Row>
        </Table> 
    </Worksheet> 
    ......
    ...... 
    ...... 
    ...... 
<Workbook>

Using the code

The Excel header function returns the header of the file.

/// <summary>
/// Creates Excel Header 
/// </summary>
/// <returns>Excel Header Strings</returns>
private string ExcelHeader()

{
    // Excel header
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append("<?xml version=\"1.0\"?>\n");
    sb.Append("<?mso-application progid=\"Excel.Sheet\"?>\n");
    sb.Append(
      "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
    sb.Append("xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
    sb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
    sb.Append("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
    sb.Append("xmlns:html=\"http://www.w3.org/TR/REC-html40\">\n");
    sb.Append(
      "<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
    sb.Append("</DocumentProperties>");
    sb.Append(
      "<ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\n");
    sb.Append("<ProtectStructure>False</ProtectStructure>\n");
    sb.Append("<ProtectWindows>False</ProtectWindows>\n");
    sb.Append("</ExcelWorkbook>\n");
    return sb.ToString(); 
}

The main function to generate Excel worksheets using String Builder:

//First Write the Excel Header
strExcelXml.Append(ExcelHeader());
// Get all the Styles
strExcelXml.Append(ExcelStyles ("styles.config"));

// Create First Worksheet
strExcelXml.Append(WriteFirstWorkSheet());
// Worksheet options Required only one time 
strExcelXml.Append(ExcelWorkSheetOptions()); 

for(int i=1;i<iWorkSheet;i++)
{
    // Create First Worksheet tag
    strExcelXml.Append(
        "<Worksheet ss:Name=\"WorkSheet"+i.ToString()+"\">");
    // Then Table Tag
    strExcelXml.Append("<Table>");
    for(int k=1;k<iRow;k++)
    {
        // Row Tag
        strExcelXml.Append("<tr>");
        for(int j=1;j<iCol;j++)
        {
            // Cell Tags
            strExcelXml.Append("<td>");
            strExcelXml.Append(
              "Sheet"+i.ToString()+"Row"+k.ToString()+"Col"+j.ToString()); 
            strExcelXml.Append("</td>");
        }
        strExcelXml.Append("</tr>");
    }
    strExcelXml.Append("</Table>");
    strExcelXml.Append("</Worksheet>"); 
}
// Close the Workbook tag (in Excel header 
// you can see the Workbook tag)
strExcelXml.Append("</Workbook>\n");

Points of interest

The test application may take more time if there are more than 100 sheets. To improve on this you need to do a lot of string manipulations (concatenation, find and replace). As the final string grows in size, concatenation and find & replace methods start taking time. So you need to be a little careful while dealing with huge reports.

One can generate various styles like bold, italics, hyperlink, column merge etc. in the report. What Excel does is it generates a Style tag at the top of the file and keeps it for future use. A sample of the Style tag is shown below:

<Styles>
    <Style ss:ID="Default" ss:Name="Normal">
        <Alignment ss:Vertical="Bottom"/>
        <Borders/>
        <Font/>
        <Interior/>
        <NumberFormat/>
        <Protection/>
    </Style>
    <Style ss:ID="s27" ss:Name="Hyperlink">
        <Font ss:Color="#0000FF" ss:Underline="Single"/>
    </Style>
    <Style ss:ID="s24">
        <Font x:Family="Swiss" ss:Bold="1"/>
    </Style>
    <Style ss:ID="s25">
        <Font x:Family="Swiss" ss:Italic="1"/>
    </Style>
    <Style ss:ID="s26">
        <Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/>
    </Style>
</Styles>

Conclusion

Using the above methods, we can generate high end Excel files by simply using string manipulations. This gives you freedom from Office PIA's which are heavy, memory hungry and system dependent.

Version history

  • 10th Oct, 2005: Last modified.
  • Upgraded the string concatenation using the StringBuilder class and there is a huge performance enhancement. Please refer to this article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

dekajp
United States United States
Member
Hi I am Jyoti Prakash Deka From Assam/India . Basically I am an Electrical Engg. Currently working for Software Consultancy firm in Bangalore/India.
 
I am working in Microsoft Technologies .NET ,Asp.net,MS Sql server,C#.
 
I can be reached at dekajp@yahoo.com.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionI am not able to open the file in Mac machine. it comes as blank.memberhishhash4 Nov '12 - 19:58 
Any reason why? and how can i achieve this.
 
dasdsd
GeneralMy vote of 1memberlomo745 Sep '12 - 5:23 
horrible. an xml file built from scratch using a stringbuilder. I'm sure you can do better Smile | :)
GeneralWhy don't you write directly to file?!memberibogi15 Feb '11 - 22:46 
Why don't you write directly to file?!
GeneralMy vote of 4membermazmoiz25 Sep '10 - 5:49 
Solved my purpose.
GeneralMy vote of 1memberbouleanu13 Jul '10 - 23:37 
not enought details
GeneralMy vote of 1membertaptaptap19 Aug '09 - 11:14 
It is one of the most terrible code, that I've ever seen.
GeneralRe: My vote of 1memberbrip6 Sep '09 - 20:16 
Totally Agree,
 
There are thousand ways to create more efficient Excel-XML code, few of them could be like create a XSD , use A custom Class for writing xml and so on.
 

you can do better then string concat / string builder.
 

GeneralOpening in Excel without savingmembershyamal17077525 Mar '09 - 11:32 
This is a great piece of code! I was trying to open the XML Spreadsheet directly without saving the file. But I get the xml content dumped on the excel file generated. It doesn't show me in excel format. Any idea what I am missing? My code is something like this
 
System.IO.MemoryStream msExcelMS = null;
string strExcelXml = objExport.GenerateWorkSheetWithSB();
byte[] arrExcelByteData = System.Text.Encoding.Unicode.GetBytes(strExcelXml.ToString());
msExcelMS = new System.IO.MemoryStream(arrExcelByteData);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=" + strExportFilename);
Response.Charset = "";
Response.BinaryWrite(msExcelMS.ToArray());
Response.End();
msExcelMS.Close();
 
TIA
Shyamal Bhowmik
Questiongenerating excel compatible with excel 2000 and excel 2003memberanithasrinath23 Dec '08 - 20:11 
Is there a way to genrate an excel using the programme to generate an excel which will be compatible with both excel 2000 and excel 2003. I used an similar mechanism to generate excel...works fine with excel 2003 but when tried to open with excel 2000 it shows junk value.
Any help would be appreciated.
 
Thanks
AnswerRe: generating excel compatible with excel 2000 and excel 2003 [modified]memberFilipKrnjic8 Jul '09 - 1:34 
Hi,
 
Yes there is a way. You can use GemBox 3rd party .NET Excel component which is compatible with all products that deal with spreadsheet files. Component is free for commercial use if you are working with smaller files.
 
Filip
GemBox.Spreadsheet for .NET - Easily read and write Excel (XLS, XLSX or CSV) files or export to HTML files from your .NET apps.
 
modified on Tuesday, August 25, 2009 10:01 AM

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 10 Oct 2005
Article Copyright 2005 by dekajp
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid