Click here to Skip to main content
15,795,793 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am creating a windows form using C#. I need to save the data of data gridview on my local drive in csv format.
I have used string builder to save the file. I am pretty much able to do this but there is an issue that when I save my file in csv format it ignores all the formatting done in gridview, e.g. I have set the format of datetime column of gridview as dd/mm/yy hh:mm:ss but after being saved it is showing the date in format hh:mm:ss
I don't want to format it manually in excel, I want to make it possible through coding only. I am sending you my export function which I am using.
Any help will be appreciated.

public void Export()
    string strColumn = string.Empty;
    string strRow = string.Empty;
    StringBuilder objSB = new StringBuilder();
    for (int i = 0; i < dataGridView1.Columns.Count; i++)
      strColumn += (i >= dataGridView1.Columns.Count - 1) ? dataGridView1.Columns[i].Name : dataGridView1.Columns[i].Name + ",";

    for (int i = 1; i < dataGridView1.Rows.Count - 1; i++)
      for (int j = 0; j < dataGridView1.Columns.Count; j++)
        strRow += (j >= dataGridView1.Columns.Count - 1) ? dataGridView1.Rows[i].Cells[j].Value.ToString().Replace("\n", "") : dataGridView1.Rows[i].Cells[j].Value.ToString().Replace("\n", "") + ",";
      strRow = string.Empty;
    File.AppendAllText(txtFileName.Text, objSB.ToString());
    MessageBox.Show("The CSV File Is Created");
  catch (Exception e)

Please help me with the proper code as I am quite new in this field.
Updated 23-Nov-10 0:03am
JF2015 23-Nov-10 5:03am    
Edited for spelling, grammar and code formatting.

check this link,
Export to Csv[-]
Share this answer
You will need a special handling for the DateTime column. When saving this column you should not use:

instead you should use proper DateTime formatting.
Here is a list of format strings you might want to use to get the correct DateTime Format in your file:[^]

So, you should use something like:

dataGridView1.Rows[i].Cells[j].Value.ToString("dd/mm/yy hh:mm:ss");

for your datetime column.
Share this answer
Dalek Dave 23-Nov-10 5:31am    
Good Call.

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