C#讀取Excel顯示到repeater中

來源:互聯網
上載者:User

標籤:

首先需要一個用來儲存我們需要顯示的內容,防止頁面回傳丟失(添加時使用)

#region 快取檔案        private DataTable excelData;        /// <summary>        /// 緩衝已經讀取過的Datatable        /// </summary>        public DataTable ExcelData        {            get            {                if (ViewState["mydata"] != null)                {                    excelData = (DataTable)ViewState["mydata"];                }                return excelData;            }            set            {                ViewState["mydata"] = value;            }        }        #endregion

 接下來檢查上傳檔案

 /// <summary>        /// 檢查檔案上傳        /// </summary>        /// <param name="fileName"></param>        /// <returns></returns>        public string CheckFile(string fileName)        {            if (string.IsNullOrEmpty(fileName))            {                return "Please ensure that you upload file exists!";            }            if (!fileName.ToLower().EndsWith(".xls") && !fileName.ToLower().EndsWith(".xlsx"))            {                return "You select the file format is not correct, please try again!";            }            if (fileName.IndexOf(".") <= 0)            {                return "Please select a file to upload!";            }            return "";        }

 

 /// <summary>        /// 串連Excel,並讀取資料來源        /// </summary>        /// <param name="filepath">資料來源路徑</param>        /// <returns>Excel檔案的工作薄裡的資料</returns>        public DataSet connExcel(string filepath)        {            if (!string.IsNullOrEmpty(filepath))            {                try                {                    string connstring = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filepath + ";Extended Properties=‘Excel 12.0; HDR=Yes; IMEX=1‘"; //此串連可以操作.xls與.xlsx檔案 (支援Excel2003 和 Excel2007 的連接字串)                    OleDbConnection objconn = new OleDbConnection(connstring);                    objconn.Open();                    DataTable dt = objconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "table" });                    string sheetname = "Sheet1$";                    sheetname = dt.Rows[0]["TABLE_NAME"].ToString();                    objconn.Close();                    string strsql = "select * from [" + sheetname + "]";                    DataSet ds = new DataSet();                    OleDbDataAdapter adp = new OleDbDataAdapter(strsql, objconn);                    adp.Fill(ds);                    return ds;                }                catch (Exception ex)                {                    throw new Exception("Occurs when a data source connection:" + ex.Message);                }            }            else            {                throw new Exception("File does not exist!");            }        }

 

 /// <summary>        /// 讀取Excel        /// </summary>        /// <param name="path"></param>        /// <returns></returns>        private DataTable readExcel(string path)        {            DataTable dt = new DataTable("myTestTable");            dt.Columns.Add("ID");            dt.Columns.Add("Name");            dt.Columns.Add("Sex");            DataView dv = new DataView(dt);            DataSet ds = connExcel(path);            return ds.Tables[0];        }

 

/// <summary>        /// 上傳檔案的方法        /// </summary>        /// <returns></returns>        [ScriptMethod]        private void PreviewData()        {            //擷取檔案名稱            string fileName = Path.GetFileName(this.fileSave.PostedFile.FileName);            //檢索檔案            string message = CheckFile(fileName);            if (!string.IsNullOrEmpty(message))            {                Page.ClientScript.RegisterStartupScript(this.GetType(), "ok", "alert(‘" + message + "‘)", true);                return;            }            try            {                string path = Server.MapPath("/MyTest/ExcelData/");                //檔案是否存在,如果不存在則建立                if (!Directory.Exists(path))                {                    Directory.CreateDirectory(path);                }                //定義檔案的隨機數                Random rand = new Random();                path += rand.Next(0, 9999999) + DateTime.Now.Hour + DateTime.Now.Minute + fileName;                //上傳檔案                this.fileSave.PostedFile.SaveAs(path);                //將資料內容儲存到緩衝中                ExcelData = this.readExcel(path);                this.rptData.Visible = true;                this.rptData.DataSource = ExcelData;                this.rptData.DataBind();            }            catch (Exception ex)            {                throw ex;                //Page.ClientScript.RegisterStartupScript(this.GetType(), "no", "alert(‘" + ex.Message + "‘)", true);            }        }

 

C#讀取Excel顯示到repeater中

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.