将数据集/数据表转换为 CSV

发布于 2024-10-15 08:17:57 字数 93 浏览 2 评论 0原文

请告诉我,是否有任何方法可以从 DataTable 或 DataSet 生成 CSV 文件?具体来说,无需手动迭代 DataTable 的行并连接。

请帮忙

Please let me know, if there any way to generate CSV files from a DataTable or DataSet? To be specific, without manually iterating through rows of DataTable and concatenating.

Please help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

够钟 2024-10-22 08:17:58

我希望还有一种可能的方法可以做到这一点:

    static void Main(string[] args)
    {
        DataTable dt = new DataTable("MyTable");
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        DataRow dr1 = dt.NewRow();
        dr1["Id"] = 1;
        dr1["Name"] = "John Smith";
        dt.Rows.Add(dr1);
        DataRow dr2 = dt.NewRow();
        dr2["Id"] = 2;
        dr2["Name"] = "John West";
        dt.Rows.Add(dr2);

        List<DataRow> list = dt.AsEnumerable().ToList();
        var strlist = from dr in list
                      select dr[0] + ", " + dr[1];
        var csv = string.Join(Environment.NewLine,strlist);
        Console.WriteLine(csv);
    }

There is, I hope, also a possible way for doing that:

    static void Main(string[] args)
    {
        DataTable dt = new DataTable("MyTable");
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        DataRow dr1 = dt.NewRow();
        dr1["Id"] = 1;
        dr1["Name"] = "John Smith";
        dt.Rows.Add(dr1);
        DataRow dr2 = dt.NewRow();
        dr2["Id"] = 2;
        dr2["Name"] = "John West";
        dt.Rows.Add(dr2);

        List<DataRow> list = dt.AsEnumerable().ToList();
        var strlist = from dr in list
                      select dr[0] + ", " + dr[1];
        var csv = string.Join(Environment.NewLine,strlist);
        Console.WriteLine(csv);
    }
韵柒 2024-10-22 08:17:58
//Dataset To Xls
ExportDataSetToCsvFile(DS,@"C:\\");

internal static void ExportDataSetToCsvFile(DataSet _DataSet, string DestinationCsvDirectory)
{
    try
    {
        foreach (DataTable DDT in _DataSet.Tables)
        {
            String MyFile = @DestinationCsvDirectory + "\\_" + DDT.TableName.ToString() + DateTime.Now.ToString("yyyyMMddhhMMssffff") + ".csv";//+ DateTime.Now.ToString("ddMMyyyyhhMMssffff")
            using (var outputFile = File.CreateText(MyFile))
            {
                String CsvText = string.Empty;

                foreach (DataColumn DC in DDT.Columns)
                {
                    if (CsvText != "")
                        CsvText = CsvText + "," + DC.ColumnName.ToString();
                    else
                        CsvText = DC.ColumnName.ToString();
                }
                outputFile.WriteLine(CsvText.ToString().TrimEnd(','));
                CsvText = string.Empty;

                foreach (DataRow DDR in DDT.Rows)
                {
                    foreach (DataColumn DCC in DDT.Columns)
                    {
                        if (CsvText != "")
                            CsvText = CsvText + "," + DDR[DCC.ColumnName.ToString()].ToString();
                        else
                            CsvText = DDR[DCC.ColumnName.ToString()].ToString();
                    }
                    outputFile.WriteLine(CsvText.ToString().TrimEnd(','));
                    CsvText = string.Empty;
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
    catch (Exception Ex)
    {
        throw Ex;
    }  
}
//Dataset To Xls
ExportDataSetToCsvFile(DS,@"C:\\");

internal static void ExportDataSetToCsvFile(DataSet _DataSet, string DestinationCsvDirectory)
{
    try
    {
        foreach (DataTable DDT in _DataSet.Tables)
        {
            String MyFile = @DestinationCsvDirectory + "\\_" + DDT.TableName.ToString() + DateTime.Now.ToString("yyyyMMddhhMMssffff") + ".csv";//+ DateTime.Now.ToString("ddMMyyyyhhMMssffff")
            using (var outputFile = File.CreateText(MyFile))
            {
                String CsvText = string.Empty;

                foreach (DataColumn DC in DDT.Columns)
                {
                    if (CsvText != "")
                        CsvText = CsvText + "," + DC.ColumnName.ToString();
                    else
                        CsvText = DC.ColumnName.ToString();
                }
                outputFile.WriteLine(CsvText.ToString().TrimEnd(','));
                CsvText = string.Empty;

                foreach (DataRow DDR in DDT.Rows)
                {
                    foreach (DataColumn DCC in DDT.Columns)
                    {
                        if (CsvText != "")
                            CsvText = CsvText + "," + DDR[DCC.ColumnName.ToString()].ToString();
                        else
                            CsvText = DDR[DCC.ColumnName.ToString()].ToString();
                    }
                    outputFile.WriteLine(CsvText.ToString().TrimEnd(','));
                    CsvText = string.Empty;
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
    catch (Exception Ex)
    {
        throw Ex;
    }  
}
花开半夏魅人心 2024-10-22 08:17:58

所以这是一个相当奇怪的解决方案,但它比大多数解决方案运行得更快,因为它利用了 JSON.net 库的序列化。这显着加快了求解速度。

步骤:

  1. 创建数据表中每列名称的数组,应该是
    简单
  2. 使用 JSON.net 将数据表转换为 json 字符串

    string json = JsonConvert.SerializeObject(dt, Formatting.None);

  3. 开始在 C# 字符串上使用 Replace 函数并去掉
    所有json格式的json字符串。

    json = json.Replace("\"", "").Replace("},{", "\n").Replace(":", "").Replace("[{ ", "").Replace("}]", "");

  4. 然后使用步骤 1 中的数组从
    json 字符串。您将得到一个 csv 格式的字符串。

  5. 考虑使用步骤 1 中创建的数组来添加列名称
    返回为 csv 格式的第一行。

So this is a fairly bizarre solution, but it works faster than most as it makes use of the JSON.net library's serialization. This speeds the solution up significantly.

Steps:

  1. Create array of every column name in the data table, should be
    simple
  2. Use JSON.net to convert datatable to a json string

    string json = JsonConvert.SerializeObject(dt, Formatting.None);

  3. Begin making use of the Replace function on c# strings and strip the
    json string of all json formatting.

    json = json.Replace("\"", "").Replace("},{", "\n").Replace(":", "").Replace("[{", "").Replace("}]", "");

  4. Then use the array from step 1 to remove all column names from the
    json string. You are left with a csv formatted string.

  5. Consider using the array created in step 1 to add the column names
    back in as the first row in csv format.

面犯桃花 2024-10-22 08:17:57

有几种方法可以做到这一点。

最简单的方法之一(IMO)是使用 FileHelpers Library

FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);

There are several ways to do that.

One of the simplest (IMO) is using FileHelpers Library

FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);
望喜 2024-10-22 08:17:57

一个相对简单、紧凑且相当灵活的解决方案可能是以下扩展方法:

public static string ToCsv(this DataTable table, string colSep = "", string rowSep = "\r\n")
{
    var format = string.Join(colSep, Enumerable.Range(0, table.Columns.Count)
                                            .Select(i => string.Format("{{{0}}}", i)));

    return string.Join(rowSep, table.Rows.OfType<DataRow>()
                                        .Select(i => string.Format(format, i.ItemArray)));
}

请注意,此解决方案可能会导致大量数据出现问题,在这种情况下,您应该流式输出。引用和格式化当然会使代码变得更加复杂。

A relative simple, compact and quite flexible solution could be the following extension method:

public static string ToCsv(this DataTable table, string colSep = "", string rowSep = "\r\n")
{
    var format = string.Join(colSep, Enumerable.Range(0, table.Columns.Count)
                                            .Select(i => string.Format("{{{0}}}", i)));

    return string.Join(rowSep, table.Rows.OfType<DataRow>()
                                        .Select(i => string.Format(format, i.ItemArray)));
}

Please note that this solution could cause problems with huge amounts of data, in which case you should stream the output. Quoting and formatting would of course make the code more complex.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文