C#操作CSV文件类实例
程序员文章站
2023-12-04 17:30:34
本文实例讲述了c#操作csv文件类。分享给大家供大家参考。具体分析如下:
这个c#类用于转换datatable为csv文件、csv文件转换成datatable,如果需要进...
本文实例讲述了c#操作csv文件类。分享给大家供大家参考。具体分析如下:
这个c#类用于转换datatable为csv文件、csv文件转换成datatable,如果需要进行csv和datatable之间进行转换,使用这个类非常合适。
using system.data; using system.io; namespace dotnet.utilities { /// <summary> /// csv文件转换类 /// </summary> public static class csvhelper { /// <summary> /// 导出报表为csv /// </summary> /// <param name="dt">datatable</param> /// <param name="strfilepath">物理路径</param> /// <param name="tableheader">表头</param> /// <param name="columname">字段标题,逗号分隔</param> 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; } } /// <summary> /// 将csv读入datatable /// </summary> /// <param name="filepath">csv文件路径</param> /// <param name="n">表示第n行是字段title,第n+1行是记录开始</param> 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#程序设计有所帮助。
上一篇: cad打印预览显示不全怎么办?