c#用OleDb这种方式导入excel并转换为datatable

辅助方法:

   public  void AcquireTwoArray(DataSet ds)
        {

            foreach (DataTable dt in ds.Tables)//遍历所有的DataTable
            {
                foreach (DataRow dr in dt.Rows)//遍历所有的行
                {
                    foreach (DataColumn dc in dt.Columns)//遍历所有的列
                    {
                        Console.Write("{0},{1},{2}", dt.TableName, dc.ColumnName, dr[dc].ToString());//表名,列名,单元格数据


                    }
                }

            }

        }


        public  System.Data.DataSet ExcelSqlConnection(string filepath, string tableName)
        {

            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
            OleDbConnection ExcelConn = new OleDbConnection(strCon);
            try
            {
                string strCom = string.Format("SELECT * FROM [Sheet1$]");
                ExcelConn.Open();
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
                DataSet ds = new DataSet();
                myCommand.Fill(ds, "[" + tableName + "$]");
                ExcelConn.Close();
                return ds;
            }
            catch
            {
                ExcelConn.Close();
                return null;
            }
        }

调用:
string path = AppDomain.CurrentDomain.BaseDirectory + “report.xlsx”;

        Excel1 ex=new Excel1 ();

        string path1 = AppDomain.CurrentDomain.BaseDirectory + "excel1.xls";
        DataSet dse = ex.ExcelSqlConnection(path, "report.xls");
   ex.AcquireTwoArray(dse);

注意:当excel版本不一样时,会弹出外部表不是预期格式错误,只需修改链接字符窜即可
string strCon = “Provider=Microsoft.Ace.OleDb.12.0;” + “data source=” + filepath + “;Extended Properties=’Excel 12.0; HDR=Yes; IMEX=1’”;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值