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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[将数据导出到CSV时如何获取DataTable列名?相关的知识,希望对你有一定的参考价值。

我具有以下代码,可用于将大量数据从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("
")?""" + r + """:r);
             swr.WriteLine(string.Join(delimiter, line));
        }
    }

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

以上是关于[将数据导出到CSV时如何获取DataTable列名?的主要内容,如果未能解决你的问题,请参考以下文章

c#怎么将datatable导出到csv文件中

如何将具有值的行/列添加到数据表 csv 导出

导出数据表时排除/隐藏某些列

将csv上传到sql server时,“给定的ColumnMapping与源或目标中的任何列都不匹配”

将 DataTable 转换为 CSV 流

无法使用 OLEDB 从 CSV 获取所有列的值