根据Excel文件创建数据集

来源:互联网 发布:绘画软件 知乎 编辑:程序博客网 时间:2024/05/16 15:54

using System.Data.OleDb;
using System.Web;

 

 

         /// <summary>
        /// 此处写为一个静态方法
        /// 根据Excel文件创建数据集
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static DataSet CreateExcelDataSet(String filename)
        {
            HttpContext content = HttpContext.Current;
            string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + content.Server.MapPath( filename) + ";Extended Properties=Excel 8.0";
            OleDbConnection thisconnection = new OleDbConnection(conn);
            thisconnection.Open();
            string Sql = "select * from [data upload$]";
            OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, thisconnection);
            DataSet ds = new DataSet();
            mycommand.Fill(ds, "data");
            thisconnection.Close();
            return ds;
        }

 

注意:因为调用了content.Server.MapPath()方法,所以传入的文件路径可以是一个相对于此文件的路径,也可以一个网站绝对根路径。

原创粉丝点击