Click here to Skip to main content
14,838,511 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
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 dd.mm.yy 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()
{
  try
  {
    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 + ",";
    }
    objSB.AppendLine(strColumn);

    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", "") + ",";
      }
      objSB.AppendLine(strRow);
      strRow = string.Empty;
    }
    File.AppendAllText(txtFileName.Text, objSB.ToString());
    MessageBox.Show("The CSV File Is Created");
  }
  catch (Exception e)
  {
    MessageBox.Show(e.Message.ToString());
  }
}

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

Hi,
check this link,
Export to Csv[-]
   
You will need a special handling for the DateTime column. When saving this column you should not use:
dataGridView1.Rows[i].Cells[j].Value.ToString()

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:

http://msdn.microsoft.com/en-us/library/az4se3k1.aspx[^]

So, you should use something like:

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


for your datetime column.
   
Comments
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