首页 > 代码库 > 数据流读、写、删、修CSV文件

数据流读、写、删、修CSV文件

使用CSV文件记录数据

   class CSVFileOperation    {        private string fileFullName;//CSV文件路径,包括文件名、扩展名            public CSVFileOperation(string fileFullName)        {            this.fileFullName = fileFullName;        }        //注意FileMode:Create和CreateNew的区别        public void WriteFile(DataTable dt)        {                        FileStream fs = new FileStream(fileFullName, System.IO.FileMode.Create, System.IO.FileAccess.Write);            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);            string data = http://www.mamicode.com/"";            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++)                {                    data += dt.Rows[i][j].ToString();//将数据均已字符串个数输出                    if (j < dt.Columns.Count - 1)//每行末不需要加","                    {                        data += ",";                    }                }                sw.WriteLine(data);            }            sw.Close();            fs.Close();                    }        /// <summary>        /// 创建一个新的CSV文件,只包含列名,表格的行数为0        /// </summary>        /// <param name="colNames">包含列名的数组,列的个数等于数组的长度</param>        public void CreateNewFile(string[] colNames)        {            if (File.Exists(fileFullName))            {                DialogResult result = MessageBox.Show("您想创建的文件已经存在,是否要覆盖?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);                if (!(result == DialogResult.Yes))                {                    MessageBox.Show("退出创建新文件", "提示");                    return;                }            }            FileStream fs = new FileStream(fileFullName, System.IO.FileMode.Create, System.IO.FileAccess.Write);            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);            string data = http://www.mamicode.com/"";            for (int j = 0; j < colNames.Length; j++)            {                data += colNames[j].ToString();                if (j < colNames.Length - 1)                {                    data += ",";                }            }            sw.WriteLine(data);            sw.Close();            fs.Close();            MessageBox.Show("创建了一个新CSV文件,仅包括标题行!");        }        /// <summary>        /// 将CSV文件的数据读取到DataTable中        /// </summary>        /// <returns>将文件数据以DataTable形式返回</returns>        public DataTable ReadFileData()        {                        DataTable dt = new DataTable();            FileStream fs = new FileStream(fileFullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);            string strLine = "";//记录每次读取的一行记录            string[] aryLine;//记录每行记录中的各字段内容            int columnCount = 0;//标示列数            bool IsFirst = true; //标示是否是读取的第一行            while ((strLine = sr.ReadLine()) != null)//逐行读取CSV中的数据            {                aryLine = strLine.Split(,);//逗号分割字符串                if (IsFirst == true)                {                    IsFirst = false;                    columnCount = aryLine.Length;//创建列                                        for (int i = 0; i < columnCount; i++)                    {                        DataColumn dc = new DataColumn(aryLine[i]);                        dt.Columns.Add(dc);                    }                }                else                {                    DataRow dr = dt.NewRow();                    for (int j = 0; j < columnCount; j++)                    {                        dr[j] = aryLine[j];                    }                    dt.Rows.Add(dr);                }            }            sr.Close();            fs.Close();            return dt;        }        public int GetColsNum()        {            FileStream fs = new FileStream(fileFullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);            string strLine = "";//记录每次读取的一行记录            string[] aryLine;//记录每行记录中的各字段内容            int columnCount = 0;//标示列数            if ((strLine = sr.ReadLine()) != null)            {                aryLine = strLine.Split(,);//逗号分割字符串                                columnCount = aryLine.Length;//创建列                                              }            sr.Close();            fs.Close();            return columnCount;        }        /// <summary>        /// 得到当前文件的行数,不含标题行        /// </summary>        /// <returns>行数</returns>        public int  GetRowsNum()        {            FileStream fs = new FileStream(fileFullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);            int RowCount = 0;//标示列数            while (sr.ReadLine() != null)            {                RowCount++;            }            sr.Close();            fs.Close();            return RowCount - 1;//实际行数不包含标题行        }        /// <summary>        /// 在存在的文件后面添加一行        /// </summary>        /// <param name="str">添加行的字符数组</param>        /// <returns>返回当前操作是否成功</returns>        public bool AppendLine(string[] str)        {            //注意:FileMode打开文件的方式修改为Append                if (File.Exists(fileFullName) == false)//如果文件不存在则创建新的文件            {                return false;            }            FileStream fs = new FileStream(fileFullName, System.IO.FileMode.Append, System.IO.FileAccess.Write);            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);            string data = http://www.mamicode.com/"";            for (int j = 0; j < str.Length; j++)            {                data += str[j].ToString();                if (j < str.Length - 1)                {                    data += ",";                }            }            sw.WriteLine(data);            sw.Close();            fs.Close();            return true;        }        /// <summary>        /// 删除行        /// </summary>        /// <param name="rowNum">实际行数(1...总行数)</param>        /// <returns></returns>        public bool DeleteLine(int rowNum)        {            if (rowNum > this.GetRowsNum() || rowNum < 1)            {                return false;            }            DataTable dt = this.ReadFileData();            dt.Rows.RemoveAt(rowNum - 1);//删除rowNum行            try            {                this.WriteFile(dt);                return true;            }            catch (Exception ex)            {                MessageBox.Show(ex.Message, "异常");                return false;            }        }        /// <summary>        ///         /// </summary>        /// <param name="rowNum"></param>        /// <param name="str"></param>        /// <returns></returns>        public bool ModificationLine(int rowNum, string[] str)        {            if (rowNum > this.GetRowsNum() || rowNum < 1)            {                return false;            }            DataTable dt = this.ReadFileData();            dt.Rows.RemoveAt(rowNum - 1);//删除rowNum行            DataRow dr = dt.NewRow();            for (int i = 0; i < str.Length; i++)            {                dr[i] = str[i];            }            dt.Rows.InsertAt(dr, rowNum - 1);                       try            {                this.WriteFile(dt);                return true;            }            catch (Exception ex)            {                MessageBox.Show(ex.Message, "异常");                return false;            }        }    }

 

数据流读、写、删、修CSV文件