using LumenWorks.Framework.IO.Csv;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Text.Encodings;

namespace Mall.Common
{
    public class CSVHelper
    {
        /// <summary>
        /// 获取路径下的.csv文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public DataTable GetStream(string FilePath)
        {
            FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            Stream stream = new MemoryStream(bytes);
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            return GetData(stream, Encoding.GetEncoding("GB2312"));
        }

        /// <summary>
        /// 将.csv文件转换成DataTable
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        private DataTable GetData(Stream stream, Encoding enc)
        {
            using (stream)
            {
                using StreamReader input = new StreamReader(stream, enc);
                using CsvReader csv = new CsvReader(input, true);
                DataTable dt = new DataTable();
                //第一行字段数量
                int columnCount = csv.FieldCount;
                //标题数组
                string[] headers = csv.GetFieldHeaders();
                //循环添加标题行
                for (int i = 0; i < columnCount; i++)
                {
                    dt.Columns.Add(headers[i]);
                }
                //循环添加列数据
                while (csv.ReadNextRecord())
                {
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < columnCount; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(csv[i]))
                        {
                            dr[i] = csv[i];
                        }
                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
        }
    }
}

