[轉]C# web 讀取Excel檔案

來源:互聯網
上載者:User

標籤:ext   int   get   string   檔案   c   

項目中總是遇到要整理基礎資料的問題,少量的資料還好說,如果資料量大的話,這無疑會增加項目開發的用時,拖延交期。

那麼我們會讓客戶自己去整理基礎資料,但是問題是,客戶整理的資料怎寫入系統呢?我們一般會採用excel檔案,給定客戶格式,讓其按照格式整理,這樣我們就可以匯入資料庫了,但是在使用的過程中又會產生一些基礎資料,我們不可能會再次去協助使用者匯入資料,那麼這個時候,我們就需要用到一個功能,那就是把excel檔案匯入到資料庫中,那麼現在我們就來實現這個功能。

//=====================================================================
// 蘇州塔西亞軟體有限公司 
// 建立人: Aple
// 日 期: 2010-09-23
// 描 述: 讀取excel資料
// QQ群: asp.net(C#)技術交流 71436018
// 版 本: 1.0.0.0
//=====================================================================

首先在頁面上放3個控制項,一個FileUpload(ID:FileUpload1),一個button(ID:btnRead),一個gridview(ID:GridView1),首先說明下3個控制項的作用,

第一個 FileUpload1:用來讓使用者選擇資料來源excel的

第二個 btnRead:選擇好資料來源以後,讀取資料按鈕

第三個 GridView1:顯示資料控制項,把剛剛讀取的資料顯示出來

下面貼出方法:

   #region 讀取excel資料
        /// <summary>
        /// 讀取excel資料返回datatable
        /// </summary>
        /// <param name="sheetName">要讀取資料的sheet的名字</param>
        /// <returns>返回excel裡的資料</returns>
        public DataTable ReadExcelData(string sheetName,FileUpload UpLoadFile)
        {
            string strFileName = "";
            DataSet ds = new DataSet();
            DataTable dt;
             String fileName = UpLoadFile.PostedFile.FileName.Substring(UpLoadFile.PostedFile.FileName.LastIndexOf("\\") + 1, UpLoadFile.PostedFile.FileName.Length - 1 - UpLoadFile.PostedFile.FileName.LastIndexOf("\\"));
            ///取到目前時間的年、月、日、分、秒和毫秒的值,並使用字串格式把他們組合成一個字串
            String fileTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
            + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()
            + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()
            + DateTime.Now.Millisecond.ToString();
            ///在時間字串後面添加一個隨機數和檔案的尾碼名
            String src = fileName.Substring(fileName.LastIndexOf(".") + 1, fileName.Length - fileName.LastIndexOf(".") - 1).ToLower();
            fileName = fileTime + GetRandomint() + "." + src;
            //上傳檔案到伺服器硬碟
            UpLoadFile.PostedFile.SaveAs(Server.MapPath(Request.ApplicationPath) + "UserFile\\" + fileName);
            strFileName = Server.MapPath(Request.ApplicationPath) + "UserFile\\" + fileName;
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "+ strFileName + "; Extended Properties=‘Excel 8.0‘";
            OleDbDataAdapter oada = new OleDbDataAdapter("select * from ["+sheetName+"$]", strConn);
            oada.Fill(ds);
            dt = ds.Tables[0];
            return dt;
        }
        #endregion

 

以上方法用到一個隨機數的方法

private static string GetRandomint()
       {
             Random random = new Random();
             return(random.Next(10000).ToString());    //產生一個小於10000的隨機正整數
       }
好了,有了這2個方法,我們就可以在 button 按鈕的事件裡調用這個方法了:

調用如下:

DataTable dt= ReadExcelData("查詢", FileUpload1);
           GridView1.DataSource = dt;
           GridView1.DataBind();

 

當然嘍,這隻是最基本的讀取excel資料,如果想插入資料那就得按照規定的格式整理excel,然後從datatable裡讀取資料迴圈插入資料庫。

記得引用 using System.Data.OleDb;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.