Wednesday, May 13, 2009

Export DatagridView contents to Excel File

Hi Friends,

I read about a simple article on how to Export DatagridView contents to Excel File.
With due credit to author(I lost the link), I am posting it for you all.
______________________________________________________________
Call to the function:

string ExcelFileName = @"C:\TestingExcelFolder\" + "Testing.xls";
this.export_datagridview_to_excel(ref dGViewTesting, ExcelFileName);
______________________________________________________________
Function definition :

public void export_datagridview_to_excel(ref DataGridView dgv, string excel_file)
{
if(!System.IO.Directory.Exists(@"C:\TestingExcelFolder"))
{
System.IO.Directory.CreateDirectory(@"C:\TestingExcelFolder");
}
if (!System.IO.File.Exists(excel_file))
{
System.IO.FileStream fs = System.IO.File.Create(excel_file);
fs.Dispose();
}

int cols;
//--open file
StreamWriter wr = new StreamWriter(excel_file);
//--determine the number of columns and write columns to file
cols = dgv.Columns.Count;
wr.WriteLine("\t Heading\t");
wr.WriteLine();
for (int i = 0; i < cols; i++)
{
wr.Write(dgv.Columns[i].HeaderText.ToString().ToUpper() + "\t");
}

wr.WriteLine();
//--write rows to excel file
for (int i = 0; i <= (dgv.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dgv.Rows[i].Cells[j].Value != null)
wr.Write(dgv.Rows[i].Cells[j].Value + "\t");
else
{ wr.Write("\t"); }
}

wr.WriteLine();
}
//--close file
wr.Close();
}
______________________________________________________________

Let's Make Things Simple :-)

No comments:

Post a Comment