如何将我的DataGridView导出到csv文件?

时间:2018-02-22 15:21:38

标签: c#

我尝试使用以下代码将DataGridView导出到csv文件:

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");
}

但输出是这样的:

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
,,
,,
,,
,,
,,
,,
,,
,,

空行也会被导出。

如何解决此问题?

2 个答案:

答案 0 :(得分:0)

如果要创建逗号分隔文件

,首先应该对文本数据进行限定,如果他们有逗号。

取自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()); // 

答案 1 :(得分:-1)

如果您想坚持使用代码,请检查stOutput - 如果',,'不将其写入文件。

您可能需要查看https://stackoverflow.com/a/4959869/7505395 - 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 ...

之后你必须修复空的换行符。

最好的办法是将每一行(或整个表格 gasp )组合成StringBuilder - 并且只将其写入一次(或至少按行顺序)文件何时(线或整个表)完全组装。

StringBuilders是 build ,用于迭代添加它们,并且应该使代码更快。