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

Exporting Data into Excel in Multiple Worksheets

By , 29 Mar 2007
 

Introduction

One thing that all developers come across is putting DataGrid data into an Excel sheet. In this article, I will show you how you can export your DataGrid data to an Excel file.

Exporting DataGrid to Excel

Exporting to Excel is carried out here by dynamically building Excel XML code. The advantage of such an approach is that any number of worksheets can be created. This solves the problem were Excel truncates records after a count of 63000.

Using the Code

A brief description of how to use the code is given below. Use the below function in your web page in your code-behind or in a separate class. The function dynamically generates XML code for Excel. It returns a StringWriter object.

public System.IO.StringWriter ExportToExcelXML(DataSet source)
{
    System.IO.StringWriter excelDoc;
    excelDoc = new System.IO.StringWriter();
    StringBuilder ExcelXML = new StringBuilder();

    ExcelXML.Append("<xml version>\r\n<Workbook ");
    ExcelXML.Append("xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n");
    ExcelXML.Append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n ");
    ExcelXML.Append("xmlns:x=\"urn:schemas- microsoft-com:office:");
    ExcelXML.Append("excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:");
    ExcelXML.Append("office:spreadsheet\">\r\n <Styles>\r\n ");
    ExcelXML.Append("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n ");
    ExcelXML.Append("<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>");
    ExcelXML.Append("\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>");
    ExcelXML.Append("\r\n <Protection/>\r\n </Style>\r\n ");
    ExcelXML.Append("<Style ss:ID=\"BoldColumn\">\r\n <Font ");
    ExcelXML.Append("x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n ");
    ExcelXML.Append("<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat");
    ExcelXML.Append(" ss:Format=\"@\"/>\r\n </Style>\r\n <Style ");
    ExcelXML.Append("ss:ID=\"Decimal\">\r\n <NumberFormat ");
    ExcelXML.Append("ss:Format=\"0.0000\"/>\r\n </Style>\r\n ");
    ExcelXML.Append("<Style ss:ID=\"Integer\">\r\n <NumberFormat ");
    ExcelXML.Append("ss:Format=\"0\"/>\r\n </Style>\r\n <Style ");
    ExcelXML.Append("ss:ID=\"DateLiteral\">\r\n <NumberFormat ");
    ExcelXML.Append("ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n ");
    ExcelXML.Append("<Style ss:ID=\"s28\">\r\n");
    ExcelXML.Append("<Alignment ss:Horizontal=\"Left\" ss:Vertical=\"Top\" 
        ss:ReadingOrder=\"LeftToRight\" ss:WrapText=\"1\"/>\r\n");
    ExcelXML.Append("<Font x:CharSet=\"1\" ss:Size=\"9\" ss:Color=\"#808080\" 
        ss:Underline=\"Single\"/>\r\n");
    ExcelXML.Append("<Interior ss:Color=\"#FFFFFF\" ss:Pattern=\"Solid\"/>
        </Style>\r\n");
    ExcelXML.Append("</Styles>\r\n ");

    string startExcelXML = ExcelXML.ToString();
    const string endExcelXML = "</Workbook>";
    int rowCount = 0;
    int sheetCount = 1;

    excelDoc.Write(startExcelXML);
    excelDoc.Write("<Worksheet ss:Name=\"Report_Sheet" + 
                   sheetCount + "\">");
    excelDoc.Write("<Table>");

    ///Header Part
    // Add any Header for the report
    ///

    excelDoc.Write("<Row ss:AutoFitHeight=\"0\" ss:Height=\"6.75\"/>\r\n");
    excelDoc.Write("<Row><Cell ss:MergeAcross=\"10\" ss:StyleID=\"s34\">
        <Data ss:Type=\"String\">");
    excelDoc.Write("HEADER TEXT");
    excelDoc.Write("</Data></Cell>");
    excelDoc.Write("<Cell ss:MergeAcross=\"1\" ss:StyleID=\"BoldColumn\">
        <Data ss:Type=\"String\">");
    excelDoc.Write("Report Date");
    excelDoc.Write("</Data></Cell>");
    excelDoc.Write("<Cell ss:MergeAcross=\"1\" ss:StyleID=\"DateLiteral\">
                <Data ss:Type=\"String\">");
    excelDoc.Write(GetDate(DateTime.Now.ToShortDateString()));
    excelDoc.Write("</Data></Cell></Row>"); 
    excelDoc.Write("<Row ss:AutoFitHeight=\"0\" ss:Height=\"10\"/>\r\n");

    ///Complete
    excelDoc.Write("<Row>");
    for (int x = 0; x < source.Tables[0].Columns.Count; x++)
    {
        excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
        excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
        excelDoc.Write("</Data></Cell>");
    }
    excelDoc.Write("</Row>");

    foreach (DataRow x in source.Tables[0].Rows)
    {
        rowCount++;

        //if the number of rows is > 63000 create a new page to continue output
        if (rowCount == 63000)
        {
            rowCount = 0;
            sheetCount++;
            excelDoc.Write("</Table>");
            excelDoc.Write(" </Worksheet>");
            excelDoc.Write("<Worksheet ss:Name=\"Report_Sheet" + 
                           sheetCount + "\">");
            excelDoc.Write("<Table>");
            excelDoc.Write("<Row>");

            for (int xi = 0; xi < source.Tables[0].Columns.Count; xi++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\">" + 
                               "<Data ss:Type=\"String\">");
                excelDoc.Write(source.Tables[0].Columns[xi].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
        }
        excelDoc.Write("<Row>"); 

        for (int y = 0; y < source.Tables[0].Columns.Count; y++)
        {
            string XMLstring = x[y].ToString();

            XMLstring = XMLstring.Trim();
            XMLstring = XMLstring.Replace("&", "&");
            XMLstring = XMLstring.Replace(">", ">");
            XMLstring = XMLstring.Replace("<", "<");

            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" + 
                           "<Data ss:Type=\"String\">");
            excelDoc.Write(XMLstring);
            excelDoc.Write("</Data></Cell>");
        }
        excelDoc.Write("</Row>");
    }

    ///Ending Tag
    ///

    excelDoc.Write("<Row ss:Height=\"15\"><Cell ss:HRef=\http://www.sachin" + 
      "kumark.com\ss:MergeAcross=\"2\" ss:StyleID" + 
      "=\"s28\"><Data ss:Type=\"String\">");
    excelDoc.Write("www.sachinkumark.com");
    excelDoc.Write("</Data></Cell></Row>");
    excelDoc.Write("<Row ss:Height=\"15\"><Cell ss:MergeAcross=\"6\" 
            ss:StyleID=\"s28\"><Data ss:Type=\"String\">");
    excelDoc.Write("Copyright © 2007");
    excelDoc.Write("</Data></Cell></Row>"); 

    ///Complete
    excelDoc.Write("</Table>");
    excelDoc.Write(" </Worksheet>");
    excelDoc.Write(endExcelXML);

    return excelDoc;
}
//

The above function can be called from a button event like below:

private void lnkExcel1_Click(object sender, System.EventArgs e)
{
    Response.Buffer = true; 
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Disposition", "attachment; filename=Report.xls");

    this.EnableViewState = false;
    Response.Charset = string.Empty;
    System.IO.StringWriter myTextWriter = new System.IO.StringWriter();
    myTextWriter = ExportToExcelXML(Dataset);
    Response.Write(myTextWriter.ToString());
    Response.End();
}

Provide the DataSet as input to the function. For clarifications, please post in the discussion area below.

Points of Interest

Once you understand the schema, the code can be manipulated to format the rows inside Excel.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

SachinKumarK
Web Developer
India India
Member
No Biography provided

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   
GeneralRC1C1 NotationmemberOliverGu2 Mar '11 - 12:10 
Your code renders well and everything but I have a problem regarding the formulas option. How can I render a column with formulas embedded written in A1 notation and not in R1C1 notation? My user dislikes R1C1 notation; I have tried rendering the formula as a string but in excel it ends up treated as a text and formula is not calculated. Thanks.
GeneralRe: RC1C1 NotationmemberSachinKumarK2 Mar '11 - 22:05 
The method used here for exporting data is by XML, which would mean anything entered is considered as data. So the formula would have to be computed in code before exporting to excel.
GeneralHaving Problem when file is generated the error is asmemberhanmanthreddygurrala15 Dec '09 - 8:56 
probelm come up with following areas during load
 
WorkBook Setting
 
Table
 

 
this file can not be open because of errors.
GeneralGetting Error "System.outofmemory" while preparing excel with a huge data.memberSuvarna A26 Oct '09 - 20:47 
Hi,
 
I m trying to create a report with multiple sheets and for that i have used the code which you have posted here and it works fine for me if the data is less but i have to deal with a huge data and when i try to create a report with more than 50,000 records it throws an exception saying "system,outofmemory".
If u have any idea please share with me.
 

Suvarna
GeneralRe: Getting Error "System.outofmemory" while preparing excel with a huge data.memberSachinKumarK27 Oct '09 - 3:31 
Hi
 
max no of rows in excel is 65536. This code was written basically to handle more than 65536 records. The error ur getting would be from the server/system.
QuestionHow can i create a sheet breakup within the same workbookmemberspeedriser14 Oct '08 - 2:18 
Hi,
 
Can u give me the code to Export two datagrids in my page to two different Sheets within the same Worknook file
AnswerRe: How can i create a sheet breakup within the same workbookmemberSachinKumarK27 Oct '09 - 3:34 
in the code a new sheet is opened when no of rows reach 63000.( u can see an if condition in the code). U can change the if condition to suit ur requirement
Generalmade it by handmemberbigblue19808 Sep '08 - 17:26 
If the excel template is very complicated,what can we do.
GeneralRe: made it by handmemberSachinKumarK16 Sep '08 - 22:10 
As i have written in my article...create a dummy excel that u want to create .. save in xml format. now u can generate the xml schema using code and write to excel. u can send me the file u want to create..i can try to get u the code
GeneralWindows Application codememberWalaza8 Apr '08 - 8:02 
Hi,
Do you have code that does this for a windows application?
 
Mvelo Walaza
Developer
Telkom SA

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 29 Mar 2007
Article Copyright 2007 by SachinKumarK
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid