CSV是一种通用的、相对简单的文件格式,常用于程序之间转移表格数据。CSV文件默认以英文逗号做为列分隔符,换行符作为行分隔符。
以文本方式打开csv会发现其实列是由“,”分割。
C#读写CSV的常用写法,在这里写个笔记。
一、读取CSV返回DataTable /// <summary> /// 读取CSV /// </summary> /// <param
name="filePath">CSV路径</param> /// <param
name="n">表示第n行是字段title,第n+1行是记录开始</param> /// <returns></returns> public static
System.Data.DataTable CsvToDataTable(string filePath, int n) {
System.Data.DataTable dt = new System.Data.DataTable(); StreamReader reader =
new StreamReader(filePath, System.Text.Encoding.Default, false); int m = 0;
while (!reader.EndOfStream) { m = m + 1; string str = reader.ReadLine();
string[] split = str.Split(','); if (m == n) { System.Data.DataColumn column ;
//列名 for (int c = 0; c < split.Length;c++ ) { column = new
System.Data.DataColumn(); column.DataType =
System.Type.GetType("System.String"); column.ColumnName = split[c]; if
(dt.Columns.Contains(split[c])) //重复列名处理 column.ColumnName = split[c] + c;
dt.Columns.Add(column); } } if (m >= n + 1) { System.Data.DataRow dr =
dt.NewRow(); for (int i = 0; i < split.Length; i++) { dr[i] = split[i]; }
dt.Rows.Add(dr); } } reader.Close(); return dt; }二、DataTable数据写入CSV ///
<summary> /// DataTable导出为CSV /// </summary> /// <param
name="dt">DataTable</param> /// <param name="strFilePath">路径</param>
public static void dataTableToCsvT(System.Data.DataTable dt, string
strFilePath) { if (dt == null || dt.Rows.Count == 0)
//确保DataTable中有数据 return; string strBufferLine = "";
StreamWriter strmWriterObj = new StreamWriter(strFilePath, false,
System.Text.Encoding.Default); //写入列头 foreach
(System.Data.DataColumn col in dt.Columns) strBufferLine +=
col.ColumnName + ","; strBufferLine = strBufferLine.Substring(0,
strBufferLine.Length - 1); strmWriterObj.WriteLine(strBufferLine);
//写入记录 for (int i = 0; i < dt.Rows.Count; i++) {
strBufferLine = ""; for (int j = 0; j <
dt.Columns.Count; j++) { if (j > 0)
strBufferLine += ","; strBufferLine +=
dt.Rows[i][j].ToString().Replace(",", ""); //因为CSV文件以逗号分割,在这里替换为空
} strmWriterObj.WriteLine(strBufferLine); }
strmWriterObj.Close(); }
热门工具 换一换