asp.net导出csv的例子

本文详细介绍了如何使用ASP.NET将数据转换为CSV文件,包括创建CSV文件的基本步骤、如何正确处理逗号以及代码实现。通过实例演示了如何在ASP.NET应用中导出数据到CSV格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


http://wiki.asp.net/page.aspx/401/export-to-csv-fi

 

First let’s see what the CSV file is:

CSV file is a text based file in which data are separated by comma. It can be opened by excel so you can use excel functionality. Each row of data including the title is in separate line. Meanwhile, each row has data separated by comma.

 

How to create a CSV file?

We need to write data to the Response object. Meanwhile the content type should be text/csv also a header type of attachment should be added to response. Afterwards, column names are written to response then to actual data is written (each row should be just in one line).Finally you need to call Response.End to finalize your work.

Important: if any part of data has comma unfortunately the CSV file will screw up. What I did in the code is that I am replacing comma with space so I am sure that the only comma exists in each row is just for separating data rather than being part of data.

public class CSVExporter
{
    public static void WriteToCSV(List<Person> personList)
    {
        string attachment = "attachment; filename=PersonList.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 (Person person in personList)
        {
            WriteUserInfo(person);
        }
        HttpContext.Current.Response.End();
    }

    private static void WriteUserInfo(Person person)
    {
        StringBuilder stringBuilder = new StringBuilder();
        AddComma(person.Name, stringBuilder);
        AddComma(person.Family, stringBuilder);
        AddComma(person.Age.ToString(), stringBuilder);
        AddComma(string.Format("{0:C2}", person.Salary), 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, Family, Age, Salary";
        HttpContext.Current.Response.Write(columnNames);
        HttpContext.Current.Response.Write(Environment.NewLine);
    }

}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值