Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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 do't understand Visual Basic :o

 

thanks

Posted

Well... you'll have to do a lot work in this. We've talked about his so many times in this forums that I don't remember how many.

 

You'll have to go through COM. Adding the Excel composant and learn to write to an excel file. That's the only way I know.

 

If someone have better idea... mine is probably not the best but at least it works.

"If someone say : "Die mortal !"... don't stay to see if he isn't." - Unknown

"Learning to program is like going out with a new girl friend. There's always something that wasn't mentioned in the documentation..." - Me

"A drunk girl is like an animal... it scream at everything like a cat and roll in the grass like a dog." - Me after seeing my girlfriend drunk and some of her drunk friend.

C# TO VB TRANSLATOR

  • *Experts*
Posted

I'd 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.

 

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.

"Being grown up isn't half as fun as growing up

These are the best days of our lives"

-The Ataris, In This Diary

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...