How to create an excel file and write a datagrid to it using dotnet

Posted by Dinee_432 under C# on 10/30/2009 | Views : 1916 | Status : [Member] | Replies : 2
My application is when I click on a button i need to create a new excel file and write a datagrid datas to it.
Please help me in doing this.


thanks




Responses

Posted by: Syedshakeer on: 11/2/2009 [Member] Starter

Up
0
Down
Hi Dinne
creating a text file with a coding :-
Below line is creating a excelfile with a name file11.just you have to give a path where your Excel file should be located.here I am saving my file in 'F Drive'.
FileStream fileStream = new FileStream(@"F:\file11.xls", FileMode.Create);

Here FileMode.Create will automatically create a excelfile with a name called file11.xls in 'F drive' with a FileStream Class.
If your are using Io Streams class then you have to Import a NameSpace as Using Sytstem.Io ;
Write below code in one Button
TextWriter sw = new StreamWriter(@"F:\\file11.xls");

int rowcount = dataGridView1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dataGridView1.Rows[i].Cells[0].Value.ToString() + "\t" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "\t" + dataGridView1.Rows[i].Cells[2].Value.ToString());
}
sw.Close();
//Don't Forget Close the TextWriter Object(sw)
MessageBox.Show("Data Successfully Exported toExcelsheet");


In above code

Cells[0] is first column in datagridview
Cells[1] is second column in datagridview
Cells[2] is third column in datagridview





Syed Shakeer Hussain

Dinee_432, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Carpenter on: 11/2/2009 [Member] Starter

Up
0
Down
There is a good movie and some source code (in VB), on that here:

http://www.asp.net/learn/linq-videos/video-218.aspx



Hope it helps...





Dinee_432, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response