将数据导出到 CSV 时如何获取 DataTable 列名?

How to get DataTable Column Names when exporting data to CSV?

我有以下代码可用于将大量数据从 DataTable 导出到 CSV。出于某种原因,DataTable 的列没有随行一起导出。

我是否遗漏了以下代码中的某些内容?获取行时 DataTable 列不会自动导出吗?

 private void ExportToCSV()
    {
        try
        {
            string delimiter = ",";
            DataTable dt = new DataTable();
            foreach (DataGridViewColumn col in dgvSearchFilter.Columns)
            {
                dt.Columns.Add(new DataColumn(col.Name, typeof(string)));
            }

            for (int i = 0; i < dgvSearchFilter.RowCount; i++)
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    dr[j] = dgvSearchFilter.Rows[i].Cells[j].Value;
                }
                dt.Rows.Add(dr);
            }

            string unique = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            string fileName = "SQLQueryOutput_" + unique + ".csv";
            using (StreamWriter swr = new StreamWriter(File.Open(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName), FileMode.CreateNew), Encoding.Default, 1000000))
            { 
                foreach (DataRow dr in dt.Rows)
                {
                    swr.WriteLine(string.Join(delimiter, dr.ItemArray));
                }
            }
            MessageBox.Show("Your file was generated and its ready for use.");
}

类似这样。

    private void ExportToCSV()
    {
        List<string> headers = new List<string>();
        try
        {
            string delimiter = ",";
            DataTable dt = new DataTable();
            foreach (DataGridViewColumn col in dgvSearchFilter.Columns)
            {
                dt.Columns.Add(new DataColumn(col.Name, typeof(string)));
                headers.Add(col.Name);
            }

            for (int i = 0; i < dgvSearchFilter.RowCount; i++)
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    dr[j] = dgvSearchFilter.Rows[i].Cells[j].Value;
                }
                dt.Rows.Add(dr);
            }

            string unique = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            string fileName = "SQLQueryOutput_" + unique + ".csv";
            using (StreamWriter swr = new StreamWriter(File.Open(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName), FileMode.CreateNew), Encoding.Default, 1000000))
            { 
                swr.WriteLine(string.Join(delimiter, headers));
                foreach (DataRow dr in dt.Rows)
                {
                    swr.WriteLine(string.Join(delimiter, dr.ItemArray));
                }
            }
            MessageBox.Show("Your file was generated and its ready for use.");
}
private void ExportToCSV()
{
    string delimiter = ",";

    var columns = dgSearchFilter.Columns.Select(c => c.Name.Cointains(deliminter)?"\"" + c.Name + "\"": c.Name);
    string header = string.Join(delimiter, columns);

    var unique =  DateTime.Now.ToString("yyyyMMddHHmmssffff");
    using (var swr = new StreamWriter($"SQLQueryOutput_{unique}.csv"))
    {
        swr.WriteLine(header);

        var rows = dgvSearchFilter.Rows.Select(r => r.Cells.Select(c => c.Value.ToString()));
        foreach (var row in rows)
        { 
             var line = row.Select(r => r.Contains(delimiter) || r.Contains("\n")?"\"" + r + "\"":r);
             swr.WriteLine(string.Join(delimiter, line));
        }
    }

    MessageBox.Show("Your file was generated and its ready for use.");
}

所以我根据@Joel Coehoorn 的评论修改了我的代码。我能够在不到一分钟 than/about 的时间内导出 1,000,000 行数据(至少一个 230 MB 的文件)

代码如下所示:

            var headers = dgvSearchFilter.Columns.Cast<DataGridViewColumn>();
            string delimiter = ",";
            DataTable dt = new DataTable();
            foreach (DataGridViewColumn col in dgvSearchFilter.Columns)
            {
                dt.Columns.Add(new DataColumn(col.Name, typeof(string)));
            }

            foreach (DataGridViewRow row in dgvSearchFilter.Rows)
            {
                DataRow dataRow = dt.NewRow();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (row.Cells[cell.ColumnIndex].Value == null || row.Cells[cell.ColumnIndex].Value == DBNull.Value || String.IsNullOrWhiteSpace(row.Cells[cell.ColumnIndex].Value.ToString()))
                    {
                        dataRow[cell.ColumnIndex] = " ";
                    }
                    else
                    {
                        dataRow[cell.ColumnIndex] = cell.Value.ToString();
                    }
                }
                dt.Rows.Add(dataRow);
            }

            string unique = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            string fileName = "SQLQueryOutput_" + unique + ".csv";
            using (StreamWriter swr = new StreamWriter(File.Open(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName), FileMode.CreateNew), Encoding.Default, 1000000))
            {
                swr.WriteLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));
                foreach (DataRow dr in dt.Rows)
                {
                    var line = dr.ItemArray.Select(r => r.ToString().Contains(delimiter) || r.ToString().Contains("\n") ? "\"" + r + "\"" : r);
                    swr.WriteLine(string.Join(delimiter, line));
                }
            }

            MessageBox.Show("Your file was generated and its ready for use.");