c# - 从DataGrid CSV导出-错误的行



wpf export-to-csv (1)

我怎样才能正确导出我的datagrid到CSV? 为什么行在不同的列?

ExportToCsv函数返回值:

列标题:

“SR#; 8D报告请求;状态(ASSIST);研发中; BTQ NUMBER;优先权;目标日期;实施日期;状态(BTQ)”

行:错误!

“1-3271406718;是;是; BTQ00153254; 6 - 增强; 22.02.2014; 09.09.2014;完成;工程等待”

它应该如何:

列标题:

“SR#; 8D报告请求;状态(ASSIST);研发中; BTQ NUMBER;优先权;目标日期;实施日期;状态(BTQ)”

行:

“1-3271406718; yes; Eng。wait; yes; BTQ00153254; 6 - Enhancement; 22.02.2014; 09.09.2014; COMPLETED”

在这里我的代码:

                string CsvFpath = saveDLG.FileName;
                StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
                string columnHeaderText = "";
                int countColumn = dgvView.Columns.Count - 1;
                if (countColumn >= 0)
                {
                    columnHeaderText = (dgvView.Columns[0].Header).ToString();
                }
                //Writing column headers
                for (int i = 1; i <= countColumn; i++)
                {
                    columnHeaderText = columnHeaderText + ';' + (dgvView.Columns[i].Header).ToString();
                }
                csvFileWriter.WriteLine(columnHeaderText);

                // Writing values row by row
                for (int i = 0; i <= dgvView.Items.Count - 2; i++)
                {
                    string dataFromGrid = "";
                    for (int j = 0; j <= dgvView.Columns.Count - 1; j++)
                    {
                        if (j == 0)
                        {
                            dataFromGrid = ((DataRowView)dgvView.Items[i]).Row.ItemArray[j].ToString();
                        }
                        else
                        {
                            dataFromGrid = dataFromGrid + ';' + ((DataRowView)dgvView.Items[i]).Row.ItemArray[j].ToString();
                        }
                    }
                    csvFileWriter.WriteLine(dataFromGrid);
                }
                csvFileWriter.Flush();
                csvFileWriter.Close();

尝试与Linq。 它更简单易读:

    public string DataGridToCSV(string delimiter = ";")
    {
        var sb = new StringBuilder();

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

        foreach (DataGridViewRow row in myDataGridView.Rows)
        {
            var cells = row.Cells.Cast<DataGridViewCell>();
            sb.AppendLine(string.Join(delimiter, cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
        }
        return sb.ToString();
    }

只需将String保存为*.csv文件即可。





export-to-csv