本文实例讲述了C#操作CSV文件类。分享给大家供大家参考。具体分析如下:
这个C#类用于转换DataTable为CSV文件、CSV文件转换成DataTable,如果需要进行CSV和DataTable之间进行转换,使用这个类非常合适。
using System.Data; using System.IO; namespace DotNet.Utilities { ////// CSV文件转换类 /// public static class CsvHelper { ////// 导出报表为Csv /// /// DataTable /// 物理路径 /// 表头 /// 字段标题,逗号分隔 public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname) { try { string strBufferLine = ""; StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8); strmWriterObj.WriteLine(tableheader); strmWriterObj.WriteLine(columname); 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(); } strmWriterObj.WriteLine(strBufferLine); } strmWriterObj.Close(); return true; } catch { return false; } } ////// 将Csv读入DataTable /// /// csv文件路径 /// 表示第n行是字段title,第n+1行是记录开始 public static DataTable csv2dt(string filePath, int n, DataTable dt) { StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false); int i = 0, m = 0; reader.Peek(); while (reader.Peek() > 0) { m = m + 1; string str = reader.ReadLine(); if (m >= n + 1) { string[] split = str.Split(','); System.Data.DataRow dr = dt.NewRow(); for (i = 0; i < split.Length; i++) { dr[i] = split[i]; } dt.Rows.Add(dr); } } return dt; } } }
希望本文所述对大家的C#程序设计有所帮助。