Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i want to save the datagridview data to CSV but dont know the idea to chang the date format from 2022/03/07 00:00 to 2022/03/07.

What I have tried:

private void button7_Click(object sender, EventArgs e)
     {
    
     try
          {
              string csv = string.Empty;
              string HeaderText = string.Empty;
             foreach (DataGridViewColumn column in tableDataGridView.Columns)
                 {
                     csv += column.HeaderText + ',';
    
                 }
                 csv += "\r\n";
                 foreach (DataGridViewRow row in tableDataGridView.Rows)
                 {
                    foreach (DataGridViewCell cell in row.Cells)
                        {
                            if (cell.Value != null)
    
                             {
                   
           csv += cell.Value.ToString()/*.TrimEnd(',')*//*.Replace(",", ";") */+ /*','*/",";
                               
    
                         }
                            
                     }
                     csv += "\r\n";
                 }
    
    
                 string folderPath = "C:\\CSV\\";
                 if (!Directory.Exists(folderPath))
                 {
                     Directory.CreateDirectory(folderPath);
                 }
    
                 {
    
    
                  File.WriteAllText(folderPath + DateTime.Now.ToString("yyyyMMdd_HH-mm-ss") + ".csv", csv, Encoding.UTF8);
    
    
                     textBox3.Text = "保存しました";
                     textBox3.BackColor = Color.Green;
                 }
             }
Posted
Updated 6-Mar-22 21:06pm

1 solution

You have other problems you need to sort out first:
1) Don't use the DataGridView itself directly unless you really have to - use the underlying DataSource instead. That way, you get access to the actual data fields more easily.
2) Your column headers line ends with a spurious comma: consider using string.Join[^] instead of a manual loop.
C#
if (myDataGridView.DataSource is DataTable dt)
    {
    string s = string.Join(",", dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName));
    Console.WriteLine(s);
    }

3) Your row data isn't separated by a comma at all! Again, string.Join is your friend here.
4) Strings are immutable in .NET: each time you try to add two strings, you cause a new memory allocation and two copy operations - which can get extremely time- and memory-consuming with large data sets. Use a StringBuilder[^] instead.
5) Instead of a "blanket" ToString operation to build the CSV row data, check the datatype: if it's a DateTime, then use a specific ToString to convert it.

C#
if (myDataGridView.DataSource is DataTable dt)
    {
    List<string> csvReady = new List<string>(dt.Rows.Count + 1);
    csvReady.Add(string.Join(",", dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName)));
    List<string> rowData = new List<string>(dt.Columns.Count);
    foreach (DataRow row in dt.Rows)
        {
        rowData.Clear();
        for (int i = 0; i < dt.Columns.Count; i++)
            {
            object cell = row[i];
            if (cell.GetType() == typeof(DateTime))
                {
                rowData.Add(((DateTime)cell).ToString("yyyy/MM/dd"));
                }
            else
                {
                rowData.Add(cell.ToString());
                }
            }
        csvReady.Add(string.Join(",", rowData));
        }
    string csv = string.Join("\n", csvReady);
    }
 
Share this answer
 
v2

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