简体   繁体   中英

How to export my DataGridView to a csv file?

I'm trying to export my DataGridView to csv file with this code:

private void saveToCsv(DataGridView dGV, string filename)
{
    if (dGV.RowCount > 0)
    {
        DataTable dt = new DataTable();
        dt = dGV.DataSource as DataTable;
        int d = dt.Columns.Count;
        int c = dt.Rows.Count;
        foreach (var column in dt.Columns.Cast<DataColumn>().ToArray())
        {
            if (dt.AsEnumerable().All(dr => dr.IsNull(column)))
                d--;
        }
        string stOutput = "";
        DataGridViewRow ds = new DataGridViewRow();
        StreamWriter swOut = new StreamWriter(filename);

        //write header rows to csv
        for (int i = 0; i <= d - 1; i++)
        {
            if (i > 0)
            {
                swOut.Write(",");
            }
            swOut.Write(dGV.Columns[i].HeaderText);
        }

        swOut.WriteLine();

        //write DataGridView rows to csv
        for (int j = 0; j <= c - 1; j++)
        {
            if (dt.Rows[j].IsNull)
            if (j > 0)
            {
                swOut.WriteLine();
            }

            ds = dGV.Rows[j];

            for (int i = 0; i <= d - 1; i++)
            {
                if (i > 0)
                {
                    swOut.Write(",");
                }

                stOutput = ds.Cells[i].Value.ToString();
                //replace comma's with spaces
                stOutput = stOutput.Replace(',', ' ');
                //replace embedded newlines with spaces
                stOutput = stOutput.Replace(Environment.NewLine, " ");

                swOut.Write(stOutput);
            }
        }
        swOut.Close();
    }
    MessageBox.Show("Data successfully saved");
}

but the output is this:

0.512,45,tested_negative
0.966,33,tested_negative
0.42,35,tested_negative
0.665,46,tested_positive
0.329,29,tested_negative
,,
,,
,,
,,
,,
,,
,,
,,

The empty rows get exported too.

How can I fix this problem?

1st you should qualify your text data incase they have commas in them if your going to create a comma delimited file

taken from stackoverflow (ref Exporting datagridview to csv file )

var sb = new StringBuilder();

var headers = dGV.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    var cells = row.Cells.Cast<DataGridViewCell>();

    string temp string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray())
    temp = temp.Replace(",","");
    temp = temp.Replace("\"","");
    if(temp.Length > 0)
    {
      sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
    }
}
System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\test\hereIam.csv");
file.WriteLine(sb.ToString()); // 

If you want to stick with your code, check the stOutput - if it is ',,' do not write it into the file.

You might want to check https://stackoverflow.com/a/4959869/7505395 - one of the answers to c# datatable to csv

// ... your code ...

if ( stOutput != ",,")
    swOut.Write(stOutput); 
else suppressNewLine = true;  // suppress newline above, and reset bool to false

// ... more of your code ...

You have to fix the empty newlines after that.

Best thing to do would be to assemble each line (or the whole table gasp ) into a StringBuilder - and write it only once (or at least line-wise) to the file when (line or whole table) is fully assembled.

StringBuilders are build for itereatively adding to them and should make your code much faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM