把excel表当成数据源,查询数据,

 最近在做将excel表的数据导出数据库,于是自己查了下资料方法介绍了很多种,尝试自己写了数据的查询的domel,写的比较简陋。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var path = @"C:\Users\Administrator\Desktop\test.xlsx";
            dataGridView1.DataSource = null; //每次打开清空内容         
            DataTable dt = Getdata(path, "Sheet1").Tables[0];
            ///加载到dataGridView中
            dataGridView1.DataSource = dt;
            ///获取所有的工作薄
            List<string> tableName = GetTableName(path);
            ///DataTable转化成集合
            IList<Man> users = ModelConvertHelper<Man>.ConvertToModel(dt);
        }
    
        /// <summary>
        ///连接数据源
        /// </summary>
        /// <returns></returns>
        public OleDbConnection OleDbConnection(string path)
        {
            //判断文件后缀         
            string fileSuffix = System.IO.Path.GetExtension(path);
            if (string.IsNullOrEmpty(fileSuffix))
            return null;
            string connString = "";
            //判断Excel文件是2003版本还是2007版本
            if (fileSuffix == ".xls")
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
            else
                connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
            OleDbConnection conn = new OleDbConnection(connString);
            conn.Open();
            return conn;
                       
        }
        /// <summary>
        /// 读取数据源
        /// </summary>
        /// <param name="path">excel文件</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public DataSet Getdata(string path, string tableName)
        {
            OleDbConnection conn = OleDbConnection(path);
            using (DataSet ds = new DataSet())
            {
                try
                {
                    
                    string sql_select = " SELECT * FROM" + "["+ tableName + "$]";
                    using (OleDbDataAdapter cmd = new OleDbDataAdapter(sql_select, conn))
                    {
                        cmd.Fill(ds);
                        conn.Close();
                    }
                    if (ds == null || ds.Tables.Count <= 0) return null;
                }
                catch (Exception ex)
                {             
                    Console.WriteLine("Getdata()", ex.Message);
                }
                return ds;
            }
        }
        /// <summary>
        ///  获取工作表名
        /// </summary>
        /// <param name="path">excel文件</param>
        /// <returns></returns>
        public List<string> GetTableName(string path)
        {
            List<string> tableName = new List<string>();
            try
            {
                OleDbConnection conn = OleDbConnection(path);
                DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                for (int i = 0; i < sheetNames.Rows.Count; i++)
                {
                    DataRow row = sheetNames.Rows[i];
                    for (int j = 0; j < row.ItemArray.Length; j++)
                    {
                        var type = row.ItemArray[j].GetType().Name;
                        if (type != "DBNull")
                        {
                            string name = Convert.ToString(row.ItemArray[j]);
                            if (name.EndsWith("$"))
                            {
                                tableName.Add(name);
                            }
                        }
                    }
                }
                conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetTableName()", ex.Message);
            }
            return tableName;
        }
        public class ModelConvertHelper<T> where T : new()  // 此处一定要加上new()
        {
            public static IList<T> ConvertToModel(DataTable dt)
            {
                IList<T> ts = new List<T>();// 定义集合
                Type type = typeof(T); // 获得此模型的类型
                string tempName = "";
                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    // 获得此模型的公共属性
                    PropertyInfo[] propertys = t.GetType().GetProperties();
        
                    foreach (PropertyInfo pi in propertys)
                    {
                        tempName = pi.Name;
                        // 检查DataTable是否包含此列
                        if (dt.Columns.Contains(tempName))
                        {
                            if (!pi.CanWrite) continue;
                            object value = dr[tempName];
                            if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                        }
                    };                   
                    ts.Add(t);
                }
                return ts;
            }
        }   
    }
    public class Man
    {
        public double Id { get; set; }

        public string Name { get; set; }
        public double Age { get; set; }
    }
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值