功能描述:
- 集合转换为csv数据
- DataSe转换为csv数据
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace IM.Common { /// <summary> /// csv操作 /// <para>创建作者:changjin</para> /// <para>创建日期:2011/06/17</para> /// </summary> public class CsvHelper { public static string _seperator = ","; public static string _bracer = """; public static string _newline = " "; public static string _regex_special = ".*[, "].*"; /// <summary> /// 集合转换为csv数据 /// <para>创建作者:changjin</para> /// <para>创建日期:2011/06/17</para> /// </summary> /// <param name="list">数据集合,行、列</param> /// <returns>csv数据</returns> public static string ToCsvData(List<List<string>> list) { string temp = string.Empty; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (List<string> row in list) { for (int i = 0; i < row.Count; i++) { temp = row[i]; temp = (temp != null ? temp : ""); if (i != 0) { sb.Append(_seperator); } if (temp.Contains(_seperator) || temp.Contains(_bracer) || temp.Contains(_newline)) { if (temp.Contains(_bracer)) { temp = temp.Replace(_bracer, _bracer + _bracer); } if (temp.Contains(_newline)) { temp = temp.Replace(_newline, "<br/>"); } sb.Append(_bracer + temp + _bracer); } else { sb.Append(temp); } if (i == row.Count - 1) { sb.Append(_newline); } } } return sb.ToString(); } /// <summary> /// DataSe转换为csv数据 /// <para>创建作者:changjin</para> /// <para>创建日期:2011/06/17</para> /// </summary> /// <param name="ds">数据集</param> /// <returns>csv数据</returns> public static string ToCsvData(DataSet ds) { List<List<string>> list = new List<List<string>>(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null) { DataTable dt = ds.Tables[0]; List<string> columnNameList = new List<string>(); //添加列 if (dt.Columns.Count > 0) { foreach (DataColumn column in dt.Columns) { columnNameList.Add(column.ColumnName); } list.Add(columnNameList); } //迭代添加行记录 foreach (DataRow row in dt.Rows) { List<string> rowData = new List<string>(); foreach (string columnName in columnNameList) { rowData.Add(Convert.ToString(row[columnName])); } list.Add(rowData); } } return ToCsvData(list); } } }