简体   繁体   English

如何将DataGridView导出到csv文件?

[英]How to export my DataGridView to a csv file?

I'm trying to export my DataGridView to csv file with this code: 我正在尝试使用以下代码将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");
}

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 ) 取自stackoverflow(请参阅将datagridview导出到csv文件

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. 如果要坚持使用代码,请检查stOutput如果它是',,'请不要将其写入文件中。

You might want to check https://stackoverflow.com/a/4959869/7505395 - one of the answers to c# datatable to csv 您可能要检查https://stackoverflow.com/a/4959869/7505395-C#数据表 到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. 最好的办法是将每行(或整个表gasp )组装到StringBuilder -并在完全组装(行或整个表)时仅一次(或至少逐行)地将其写入文件。

StringBuilders are build for itereatively adding to them and should make your code much faster. StringBuilders是为向其迭代添加而构建的,应该使您的代码更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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