ASP.NET導入Excel

  public DataSet ExcelToDS(string Path)
        {
            try
            {
                string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";Extended Properties='Excel 12.0'";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                string strExcel = "";
                OleDbDataAdapter myCommand = null;
                DataSet ds = null;


                try
                {
                    strExcel = "select * from [工作表1$]";
                    myCommand = new OleDbDataAdapter(strExcel, strConn);
                    ds = new DataSet();
                    myCommand.Fill(ds);
                }
                catch
                {
                    strExcel = "select * from [Sheet1$]";
                    myCommand = new OleDbDataAdapter(strExcel, strConn);
                    ds = new DataSet();
                    myCommand.Fill(ds);


                }
                return ds;
            }
            catch(Exception ex)
            {
                pm.ShowMSG(ex.Message);
                return new DataSet();
            }
          }
調用:
  string ppath = FileUpload1.PostedFile.FileName;
        if (File.Exists(ppath))
        {
            string FileExt = Path.GetExtension(ppath);

            string[] FileExt_set = { ".xls", ".xlsx" };
            if (FileExt != FileExt_set[0] && FileExt != FileExt_set[1])
            {
               pm.ShowMSG("選擇的文件不是Excel文件,請重新選擇.");
            }
            else
            {
                DataSet ds = ExcelToDS(ppath);
                GridView1.DataSource = ds.Tables[0].DefaultView;
                GridView1.DataBind();
            }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章