使用LINQ将表导出为CSV

时间:2014-04-24 21:17:24

标签: c# wpf linq csv

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

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();

一切都很好,除了它导出一列中的每一行而不分开它。看到这里 - > http://i.stack.imgur.com/XSNK0.jpg 那么问题是显而易见的,如何将它分成我在数据库中的列?

由于

1 个答案:

答案 0 :(得分:2)

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

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

或者只是尝试这个

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