C# 读取 excel 中 sheet 及数据到DataTable

 public class Utils
    {
        public static DataSet LoadDataFromExcel(string fileName)
        {
            try
            {
                List<string> names = new List<string>();
                System.Data.DataTable dtNames = GetExcelTableName(fileName);
                for (int i = 0; i < dtNames.Rows.Count; i++)
                {
                    if (dtNames.Rows[i]["Table_Name"].ToString() == "_xlnm#_FilterDatabase") continue;
                    names.Add(dtNames.Rows[i]["Table_Name"].ToString());
                }
                string strConn = GetConString(fileName);


                DataSet OleDsExcle = new DataSet();
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleDbDataAdapter OleDaExcel = null; OleConn.Open();
                for (int i = 0; i < names.Count; i++)
                {
                    DataSet dsTmp = new DataSet();
                    String sql = String.Empty;
                    sql += String.Format("SELECT * FROM  [{0}];", names[i]);


                    OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                    OleDaExcel.Fill(dsTmp, names[i]);
                    OleDsExcle.Tables.Add(dsTmp.Tables[0].Copy());


                }
                OleConn.Close();
                return OleDsExcle;
            }
            catch
            {
                return null;
            }
        }
        public static System.Data.DataTable GetExcelTableName(string fileName)
        {
            try
            {
                if (System.IO.File.Exists(fileName))
                {
                    OleDbConnection _ExcelConn = new OleDbConnection(GetConString(fileName));
                    _ExcelConn.Open();
                    System.Data.DataTable _Table = _ExcelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    _ExcelConn.Close();
                    return _Table;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        private static string GetConString(string fileName)
        {
            return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
                                 + fileName + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";

        }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值