将Execl以数据源的方式快速读取到DataTable中

来源:互联网 发布:黑莓classic转制软件 编辑:程序博客网 时间:2024/06/16 03:07
 #region 读取文件,以数据源的方式(适合03甚至更高的Execl版本)
    public DataSet ExcelToDS(string Path)
    {
        string strFileExtent = System.IO.Path.GetExtension(Request["FilePath"].ToString()).ToLower();//文件扩展名
        string strConn = "";
        if (strFileExtent == ".xlsx")
        {
            strConn = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source='" + Path + "';Extended Properties='Excel 12.0;HDR=yes;IMEX=1'";
        }
        else if (strFileExtent == ".xls")
        {
            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + Path + "';Extended Properties='Excel 8.0;HDR=1;IMEX=1'";
        }
        OleDbConnection conn = new OleDbConnection(strConn);
        conn.Open();
        string strExcel = "";
        OleDbDataAdapter myCommand = null;
        DataSet ds = null;
        strExcel = "select * from [sheet1$]";
        myCommand = new OleDbDataAdapter(strExcel, strConn);
        ds = new DataSet();
        myCommand.Fill(ds, "table1");
        myCommand.Dispose();
        conn.Close();
        return ds;
    }
    #endregion
原创粉丝点击