如何在c#中生成和导出csv文件?

时间:2016-05-27 08:39:37

标签: c# csv

我在这里做错了什么? 我试图将客户列表导出到可下载的csv文件,可以在Excel中查看 目前我不关心按钮和监听器,我只想生成实际的csv文件。

public class CSVExporter
{
    public static void WriteToCSV(List<CustomerInformation> customerList)
    {
        string attachment = "attachment; filename=CustomerList.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.AddHeader("Pragma", "public");
        WriteColumnName();
        foreach (CustomerInformation customer in customerList)
        {
            WriteUserInfo(customer);
        }
        HttpContext.Current.Response.End();
    }

    private static void WriteUserInfo(CustomerInformation customer)
    {
        StringBuilder stringBuilder = new StringBuilder();
        AddComma(customer.name, stringBuilder);
        AddComma(customer.email, stringBuilder);
        AddComma(customer.username, stringBuilder);
        AddComma(customer.mobilenumber, stringBuilder);
        AddComma(customer.dateCreated, stringBuilder);
        AddComma(customer.birthday, stringBuilder);

        HttpContext.Current.Response.Write(stringBuilder.ToString());
        HttpContext.Current.Response.Write(Environment.NewLine);
    }

    private static void AddComma(string value, StringBuilder stringBuilder)
    {
        stringBuilder.Append(value.Replace(',', ' '));
        stringBuilder.Append(", ");
    }

    private static void WriteColumnName()
    {
        string columnNames = "Name, Email, Username, Mobile number, Date created, Birthdate";
        HttpContext.Current.Response.Write(columnNames);
        HttpContext.Current.Response.Write(Environment.NewLine);
    }
}

当我运行代码时,我明白了:

enter image description here

1 个答案:

答案 0 :(得分:0)

我只是使用了这个

public HttpResponseMessage DownloadCsv()
        {
            const string csv = "mobile,type,amount\r\n123456789,0,200\r\n56987459,0,200";

            var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(csv)};
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Sample.csv"
            };
            return result;
        }