读取Excel里面的内容转为DataTable

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;

namespace ExcelRead
{
    class ExcelHelper
    {
        private static string excelConstr;
        private OleDbConnection conn = null;//操作数据库
        private OleDbDataAdapter ada = null;//填充dataset
        public ExcelHelper(string path)
        {
            excelConstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties = Excel 12.0";
            if (conn == null || conn.State == ConnectionState.Closed)
            {
                conn = new OleDbConnection(excelConstr);
            }
        }

        public DataTable GetDataSource(string sheetName)
        {
            DataTable dt = new DataTable();
            string sql = string.Empty;
            sql = "select * from [" + sheetName + "]";
            dt = GetDT(sql);
            return dt;
        }

        /// <summary>
        /// 获取excel数据
        /// </summary>
        /// <param name="sql">用于查询的sql</param>
        /// <returns></returns>
        public DataTable GetDT(string sql)
        {
            DataSet ds = new DataSet();
            try
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                ada = new OleDbDataAdapter(sql, conn);
                ada.Fill(ds);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }
            return ds.Tables[0];
        }
    }
}

  

//获取Excel表里Sheet1的数据
//调用 ExcelHelper _excelhelper = new ExcelHelper("Excel文件路径"); //Excel的sheet名称,后面要跟$符号 _excelhelper.GetDataSource("Sheet1$");

  

猜你喜欢

转载自www.cnblogs.com/macT/p/9889025.html