自用 .net C# CSV文件写入读取工具类

using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace AddrList.Common
{
    public class CsvHelper
    {
        /// <summary>
        /// 写入CSV
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="dt">要写入的内存表</param>
        /// <returns>是否写入成功</returns>
        public static bool WriteCSV(string fileName, DataTable dt)
        {
            FileStream fs = null;
            StreamWriter sw = null;

            try
            {
                if (File.Exists(fileName)) File.Delete(fileName);

                fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.UTF8);

                sw.WriteLine(string.Join(",", dt.Columns.Cast<DataColumn>().Select(m => m.ColumnName)));

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sw.WriteLine(string.Join(",", dt.Rows[i].ItemArray.Select(m =>
                    {
                        if (m is string && new Regex(@"^\d+$").IsMatch(m.ToString().Trim()))
                        {
                            m = $"'{m}";
                        }
                        //else if (m is DateTime time)
                        //{
                        //    m = time.ToString("yyyy-MM-dd HH:mm:ss");
                        //}

                        return m?.ToString();
                    })));
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                sw?.Close();
                fs?.Close();
            }

            return true;
        }

        /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="fileName">文件路径</param>
        public static DataTable ReadCSV(string fileName)
        {
            DataTable dt = new DataTable();

            FileStream fs = null;
            StreamReader sr = null;

            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                sr = new StreamReader(fs, Encoding.UTF8);

                //记录每次读取的行记录
                string strLine;

                //逐行读取
                while ((strLine = sr.ReadLine()?.Trim()) != null)
                {
                    string[] arrLine = strLine.Split(new[] { ',' });
                    if (dt.Columns.Count == 0) //表头
                    {
                        dt.Columns.AddRange(arrLine.Select(m => new DataColumn(m)).ToArray());
                    }
                    else //表内容
                    {
                        DataRow dataRow = dt.NewRow();
                        dataRow.ItemArray = arrLine;

                        dt.Rows.Add(dataRow);
                    }
                }
            }
            finally
            {
                sr?.Close();
                fs?.Close();
            }

            return dt;
        }
    }
}

  

posted @ 2023-04-13 08:48  你好创造者  阅读(142)  评论(0编辑  收藏  举报