c# 读写操作csv文件

1.把cvs读取到dt中

        /// <summary>
        /// 把csv读到dt中
        /// </summary>
        /// <param name="file">csv文件路径</param>
        /// <returns>dt</returns>
       public static DataTable ReadDataFromCsv(string file)
        {
            DataTable dt = null;

            if (File.Exists(file))
            {
                #region 如果文件存在
                dt = new DataTable();
                FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read);
              
                StreamReader sr = new StreamReader(fs,Encoding.Default);

                    string head = sr.ReadLine();
                    string[] headNames = head.Split(',');
                    for (int i = 0; i < headNames.Length; i++)
                    {
                        dt.Columns.Add(headNames[i], typeof(string));
                    }
                    while (!sr.EndOfStream)
                    {
                        #region ==循环读取文件==
                        string lineStr = sr.ReadLine();
                        if (lineStr == null || lineStr.Length == 0)
                            continue;
                        string[] values = lineStr.Split(',');
                        #region ==添加行数据==
                        DataRow dr = dt.NewRow();
                        for (int i = 0; i < values.Length; i++)
                        {
                            dr[i] = values[i];
                        }
                        dt.Rows.Add(dr);
                        #endregion
                        #endregion
                    }
                    fs.Close();
                    sr.Close();
                #endregion
            }
            return dt;
        }

2.从dt中写入csv

 static public void toCsv(DataTable dt, string fullPath)
       {
           FileInfo fi = new FileInfo(fullPath);
           if (!fi.Directory.Exists)
           {
               fi.Directory.Create();
           }
           FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
          StreamWriter sw = new StreamWriter(fs, 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);
         }
         sw.Close();
         fs.Close();
       }

猜你喜欢

转载自blog.csdn.net/qq_38396292/article/details/89956788