欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#工具:CSV文件转换帮助类

程序员文章站 2022-07-11 09:38:55
CSV是逗号分隔值格式的文件,其文件以纯文本形式存储表格数据(数字和文本)。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。在C#中有时候需要读取和写入Csv文件,特此封装了一个工具类CsvHelper。特此说一句 ......

csv是逗号分隔值格式的文件,其文件以纯文本形式存储表格数据(数字和文本)。csv文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。在c#中有时候需要读取和写入csv文件,特此封装了一个工具类csvhelper。特此说一句,c#将数据导出到csv文件的速度比较快,有时候导出excel文件很慢的时候可以选择先导出.csv文件,而后再本地用excel软件打开。

csvhelper类主要是利用c#操作csv文件,主要包含2个方法。

dt2csv(参数略):将数据导入到csv文件中

csv2dt(参数略):将csv读入datatable

具体的工具类实现如下:

 

C#工具:CSV文件转换帮助类
using system;
using system.collections.generic;
using system.text;
using system.io;
using system.data;
using system.data.oledb;


namespace core.io
{
    /// <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;
        }

        /// <summary>
        /// csv转换成datatable(oledb数据库访问方式)
        /// </summary>
        /// <param name="csvpath">csv文件路径</param>
        /// <returns></returns>
        public static datatable csvtodatatablebyoledb(string csvpath)
        {
            datatable csvdt = new datatable("csv");
            if (!file.exists(csvpath))
            {
                throw new filenotfoundexception("csv文件路径不存在!");
            }

            fileinfo fileinfo = new fileinfo(csvpath);
            using (oledbconnection conn = new oledbconnection(@"provider=microsoft.jet.oledb.4.0;data source=" + fileinfo.directoryname + ";extended properties='text;'"))
            {
                oledbdataadapter adapter = new oledbdataadapter("select * from [" + fileinfo.name + "]", conn);
                adapter.fill(csvdt);
            }
            return csvdt;
        }

        /// <summary>
        /// csv转换成datatable(文件流方式)
        /// </summary>
        /// <param name="csvpath">csv文件路径</param>
        /// <returns></returns>
        public static datatable csvtodatatablebystreamreader(string csvpath)
        {
            datatable csvdt = new datatable("csv");

            int intcolcount = 0;
            bool blnflag = true;
            datacolumn column;
            datarow row;
            string strline = null;
            string[] aryline;

            using (streamreader reader = new streamreader(csvpath, fileencoding.getencoding(csvpath)))
            {
                while (!string.isnullorempty((strline = reader.readline())))
                {
                    aryline = strline.split(new char[] { ',' });

                    if (blnflag)
                    {
                        blnflag = false;
                        intcolcount = aryline.length;
                        for (int i = 0; i < aryline.length; i++)
                        {
                            column = new datacolumn(aryline[i]);
                            csvdt.columns.add(column);
                        }
                        continue;
                    }

                    row = csvdt.newrow();
                    for (int i = 0; i < intcolcount; i++)
                    {
                        row[i] = aryline[i];
                    }
                    csvdt.rows.add(row);
                }
            }

            return csvdt;
        }

        /// <summary>
        /// datatable 生成 csv
        /// </summary>
        /// <param name="dt">datatable</param>
        /// <param name="csvpath">csv文件路径</param>
        public static void datatabletocsv(datatable dt, string csvpath)
        {
            if (null == dt)
                return;

            stringbuilder csvtext = new stringbuilder();
            stringbuilder csvrowtext = new stringbuilder();
            foreach (datacolumn dc in dt.columns)
            {
                csvrowtext.append(",");
                csvrowtext.append(dc.columnname);
            }
            csvtext.appendline(csvrowtext.tostring().substring(1));

            foreach (datarow dr in dt.rows)
            {
                csvrowtext = new stringbuilder();
                foreach (datacolumn dc in dt.columns)
                {
                    csvrowtext.append(",");
                    csvrowtext.append(dr[dc.columnname].tostring().replace(',', ' '));
                }
                csvtext.appendline(csvrowtext.tostring().substring(1));
            }

            file.writealltext(csvpath, csvtext.tostring(), encoding.default);
        }
    
    }
}
csvhelper