zoukankan      html  css  js  c++  java
  • C#:导入Excel通用类(CSV格式)

    • 一、引用插件LumenWorks.Framework.IO.dll(CsvReader)

         插件下载地址:https://pan.baidu.com/s/1X9Sl4bWTNHJOJb_v-KUndA  提取密码 0az3

    • 二、定义通用接口IExcelData.cs和IDataTransform.cs

      IDataTransform.cs

     public interface IDataTransform { List<Dictionary<string, string>> DataTableToDictionary(DataTable dt); } 

      IExcelData.cs         

    public interface IExcelData : IDataTransform
        {
            /// <summary>
            /// Excel工作薄所有表格转化成DataTable对应字典
            /// </summary>
            Dictionary<string, DataTable> DataTableDictionary { get; }
    
            /// <summary>
            /// Excel工作薄所有表格的名称集合
            /// </summary>
            List<string> SheetNames { get; }
    
            /// <summary>
            /// Excel工作薄所有表格数据集合
            /// </summary>
            List<DataTable> DataTableList { get; }
    
            /// <summary>
            /// 表格数量
            /// </summary>
            int SheetCount { get; }
    
            /// <summary>
            /// Excel文件路径
            /// </summary>
            string FilePath { get; }
    
            /// <summary>
            /// Excel流
            /// </summary>
            Stream ExcelStream { get; }
    
            /// <summary>
            /// Excel文件类型
            /// </summary>
            ExcelType ExcelType { get; }
    
            /// <summary>
            /// 获取Excel第一列数据集合
            /// </summary>
            List<Dictionary<string, string>> GetFirstRecords();
    
            /// <summary>
            /// 执行方法
            /// </summary>
            void Load();
        }
    • 三、定义通用类CsvData.cs

         CsvData.cs

    public class CsvData : IExcelData
        {
            #region 属性值
            public Dictionary<string, DataTable> DataTableDictionary
            {
                get { throw new NotImplementedException(); }
            }
            public List<string> SheetNames
            {
                get { throw new NotImplementedException(); }
            }
            public List<DataTable> DataTableList
            {
                get { throw new NotImplementedException(); }
            }
            public int SheetCount
            {
                get { throw new NotImplementedException(); }
            }
            private string m_filePath;
            public string FilePath
            {
                get { return m_filePath; }
            }
            private Stream m_stream;
            public Stream ExcelStream
            {
                get { return m_stream; }
            }
            public ExcelType ExcelType
            {
                get { throw new NotImplementedException(); }
            }
            private List<Dictionary<string, string>> m_Records;
            public List<Dictionary<string, string>> Records { get { return m_Records; } }
            #endregion
            #region 构造
            public CsvData(string path)
            {
                m_filePath = path;
            }
            public CsvData(Stream stream)
            {
                m_stream = stream;
            }
            #endregion
            #region 方法
            public List<Dictionary<string, string>> DataTableToDictionary(DataTable dt)
            {
                throw new NotImplementedException();
            }
    
            public List<Dictionary<string, string>> GetFirstRecords()
            {
                return m_Records;
            }
    
            /// <summary>
            /// 执行方法
            /// </summary>
            public void Load()
            {
                if (!string.IsNullOrEmpty(m_filePath))
                    Load(m_filePath);
                else
                    Load(m_stream);
            }
    
            /// <summary>
            /// 执行方法
            /// </summary>
            /// <param name="m_filePath">文件路径</param>
            private void Load(string m_filePath)
            {
                using (FileStream fs=File.Open(m_filePath,FileMode.Open,FileAccess.Read))
                {
                    using (StreamReader sr=new StreamReader(fs))
                    {
                        using (CsvReader csvReader=new CsvReader(sr,false))
                        {
                            m_Records = new List<Dictionary<string, string>>();
                            int count = csvReader.FieldCount;
                            string[] keys = new string[count];
                            string[] array = new string[count];
                            IEnumerator rows = csvReader.GetEnumerator();
                            try
                            {
                                while (rows.MoveNext())
                                {
                                    if (csvReader.CurrentRecordIndex==0)
                                    {
                                        keys = (string[])rows.Current;
                                        for (int i = 0; i < keys.Length; i++)
                                        {
                                            string s = keys[i].Replace('"', ' ').Trim();
                                            keys[i] = s;
                                        }
                                    }
                                    else
                                    {
                                        array = (string[])rows.Current;
                                        Dictionary<string, string> dic = new Dictionary<string, string>();
                                        for (int i = 0; i < keys.Length; i++)
                                        {
                                            dic.Add(keys[i], array[i]);
                                        }
                                        m_Records.Add(dic);
                                    }
                                }
                            }
                            catch
                            {
                                throw;
                            }
                        }
                    }
                }
            }
    
            /// <summary>
            /// 执行方法
            /// </summary>
            /// <param name="m_stream">文件流</param>
            private void Load(Stream m_stream)
            {
                using (StreamReader sr=new StreamReader(m_stream))
                {
                    while (true)
                    {
                        var line = sr.ReadLine();
                        if (line=="")
                        {
                            break;
                        }
                    }
                    for (int i = 0; i < 2; i++)
                    {
                        sr.Read();
                    }
                    using (CsvReader csvReader=new CsvReader(sr,false))
                    {
                        m_Records = new List<Dictionary<string, string>>();
                        int count = csvReader.FieldCount;
                        string[] keys = new string[count];
                        string[] array = new string[count];
                        IEnumerator rows = csvReader.GetEnumerator();
                        try
                        {
                            while (rows.MoveNext())
                            {
                                if (csvReader.CurrentRecordIndex==0)
                                {
                                    keys = (string[])rows.Current;
                                    for (int i = 0; i < keys.Length; i++)
                                    {
                                        string s = keys[i].Replace('"', ' ').Trim();
                                        keys[i] = s;
                                    }
                                }
                                else
                                {
                                    array = (string[])rows.Current;
                                    Dictionary<string, string> dic = new Dictionary<string, string>();
                                    for (int i = 0; i < keys.Length; i++)
                                    {
                                        dic.Add(keys[i], array[i]);
                                    }
                                    m_Records.Add(dic);
                                }
                            }
                        }
                        catch
                        {
                            
                            throw;
                        }
                    }
                }
            }
            #endregion
        }

    注:以上的通用类将CSV格式的Excel转换成DataTable,识别Excel中的首列为数据库表的列项,会提取这一列如果判断匹配,这个就是业务代码了,以上未提供,根据需求自己编写就好。

    原著:清风一人醉 http://www.cnblogs.com/W--Jing/

    以上方法可以个人分享研究!

    不可做商业项目,违者必究!

  • 相关阅读:
    Object-C支持多继承吗?可以实现多个接口吗?Category是什么?
    Action类为何要继承ActionSupport
    JAVA中的File类
    Oracle中奇怪的【不等于号】
    Oracle中INSTR、SUBSTR和NVL的用法
    【ERROR】Oracle11g两个监听同名进程的故障
    【ERROR】EXP-00091
    【ERROR】while loading shared libraries: /u01/app/oracle/product/11.2.0/lib/libclntsh.so.11.1: cannot
    【js】appendChild
    【js】正则表达式(II)
  • 原文地址:https://www.cnblogs.com/W--Jing/p/8434938.html
Copyright © 2011-2022 走看看