导出到CSV文件





4.00/5 (3投票s)
首先,我们来看看 CSV 文件是什么:CSV 文件是一种基于文本的文件,其中数据由逗号分隔。它可以被 Excel 打开,所以你可以使用
首先,我们来看看 CSV 文件是什么
CSV 文件是一种基于文本的文件,其中数据由逗号分隔。它可以被 Excel 打开,所以你可以使用 Excel 的功能。每行数据(包括标题)都在单独一行中。同时,每行中的数据由逗号分隔。
如何创建 CSV 文件?
我们需要将数据写入 Response 对象。同时,Content Type 应设置为 text/csv,并且应向 Response 添加一个 attachment 类型的 Header。之后,将列名写入 Response,然后写入实际数据(每行数据应只占一行)。最后,你需要调用 Response.End 来完成你的工作。
重要提示:如果数据中的任何部分包含逗号,那么 CSV 文件将出错。我在代码中做的就是将逗号替换为空格,这样我就能确保每行中存在的唯一逗号是为了分隔数据,而不是数据本身的一部分。
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); } } |