CSVFileHelper.cs 5.6 KB
using log4net;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

using System.Windows.Forms;

namespace OnLineStore.Common
{
    public class CSVFileHelper
    {
        public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// 将DataTable中数据写入到CSV文件中
        /// </summary>
        /// <param name="dt">提供保存数据的DataTable</param>
        /// <param name="fileName">CSV的文件路径</param>
        public static void SaveCSV(DataTable dt, string fullPath)
        {
            FileInfo fi = new FileInfo(fullPath);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
            StreamWriter sw = new StreamWriter(fs, 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);
            }
            sw.Close();
            fs.Close();
            DialogResult result = MessageBox.Show("CSV文件保存成功!");
         
        }

       public static string[][] Read(string fullname)
        {
            if (!File.Exists(fullname)) return new string[][] { };
            var lines = File.ReadAllLines(fullname).Skip(1);
            var list=new List<string[]>();
            var builder = new StringBuilder();
            foreach (var line in lines)
            {
                builder=new StringBuilder ();
                var comma = false;
                var array = line.ToCharArray();
                var values = new List<string>();
                var length = array.Length - 1;
                var index = 0;
                while (index < length)
                {
                    var item = array[index++];
                    switch (item)
                    {
                        case ',':
                            if (comma)
                            {
                                builder.Append(item);
                            }
                            else
                            {
                                values.Add(builder.ToString());
                                builder = new StringBuilder();
                            }
                            break;
                        case '"':
                            comma = !comma;
                            break;
                        default:
                            builder.Append(item);
                            break;
                    }
                }
                var count = values.Count;
                if (count == 0) continue;
                list.Add(values.ToArray());
            }
            return list.ToArray();
        }

       //public static List<StoreBagConfig> ReadList(string fullname)
       //{
       //    List<StoreBagConfig> result = new List<StoreBagConfig>();
       //    if (!File.Exists(fullname)) { 
       //        return result; 
       //    }
       //    var lines = File.ReadAllLines(fullname).Skip(1);
       //    var list = new List<string[]>(); 
       //    int index=0;
       //    foreach (var line in lines)
       //    {
       //        var array = line.Split(',');             
       //        var length = array.Length ;

       //        if (length == 5)
       //        {
       //            int col = Int32.Parse(array[0]);
       //            int row = Int32.Parse(array[1]);
       //            int axisPosition = Int32.Parse(array[2]);
       //            int highPosition = Int32.Parse(array[3]);
       //            int lowPosition = Int32.Parse(array[4]);
       //            StoreBagConfig config = new StoreBagConfig();
       //            config.AxisPostion = axisPosition;
       //            config.BagColoum = col;
       //            config.CsvRowIndex = index;
       //            config.HighPostion = highPosition;
       //            config.LowPosition = lowPosition;
       //            config.BagRow = row;
       //            result.Add(config);
       //        }
       //        else
       //        {
       //            LogUtil.error(LOGGER,"读取csv,index="+index+",数据格式不匹配!,line="+line);
       //        }
       //        index++;
       //    }
       //    return result;
       //}
    }
     
}