Search code examples
c#csvexport-to-csv

How to export column header without duplication in C#?


I would like to ask your help in C# programming. I'm making an application, one of the functions of which is to export figures from a Data Grid View to a csv file. I want to add the figures to an existing file with each save. The problem is that the column headers are always added as well. How to export figures without header duplication? Here's my code:

        StreamWriter sw = new StreamWriter("table_1.csv", true, Encoding.UTF8);
        // Column headers:
        for (int i = 0; i < dgv_data.ColumnCount; i++)
        {
            sw.Write(dgv_data.Columns[i].Name + ";");
        }
        sw.WriteLine();

        // rows:
        for (r = 0; r < dgv_data.SelectedRows.Count; r++)
        {
            for (int c = 0; c < dgv_data.ColumnCount; c++)
            {
                sw.Write(dgv_data.SelectedRows[r].Cells[c].Value.ToString() + ";");
            }
            sw.WriteLine();
        }
        sw.Close();
        

Solution

  • Just check whether the file exists before creating the StreamWriter:

    bool fileExists = File.Exists("table_1.csv");
    

    You have to check before the StreamWriter because it will create the file if it's not present already.

    Then, if the file already exists, skip the code that outputs the column headers, as shown in the example below:

    string outputFilename = "table_1.csv";
    bool fileExists = File.Exists(outputFilename);
    
    using (StreamWriter sw = new StreamWriter(outputFilename, true, Encoding.UTF8))
    {
        // Only write column headers if the file is new
        if (!fileExists)
        {
            // Column headers:
            for (int i = 0; i < dgv_data.ColumnCount; i++)
            {
                sw.Write(dgv_data.Columns[i].Name + ";");
            }
            sw.WriteLine();
        }
    
        // rows:
        for (r = 0; r < dgv_data.SelectedRows.Count; r++)
        {
            for (int c = 0; c < dgv_data.ColumnCount; c++)
            {
                sw.Write(dgv_data.SelectedRows[r].Cells[c].Value.ToString() + ";");
            }
            sw.WriteLine();
        }
        sw.Close();
    }