create an excel from a dataset

A simple way to convert dataset to excel sheet…

 Create a C# class file with the name WorkbookEngine.cs. Add the following code into it

public static void CreateWorkbook(DataSet ds, String path, string fileNam)


XmlDataDocument xmlDataDoc = new XmlDataDocument(ds);

XslTransform xt = new XslTransform();

StreamReader reader =newStreamReader(typeof (WorkbookEngine).Assembly.GetManifestResourceStream(typeof (WorkbookEngine), “Excel.xsl”));

XmlTextReader xRdr = new XmlTextReader(reader);

xt.Load(xRdr, null, null);StringWriter sw = newStringWriter();

xt.Transform(xmlDataDoc, null, sw, null);

StreamWriter myWriter = newStreamWriter(path + fileNam);

myWriter.Write (sw.ToString());

myWriter.Close ();



The following code should be available in a file named Excel.xsl

 <xsl:stylesheet version=”1.0″
 xmlns:ss=”urn:schemas-microsoft-com:office:spreadsheet” > 
<xsl:template match=”/”>
  <Workbook xmlns=”urn:schemas-microsoft-com:office:spreadsheet”
<xsl:template match=”/*”>
  <xsl:attribute name=”ss:Name”>
  <xsl:value-of select=”local-name(/*/*)”/>
    <Table x:FullColumns=”1″ x:FullRows=”1″>
        <xsl:for-each select=”*[position() = 1]/*”>
          <Cell><Data ss:Type=”String”>
          <xsl:value-of select=”local-name()”/>
<xsl:template match=”/*/*”>
<xsl:template match=”/*/*/*”>
  <Cell><Data ss:Type=”String”>
    <xsl:value-of select=”.”/>

Add this file also to the solution.


On the solution explorer right click on the Excel.xsl file and select properties.

In build action choose “Embedded Resource”.



In our coding class add the following line to invoke all this.

WorkbookEngine.CreateWorkbook(<our Dataset name>, “Our file path to store the excel sheet”, \\OurExcelFileName.xls);


Save all the files and run the code.

Our excel file will be created!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: