Export in Excel

lcroito

New member
Joined
Oct 24, 2003
Messages
3
Location
Romania
Hello,

I want to export a Datatable, (or dataview, or datagrid) in a excel file.
I have a windows application. My datagrid is windows.form.datagrid, not a WebDatagrid.

Please write the solution in C#. I dot understand Visual Basic :o

thanks
 
Well... youll have to do a lot work in this. Weve talked about his so many times in this forums that I dont remember how many.

Youll have to go through COM. Adding the Excel composant and learn to write to an excel file. Thats the only way I know.

If someone have better idea... mine is probably not the best but at least it works.
 
Id instead create a CSV (comma-separated values) file. Each line is a row of the
table, and each item on the line (separated by commas) is a new cell in that row.
Just loop through each row and add the values to a file, with commas in between.
Excel can open up CSV files just fine.

C#:
FileStream stream = new FileStream("filename.csv");
StreamWriter writer = new StreamWriter(stream);

foreach (DataRow row in myDataTable.Rows) { // Loop through all rows
  string rowText = "";

  foreach (object item in row.ItemArray)  // Loop through all items
    rowText += item.ToString() + "," // Concatenate item and a comma
  
  rowText = rowText.SubString(0, rowText.Length - 1) // Remove trailing comma
  writer.WriteLine(rowText); // Write the text to the stream
}

writer.Close();
stream.Close();

This code is untested, so if you have any problems, ask.
 

Similar threads

E
Replies
0
Views
45
Elizabeth Swain
E
S
Replies
0
Views
57
sva0008
S
A
Replies
0
Views
78
Ashkan Satarpour
A
I
Replies
0
Views
52
It_s Meee
I
Back
Top