简体   繁体   English

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

[英]How to generate and export a csv file in c#?

What am I doing wrong here? 我在这里做错了什么? I am trying to export a list of customers to a downloadable csv file, that can be viewed in Excel Currently I do not care about buttons and listeners, I just want to generate the actual csv file. 我正在尝试将客户列表导出到可下载的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);
    }
}

When I run the code, I get this: 运行代码时,我得到以下信息:

在此处输入图片说明

I've simply used this 我只是用这个

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;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM