// Export Datatable to Excel in C# Windows application
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
namespace ExportExcel
{
public partial class ExportDatatabletoExcel : Form
{
public ExportDatatabletoExcel()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Add Datacolumn
DataColumn workCol = dt.Columns.Add("FirstName", typeof(String));
dt.Columns.Add("LastName", typeof(String));
dt.Columns.Add("Blog", typeof(String));
dt.Columns.Add("City", typeof(String));
dt.Columns.Add("Country", typeof(String));
//Add in the datarow
DataRow newRow = dt.NewRow();
newRow["firstname"] = "Arun";
newRow["lastname"] = "Prakash";
newRow["Blog"] = "http://royalarun.blogspot.com/";
newRow["city"] = "Coimbatore";
newRow["country"] = "India";
dt.Rows.Add(newRow);
//open file
StreamWriter wr = new StreamWriter(@"D:\\Book1.xls");
try
{
for (int i = 0; i < dt.Columns.Count; i++)
{
wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dt.Rows.Count); i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Nice One...
ReplyDeletenice...work for me
ReplyDeleteIt works for me... thanks boss....
ReplyDeleteSuper....thanks a ton.....It perfectly works and helpful to so many people like me...God bless you..Thanks again!
ReplyDeleteThank you...
Deletegreat work
ReplyDeleteThanks for the code !! I 'm newly working on this ,and I found the following tutorail useful. Share with you guys -
ReplyDeletehttp://www.e-iceblue.com/Tutorials/Spire.DataExport/Spire.DataExport-Program-Guide/How-to-Export-Datatable-to-Excel-through-DataGridView.html
Sir, Your material helped me allot. Thank you very much
ReplyDeleteI have a simple problem using your code. The date field in .xls file shows hashes (########) except the header row. Can you please me out to show the date?
Thank you in advance...
Thank you. Good code.
ReplyDeleteNo doubt its a Good article, but the file format is not same as xls. Its a {tab} delimited file. To test, after saving the excel file, apply style or change the font/color etc. It won't save.
ReplyDeleteYou can try ZetExcel.com If you need Excel generation functionality for your .net application.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteIs It compatible in vs 2022?
ReplyDelete