Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# Windows Forms
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 !!!!
 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 18-Sep-12 14:24pm
Edited 18-Sep-12 14:54pm
v2
Comments
Wes Aday at 18-Sep-12 20:07pm
   
What do you mean the rows are mis-ordered?
Sergey Alexandrovich Kryukov at 18-Sep-12 21:04pm
   
Mis-ordered code :-)
--SA
Wes Aday at 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 at 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 at 10-Jun-13 20:43pm
   
how to use unicode here?!
lukeer at 11-Jun-13 13:56pm
   
By default, all this already is unicode.
Do you have something special that you know is in another format?
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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:
sb.Append(string.Format("{0,-10}", value).Substring(0, 10));
  Permalink  
v3
Comments
Al-Samman Mahmoud at 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 at 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.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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:
 
private void button1_Click(object sender, EventArgs e)
       {
           writeCSV(dataGridView1,"result.csv");
           MessageBox.Show("Converted successfully to *.csv format");
       }
  Permalink  
Comments
bijaynayak at 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

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



Advertise | Privacy | Mobile
Web02 | 2.8.1411023.1 | Last Updated 12 Jun 2014
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100