将数据导出为带有换行符的CSV

时间:2016-07-06 06:27:04

标签: c# excel csv

我尝试在C#中将数据导出为CSV文件,但是当我尝试在Excel中导入csv文件时问题就开始了。

在excel中我使用函数"从文本"导入,然后我将分隔符设置为分号

我的问题是有些列有换行符,然后excel中的导入错误。

我尝试过单打和双打报价而没有运气。

我已经搜索了一个解决方案,但还没有找到解决方案。

任何人都知道lumenworks是否具有导出功能,因为我将其用于导入功能

问题在于导出功能,并且需要换行。

if (list.Any())
                {
                    result = list.Select(i => new
                        {
                            i.Product.ProductIdentifier,
                            i.Product.Header,
                            body = string.Format("\"" + "{0}" + "\"", i.Product.Body),
                            Active = i.Product.Active ? 1 : 0,
                            Approved = i.Product.Approved ? 1 : 0,
                            i.Product.Sort,
                            i.Product.MetaDescription,
                            i.Product.MetaKeywords,
                            i.CatalogMenuItemContentItemId
                        }).ToList().ToCsv(";");
                }

string attachment = "attachment; filename=myfile.csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
        HttpContext.Current.Response.Write(result);
        HttpContext.Current.Response.End();    

public static string ToCsv<T>(this IEnumerable<T> items, string seperator = ",")
        where T : class
    {
        var csvBuilder = new StringBuilder();
        var properties = typeof(T).GetProperties();
        foreach (T item in items)
        {
            string line = string.Join(seperator, properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
            csvBuilder.AppendLine(line);
        }
        return csvBuilder.ToString();
    }

    private static string ToCsvValue<T>(this T item)
    {
        return string.Format("{0}", HttpUtility.HtmlDecode(item.ToString()));
    }

有什么想法吗?

0 个答案:

没有答案
相关问题