Click here to Skip to main content
15,867,278 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
I want to save Datagridview which include strings to .csv file so I used the following code ,the problem is when opened it i noticed that the cells are miss ordered the rwos which must be under a specific column is scattered along the cells ,then I noticed the idea of .csv files that it use comma so I used the String.Replace(',',' ') method but it still as it is the data is miss-ordered !!!!!!

what I can do maybe the [:] sign or what !!!!
C#
private void ExtractDataToCSV(DataGridView dgv)
       {

           // Don't save if no data is returned
           if (dgv.Rows.Count == 0)
           {
               return;
           }
           StringBuilder sb = new StringBuilder();
           // Column headers
           string columnsHeader = "";
           for (int i = 0; i < dgv.Columns.Count; i++)
           {
               columnsHeader += dgv.Columns[i].Name + ",";
           }
           sb.Append(columnsHeader + Environment.NewLine);
           // Go through each cell in the datagridview
           foreach (DataGridViewRow dgvRow in dgv.Rows)
           {
               // Make sure it's not an empty row.
               if (!dgvRow.IsNewRow)
               {
                   for (int c = 0; c < dgvRow.Cells.Count; c++)
                   {
                       // Append the cells data followed by a comma to delimit.

                       sb.Append(dgvRow.Cells[c].Value + ",");
                   }
                   // Add a new line in the text file.
                   sb.Append(Environment.NewLine);
               }
           }
           // Load up the save file dialog with the default option as saving as a .csv file.
           SaveFileDialog sfd = new SaveFileDialog();
           sfd.Filter = "CSV files (*.csv)|*.csv";
           if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
           {
               // If they've selected a save location...
               using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
               {
                   // Write the stringbuilder text to the the file.
                   sw.WriteLine(sb.ToString());
               }
           }
           // Confirm to the user it has been completed.
           MessageBox.Show("CSV file saved.");
       }
Posted
Updated 18-Sep-12 13:54pm
v2
Comments
[no name] 18-Sep-12 20:07pm    
What do you mean the rows are mis-ordered?
Sergey Alexandrovich Kryukov 18-Sep-12 21:04pm    
Mis-ordered code :-)
--SA
[no name] 18-Sep-12 21:09pm    
I really wish these guys would figure out that we can't see their files to know what it is that they are seeing.
Sergey Alexandrovich Kryukov 18-Sep-12 22:31pm    
Right. Now, when the first term in schools has started, my access to their hard drives is somewhat limited. :-)
--SA
khoighost 10-Jun-13 20:43pm    
how to use unicode here?!

Damn sure this would be helpful. I am succeeded by writing this code:
public void writeCSV(DataGridView gridIn, string outputFile)
{
    //test to see if the DataGridView has any rows
    if (gridIn.RowCount > 0)
    {
       string value = "";
       DataGridViewRow dr = new DataGridViewRow();
       StreamWriter swOut = new StreamWriter(outputFile);
 
       //write header rows to csv
       for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
       {
          if (i > 0)
          {
             swOut.Write(",");
          }
          swOut.Write(gridIn.Columns[i].HeaderText);
       }
 
       swOut.WriteLine();
 
       //write DataGridView rows to csv
       for (int j = 0; j <= gridIn.Rows.Count - 1; j++)
       {
          if (j > 0)
          {
          swOut.WriteLine();
          }
 
          dr = gridIn.Rows[j];
 
          for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
          {
             if (i > 0)
             {
                swOut.Write(",");
             }
 
             value = dr.Cells[i].Value.ToString();
             //replace comma's with spaces
             value = value.Replace(',', ' ');
             //replace embedded newlines with spaces
             value = value.Replace(Environment.NewLine, " ");
 
             swOut.Write(value);
          }
       }
       swOut.Close();
    }
 }


after copy paste this code double click the button and write this:

C#
private void button1_Click(object sender, EventArgs e)
       {
           writeCSV(dataGridView1,"result.csv");
           MessageBox.Show("Converted successfully to *.csv format");
       }
 
Share this answer
 
Comments
bijaynayak 4-Jul-14 5:31am    
this code is looking and very help full.but after loading into the csv file we need to empty the cell or that entire row.how to achieve this scenario
Member 15089981 27-May-21 23:21pm    
Hello! This solution works fine for me however
I had an error saying that dr.Cells[i].Value.ToString() was having a null error. This was due to the way that Rows are counted, you need to set AllowUserToAddRows to False in the DataGrid OR subtract 2 from the Row Count, i.e.

for (int j = 0; j <= gridIn.Rows.Count - 2; j++)

This solved my issue! Hopefullt this helps anyone coming across the same error.
Well, it depends.

In this case it depends on how you expect to open the exported file afterwards. If you plan to use some spreadsheet software (Open/Libre Office Calc, Mircrosoft Excel, ...) then you can tell it what delimiter to use. It should work with comma as delimiter as long as there are no commas in your data. It should work with tabs as well, again, there should be no tabs in your actual data.

If you're going to open the exported file in notepad, you don't want a separator but a constant column width instead. Like this one for columns 10 characters wide:
C#
sb.Append(string.Format("{0,-10}", value).Substring(0, 10));
 
Share this answer
 
v3
Comments
Al-Samman Mahmoud 19-Sep-12 5:51am    
How Can I tell it what delimiter to use ,and Can tell him to use "|" as rows separating sign .
I Want to use Microsoft excel to open .
lukeer 19-Sep-12 8:41am    
IIRC, there was an issue in opening CSV files in Excel. I have no idea how to set it up for that. My workaround is opening CSV files in LibreOffice Calc. It's free to download and use (if your admin allows you to install). Calc comes with a dialog to specify what delimiter to expect.

Your code sets the delimiter here:
sb.Append(dgvRow.Cells[c].Value + ",");
Change the comma to whatever you like. I'd try "\t" for a tab and see if Excel is confident with it.
The next statement inserts an Environment.NewLine. That's your current row delimiter. I'd leave it that way, but again, you can change that to whatever you want.

And don't forget to tweak the header part also.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900