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

Export a DataSet to Microsoft Excel without the use of COM objects

, 28 May 2005
Rate this:
Please Sign up or sign in to vote.
A simple function that writes a DataSet to a Microsoft Excel document.


This function takes in a DataSet and file name and writes the DataSet to an Excel worksheet. The code is pretty straightforward. Great thing about this function is that, it's technically an XML file that is saved as an XLS file. So it can be used as either file format. No more leading zero truncation on numbers that look like strings. Example, if you made a tab delimited file and put a field such as "00036" (a field that looks like a number but should be regarded as a string), MS Excel would truncate the leading zeros... This problem is solved with this method.

Here is the code:

public static void exportToExcel(DataSet source, string fileName)


    System.IO.StreamWriter excelDoc;

    excelDoc = new System.IO.StreamWriter(fileName);
    const string startExcelXML = "<xml version>\r\n<Workbook " + 
          "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" + 
          " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " + 
          "xmlns:x=\"urn:schemas-    microsoft-com:office:" + 
          "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" + 
          "office:spreadsheet\">\r\n <Styles>\r\n " + 
          "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " + 
          "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" + 
          "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" + 
          "\r\n <Protection/>\r\n </Style>\r\n " + 
          "<Style ss:ID=\"BoldColumn\">\r\n <Font " + 
          "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " + 
          "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" + 
          " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " + 
          "ss:ID=\"Decimal\">\r\n <NumberFormat " + 
          "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " + 
          "<Style ss:ID=\"Integer\">\r\n <NumberFormat " + 
          "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " + 
          "ss:ID=\"DateLiteral\">\r\n <NumberFormat " + 
          "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " + 
          "</Styles>\r\n ";
     const string endExcelXML = "</Workbook>";

     int rowCount = 0;
     int sheetCount = 1;
    <xml version>
    <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
    <Style ss:ID="Default" ss:Name="Normal">
      <Alignment ss:Vertical="Bottom"/>
    <Style ss:ID="BoldColumn">
      <Font x:Family="Swiss" ss:Bold="1"/>
    <Style ss:ID="StringLiteral">
      <NumberFormat ss:Format="@"/>
    <Style ss:ID="Decimal">
      <NumberFormat ss:Format="0.0000"/>
    <Style ss:ID="Integer">
      <NumberFormat ss:Format="0"/>
    <Style ss:ID="DateLiteral">
      <NumberFormat ss:Format="mm/dd/yyyy;@"/>
    <Worksheet ss:Name="Sheet1">
    excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
    for(int x = 0; x < source.Tables[0].Columns.Count; x++)
      excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
    foreach(DataRow x in source.Tables[0].Rows)
      //if the number of rows is > 64000 create a new page to continue output
        rowCount = 0;
        excelDoc.Write(" </Worksheet>");
        excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
      excelDoc.Write("<Row>"); //ID=" + rowCount + "
      for(int y = 0; y < source.Tables[0].Columns.Count; y++)
        System.Type rowType;
        rowType = x[y].GetType();
          case "System.String":
             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\">");
           case "System.DateTime":
             //Excel has a specific Date Format of YYYY-MM-DD followed by  
             //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
             //The Following Code puts the date stored in XMLDate 
             //to the format above
             DateTime XMLDate = (DateTime)x[y];
             string XMLDatetoString = ""; //Excel Converted Date
             XMLDatetoString = XMLDate.Year.ToString() +
                  "-" + 
                  (XMLDate.Month < 10 ? "0" + 
                  XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                  "-" +
                  (XMLDate.Day < 10 ? "0" + 
                  XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                  "T" +
                  (XMLDate.Hour < 10 ? "0" + 
                  XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                  ":" +
                  (XMLDate.Minute < 10 ? "0" + 
                  XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                  ":" +
                  (XMLDate.Second < 10 ? "0" + 
                  XMLDate.Second.ToString() : XMLDate.Second.ToString()) + 
                excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" + 
                             "<Data ss:Type=\"DateTime\">");
              case "System.Boolean":
                excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" + 
                            "<Data ss:Type=\"String\">");
              case "System.Int16":
              case "System.Int32":
              case "System.Int64":
              case "System.Byte":
                excelDoc.Write("<Cell ss:StyleID=\"Integer\">" + 
                        "<Data ss:Type=\"Number\">");
              case "System.Decimal":
              case "System.Double":
                excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" + 
                      "<Data ss:Type=\"Number\">");
              case "System.DBNull":
                excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" + 
                      "<Data ss:Type=\"String\">");
                throw(new Exception(rowType.ToString() + " not handled."));
        excelDoc.Write(" </Worksheet>");


To see what generated, just pass the file name with a .txt extension. For Excel format, the file name will be .xls. For XML format, the file name will be .xml.

The Export Routine does have one side effect! (if anyone can figure out a solution to this, it would be greatly appreciated). The file is saved as an .XLS file, but it technically is still an XML file. This little nuance makes the file size larger then it really should be. A quick fix to this is to just do File Save As.... after the file has been exported. When you do the Save As in Excel, it will reconstruct it as a "real" Excel file, and it will bring the file size down to what it should be.

Feed Back is always welcome.

Simple as that...Enjoy.


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


United States United States
No Biography provided

Comments and Discussions

QuestionMessage Automatically Removed Pinmembernilesh316-Dec-13 6:31 
GeneralMy vote of 5 PinmemberBrianLaF3-Aug-12 11:32 
QuestionHow to define 1000 grouping symbol for decimal number Pinmemberbotngot836-Feb-12 0:03 
What should be defined for the xml schema to format 1000 grouping symbol decimal number. For examaple, the number 1.234,56 have the decimal symbol as ',' and 1000 grouping symbol as '.'. The sample code above just define the decimal symbol only. Thanks in advance and looking for any response.
AnswerRe: How to define 1000 grouping symbol for decimal number Pinmemberbotngot838-Mar-12 16:08 
GeneralMy vote of 5 PinmemberSavindraSingh30-Jan-12 0:51 
QuestionMicrosoft Office Excel cannot open or save any more documents Pinmembersquidder1411-Jan-12 5:44 
GeneralA simpler, and free, class to export from a DataSet into an Excel 2007 .xlsx file. PinmemberMikeGledhill1-Dec-11 3:03 
GeneralMy vote of 5 PinmemberRajesh Kumar Chekuri16-Nov-11 21:09 
AnswerVery nice code PinmemberVictorio A Pellicano7-Nov-11 9:31 
Question*FIX* blank worksheet Pinmemberaarharden30-Oct-11 12:14 
GeneralMy vote of 5 Pinmembermurat8938-Jul-11 3:34 
QuestionJust a quick note about your System.DateTime case.... Pinmemberjp2code27-Jun-11 7:07 
GeneralMy vote of 5 PinmemberArjun14522-Jun-11 0:46 
GeneralHello hello Pinmemberskelmannen10-Nov-10 11:03 
GeneralNew VB version... PinmemberJalapeno Bob5-Nov-10 7:00 
QuestionWould this approach create a lot of xls files on the web server? Pinmembereric.yu.cn13-Oct-10 0:28 
GeneralGiving error in office 2007. Please help. Pinmemberraghav196-Sep-10 2:46 
GeneralExcel created as blank PinmemberPeeter1231-Sep-10 20:14 
Generalgood article~~~ ^^ PinmemberMetalzang11-Aug-10 15:41 
Question[question] Re: good article~~~ ^^ PinmemberMetalzang11-Aug-10 16:43 
GeneralVery useful PinmemberPoojaGRD11-Aug-10 0:52 
GeneralSchema source question PinmemberConsulting Mechanic20-May-10 12:55 
GeneralRe: Schema source question PinmemberXodiak20-May-10 13:07 
GeneralExporting Dataset to Excel 2007 with Hyperlink in or Pinmembermohankundenagoud29-Mar-10 2:00 
GeneralRe: Exporting Dataset to Excel 2007 with Hyperlink in or PinmemberCikaPero16-Jul-10 1:12 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150224.1 | Last Updated 28 May 2005
Article Copyright 2005 by Xodiak
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid