您现在的位置是:首页 > 文章详情文章详情

C#读写csv文件

会飞的猪 2017-12-13 730人已围观

简介白码驿站是一个面向开发者的知识共享社区,专注于为开发者打造一个纯净的技术交流社区(源码下载,免费在线图片压缩,jquery插件,插件下载,JS/CSS在线压缩。)-白码驿站

CSV(逗号分隔值文件格式)

        逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。通常,所有记录都有完全相同的字段序列。通常都是纯文本文件 -- 引用百度百科。


        当一个csv文件用记事本打开后, 我们会发现文本是以“a”,“b”,“c”,“d”这种格式存储的,既然这样, 那我们操作起来就方便多了,下面就来看看应该怎样去读取.csv文件。


生成DataTable转换为.csv文件

                                        
        /// <summary>
        /// 生成csv文件
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="fileName">文件名</param>
        /// <param name="filePath">要存放的路径</param>
        /// <returns></returns>
        public static bool CreateCsvFile(DataTable dt, string fileName, string filePath)
        {
            try
            {
                filePath = filePath + "\\" + fileName;
                using (FileStream fileWrite = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fileWrite, System.Text.Encoding.UTF8))
                    {
                        string data = "";
                        //写出列名称
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            data += dt.Columns[i].ColumnName.ToString();
                            if (i < dt.Columns.Count - 1)
                            {
                                data += ",";
                            }
                        }
                        sw.WriteLine(data);
                        //写出各行数据
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            data = "";
                            for (int j = 0; j < dt.Columns.Count; j++)
                            {
                                string str = dt.Rows[i][j].ToString();
                                //替换英文冒号 英文冒号需要换成两个冒号
                                str = str.Replace("\"", "\"\"");
                                //含逗号 冒号 换行符的需要放到引号中
                                if (str.Contains(',') || str.Contains('"') || str.Contains('\r') || str.Contains('\n'))
                                {
                                    str = string.Format("\"{0}\"", str);
                                }

                                data += str;
                                if (j < dt.Columns.Count - 1)
                                {
                                    data += ",";
                                }
                            }
                            sw.WriteLine(data);
                        }
                    }
                }
                return true;
            }
            catch (Exception e)
            {

                string mess = e.Message;
            }
            return false;
        }
                                



将.csv文件读取到DataTable中去

                                        
        /// <summary>
        /// 将CSV文件的数据读取到DataTable中
        /// </summary>
        /// <param name="fileName">CSV文件路径</param>
        /// <returns>返回读取了CSV数据的DataTable</returns>
        public static DataTable OpenCSV(string filePath)
        {
            DataTable dt = new DataTable();
            try
            {
                //读取csv文件
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        //记录每次读取的一行记录
                        string strLine = "";
                        //记录每行记录中的各字段内容
                        string[] aryLine = null;
                        string[] tableHead = null;
                        //标示列数
                        int columnCount = 0;
                        //标示是否是读取的第一行
                        bool IsFirst = true;
                        //逐行读取CSV中的数据
                        while ((strLine = sr.ReadLine()) != null)
                        {
                            if (IsFirst == true)
                            {
                                tableHead = strLine.Split(',');
                                IsFirst = false;
                                columnCount = tableHead.Length;
                                //创建列
                                for (int i = 0; i < columnCount; i++)
                                {
                                    DataColumn dc = new DataColumn(tableHead[i]);
                                    dt.Columns.Add(dc);
                                }
                            }
                            else
                            {
                                aryLine = strLine.Split(',');
                                DataRow dr = dt.NewRow();
                                for (int j = 0; j < columnCount; j++)
                                {
                                    dr[j] = aryLine[j];
                                }
                                dt.Rows.Add(dr);
                            }
                        }
                        if (aryLine != null && aryLine.Length > 0)
                        {
                            dt.DefaultView.Sort = tableHead[0] + " " + "asc";
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                string mess = ex.Message;
            }
            return dt;
        }
                                

Tags: C# 、 文件操作

很赞哦! (1)

评 论

点击排行

系统处理中...