C# .NET - export dataset to excel in windows application(winForms)

Asked By AMH MH on 23-Nov-10 11:07 PM
Hi all,
can anyone please send me a sample code to export dataset to excel in win forms,
as I know how to do it in asp.net but I want it in win forms.your help will be valuable.....

thanks in advance
AMH
Sirisha Reddy replied to AMH MH on 23-Nov-10 11:12 PM

Hii Below Sample code give how to export..

 if (value is Int16 || value is Int32 || value is Int64 || value is SByte ||
                value
is UInt16 || value is UInt32 || value is UInt64 || value is Byte)
           
{
               
WriteExcelStyledCell(value, CellStyle.Number);
           
}
           
else if (value is Single || value is Double || value is Decimal) //we'll assume it's a currency
           
{
               
WriteExcelStyledCell(value, CellStyle.Currency);
           
}
           
else if (value is DateTime)
           
{
               
//check if there's no time information and use the appropriate style
               
WriteExcelStyledCell(value, ((DateTime)value).TimeOfDay.CompareTo(new TimeSpan(0, 0, 0, 0, 0)) == 0 ? CellStyle.ShortDate : CellStyle.DateTime);
           
}
           
else
           
{
               
WriteExcelStyledCell(value, CellStyle.General);
           
}
       
}

       
#region IDisposable Members

       
public void Dispose()
       
{
           
if (_writer == null)
               
return;

            _writer
.Close();
            _writer
= null;
       
}

       
#endregion
   
}

Then you can export your DataTable using the following:

 public static void ExcelExport(DataTable data, String fileName, bool openAfter)
   
{
       
//export a DataTable to Excel
       
DialogResult retry = DialogResult.Retry;

       
while (retry == DialogResult.Retry)
       
{
           
try
           
{
               
using (ExcelWriter writer = new ExcelWriter(fileName))
               
{
                    writer
.WriteStartDocument();

                   
// Write the worksheet contents
                    writer
.WriteStartWorksheet("Sheet1");

                   
//Write header row
                    writer
.WriteStartRow();
                   
foreach (DataColumn col in data.Columns)
                        writer
.WriteExcelUnstyledCell(col.Caption);
                    writer
.WriteEndRow();

                   
//write data
                   
foreach (DataRow row in data.Rows)
                   
{
                        writer
.WriteStartRow();
                       
foreach (object o in row.ItemArray)
                       
{
                            writer
.WriteExcelAutoStyledCell(o);
                       
}
                        writer
.WriteEndRow();
                   
}
Venkat K replied to AMH MH on 23-Nov-10 11:58 PM
This article will help you to start with:
http://snippets.dzone.com/posts/show/7762

Thanks