Click here to Skip to main content
15,389,584 members
Articles / Productivity Apps and Services / Microsoft Office
Posted 7 Dec 2008

Tagged as


93 bookmarked

Export DataSet to Multiple Excel Sheets

Rate me:
Please Sign up or sign in to vote.
4.80/5 (41 votes)
12 Dec 2008CPOL
Exporting multiple tables in a DataSet to multiple sheets in an Excel file


I was in need of exporting multiple tables in a DataSet to an Excel file with multiple sheets, and I couldn't find anything that actually works. So, I wrote one to help people who might be in the same situation. The complete code in ExcelHelper.cs is shown below.

This only works for Excel 2003 and later versions. If a table in the dataset has more than 65,000 rows, it will break it into multiple sheets for the table with sheet name (tableNameX). replaceXmlChar() function is added to escape XML reserved characters.

Limitations of the Code

It does not handle data tables with more than 256 columns (Excel 2003 column limit), and when data tables have very large rows count, it might throw OutOfMemory exception.

Using the Code

To export a DataSet, just call the ExcelHelper.ToExcel() function as follows:

var ds = new DataSet();
           var dt = new DataTable("TableName For Sheet1");
           dt.Rows.Add("Value1", "Value2");

           var dt2 = new DataTable("TableName For Sheet2");
           dt2.Rows.Add("Value1", "Value2");
           ExcelHelper.ToExcel(ds, "test.xls", Page.Response);

Here is the code that does the exporting:


public class ExcelHelper
    //Row limits older Excel version per sheet
        const int rowLimit = 65000;

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

		</Style>\r\n</Styles>\r\n {0}</Workbook>");
            return sb.ToString();

        private static string replaceXmlChar(string input)
            input = input.Replace("&", "&");
            input = input.Replace("<", "<");
            input = input.Replace(">", ">");
            input = input.Replace("\"", "&quot;");
            input = input.Replace("'", "&apos;");
            return input;

        private static string getWorksheets(DataSet source)
            var sw = new StringWriter();
            if (source == null || source.Tables.Count == 0)
                sw.Write("<Worksheet ss:Name=\"Sheet1\"><Table><Row>

		<Cell  ss:StyleID=\"s62\"><Data ss:Type=\"String\"></Data>
                return sw.ToString();
            foreach (DataTable dt in source.Tables)
                if (dt.Rows.Count == 0)
                    sw.Write("<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) +
			"\"><Table><Row><Cell  ss:StyleID=\"s62\">

			<Data ss:Type=\"String\"></Data></Cell></Row>
                    //write each row data
                    var sheetCount = 0;
                    for (int i = 0; i < dt.Rows.Count; i++)
                        if ((i % rowLimit) == 0)
                            //add close tags for previous sheet of the same data table
                            if ((i / rowLimit) > sheetCount)
                                sheetCount = (i / rowLimit);
                            sw.Write("<Worksheet ss:Name=\"" +
				replaceXmlChar(dt.TableName) +
                                     (((i / rowLimit) == 0) ? "" :
				Convert.ToString(i / rowLimit)) + "\"><Table>");
                            //write column name row
                            foreach (DataColumn dc in dt.Columns)
                                        "<Cell ss:StyleID=\"BoldColumn\">

				<Data ss:Type=\"String\">{0}</Data></Cell>",
                        foreach (DataColumn dc in dt.Columns)
                                    "<Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\">


            return sw.ToString();
        public static string GetExcelXml(DataTable dtInput, string filename)
            var excelTemplate = getWorkbookTemplate();
            var ds = new DataSet();
            var worksheets = getWorksheets(ds);
            var excelXml = string.Format(excelTemplate, worksheets);
            return excelXml;

        public static string GetExcelXml(DataSet dsInput, string filename)
            var excelTemplate = getWorkbookTemplate();
            var worksheets = getWorksheets(dsInput);
            var excelXml = string.Format(excelTemplate, worksheets);
            return excelXml;

        public static void ToExcel
		(DataSet dsInput, string filename, HttpResponse response)
            var excelXml = GetExcelXml(dsInput, filename);
            response.AppendHeader("Content-Type", "application/");
		("Content-disposition", "attachment; filename=" + filename);

        public static void ToExcel
		(DataTable dtInput, string filename, HttpResponse response)
            var ds = new DataSet();
            ToExcel(ds, filename, response);


  • 7th December, 2008: Initial post
  • 8th December, 2008: Source code and article updated
  • 11th December, 2008: Source code and article updated


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


About the Author

Software Developer Oliver Wyman Groups
United States United States
Education: Masters in Applied mathematics

MCP in
MCP in SQL Server 2008 Implementation.

Working Experience In .Net since 2005

Comments and Discussions

PraiseExcellent Work Pin
Member 1492352022-Sep-20 1:42
professionalMember 1492352022-Sep-20 1:42 
QuestionExcellent work! Pin
A118914521-Dec-15 6:51
MemberA118914521-Dec-15 6:51 
QuestionNeed to add images, charts Pin
Arkadeep De3-Nov-15 19:31
professionalArkadeep De3-Nov-15 19:31 
QuestionExport to Excel with Image Pin
King Ravi Kumar 30-Sep-15 21:41
MemberKing Ravi Kumar 30-Sep-15 21:41 
QuestionThanks... :) Pin
aambhi3-Mar-15 4:35
Memberaambhi3-Mar-15 4:35 
AnswerDatetime format issue - resolved Pin
Babuji Godem16-Feb-15 0:37
MemberBabuji Godem16-Feb-15 0:37 
QuestionProbelm with datetime Pin
Babuji Godem15-Feb-15 22:19
MemberBabuji Godem15-Feb-15 22:19 
QuestionSave xls file at directory Pin
Member 841450123-Oct-14 10:56
MemberMember 841450123-Oct-14 10:56 
QuestionSave as Xlsx file Pin
vimalrvs16-Sep-14 19:41
Membervimalrvs16-Sep-14 19:41 
Questionhow can i replace Table1,Table2(Sheet name) to some other value Pin
Jeno M18-Mar-14 1:09
MemberJeno M18-Mar-14 1:09 
QuestionRegarding implementing the sample code Pin
dk deepak16-Oct-13 23:41
Memberdk deepak16-Oct-13 23:41 
QuestionIt's great Pin
Ahmed Mostafa1-Oct-13 20:50
MemberAhmed Mostafa1-Oct-13 20:50 
QuestionExport DataSet to Multiple Excel Sheets Pin
hossein nasirzade31-May-13 21:03
Memberhossein nasirzade31-May-13 21:03 
QuestionThread Exception Pin
noobville21-May-13 3:57
Membernoobville21-May-13 3:57 
Questionjet4.0 Pin
nadersghir28-Jan-13 3:41
Membernadersghir28-Jan-13 3:41 
QuestionHow to store the excel file to Network shared Drive instead of opening on client machine Pin
keyur_parekh25-Oct-12 11:37
Memberkeyur_parekh25-Oct-12 11:37 
QuestionUnable to export if there are 1 lakh records in the dataset Pin
Abhishek K Gohil11-Oct-12 1:51
MemberAbhishek K Gohil11-Oct-12 1:51 
Questionnot in correct format for 2010. Pin
Teenustar10-Oct-12 10:42
MemberTeenustar10-Oct-12 10:42 
QuestionRe: not in correct format for 2010. Pin
vimalrvs16-Sep-14 19:38
Membervimalrvs16-Sep-14 19:38 
GeneralThanks For Share this artical very helpful Pin
sapnapal8-Aug-12 22:29
Membersapnapal8-Aug-12 22:29 
GeneralMy vote of 5 Pin
chus2425-Jun-12 14:43
Memberchus2425-Jun-12 14:43 
Questiondata display in gridview depend on user key to export it? Pin
musiw12-Jun-12 23:11
Membermusiw12-Jun-12 23:11 
QuestionWorks Great...Thanks Pin
Member 3324275-Jun-12 8:29
MemberMember 3324275-Jun-12 8:29 
GeneralNice Pin
sivasankari ts14-May-12 23:28
Membersivasankari ts14-May-12 23:28 
GeneralVote of 5! Pin
mk_ln12-Apr-12 11:07
Membermk_ln12-Apr-12 11:07 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.