使用LINQ将表导出为CSV

本文关键字:CSV LINQ 使用 | 更新日期: 2023-09-27 18:00:14

我很难使用LINQ在CSV文件中导出DB表。我尝试了一些相关主题的东西,但时间太长了,我需要一个最简单的解决方案。一定有什么。使用此代码是有问题的,该文件已创建,但为空。当我尝试调试时,查询很好,有我想要导出的所有内容。我做错了什么?

private void Save_Click(object sender, RoutedEventArgs e)
    {
        StreamWriter sw = new StreamWriter("test.csv");
        DataDataContext db = new DataDataContext();
        var query = from x in db.Zbozis
                    orderby x.Id
                    select x;
        foreach (var something in query)
        {
            sw.WriteLine(something.ToString());
        }
    }

编辑:好的,我尝试了你所有的建议,遗憾的是,结果是一样的(CSV已经创建,但其中是10x Lekarna.Zbozi(项目名称/db+表名称))。所以我用了一种方法,我找到了(为什么要重新发明轮子,嗯)。

public string ConvertToCSV(IQueryable query, string replacementDelimiter)
    {
        // Create the csv by looping through each row and then each field in each row
        // seperating the columns by commas
        // String builder for our header row
        StringBuilder header = new StringBuilder();
        // Get the properties (aka columns) to set in the header row
        PropertyInfo[] rowPropertyInfos = null;
        rowPropertyInfos = query.ElementType.GetProperties();
        // Setup header row 
        foreach (PropertyInfo info in rowPropertyInfos)
        {
            if (info.CanRead)
            {
                header.Append(info.Name + ",");
            }
        }
        // New row
        header.Append("'r'n");
        // String builder for our data rows
        StringBuilder data = new StringBuilder();
        // Setup data rows
        foreach (var myObject in query)
        {
            // Loop through fields in each row seperating each by commas and replacing 
            // any commas in each field name with replacement delimiter
            foreach (PropertyInfo info in rowPropertyInfos)
            {
                if (info.CanRead)
                {
                    // Get the fields value and then replace any commas with the replacement delimeter
                    string tmp = Convert.ToString(info.GetValue(myObject, null));
                    if (!String.IsNullOrEmpty(tmp))
                    {
                        tmp.Replace(",", replacementDelimiter);
                    }
                    data.Append(tmp + ",");
                }
            }
            // New row
            data.Append("'r'n");
        }
        // Check the data results... if they are empty then return an empty string
        // otherwise append the data to the header
        string result = data.ToString();
        if (string.IsNullOrEmpty(result) == false)
        {
            header.Append(result);
            return header.ToString();
        }
        else
        {
            return string.Empty;
        }
    }

所以我有一个以前代码的修改版本:

 StreamWriter sw = new StreamWriter("pokus.csv");
        ExportToCSV ex = new ExportToCSV();
        var query = from x in db.Zbozis
                    orderby x.Id
                    select x;
        string s = ex.ConvertToCSV(query,"; ");
        sw.WriteLine(s);
        sw.Flush();

一切都很好,只是它导出一列中的每一行,并且不将其分离。请参阅此处->https://i.stack.imgur.com/XSNK0.jpg问题很明显,如何像我在数据库中那样将其划分为列?

感谢

使用LINQ将表导出为CSV

您没有关闭文件。使用"使用"

using(StreamWriter sw = new StreamWriter("test.csv"))
{
     ..............
}

或者简单地尝试这个

File.WriteAllLines("test.csv",query);