標籤:style blog http color io os ar java 檔案
先通過控制項FileUpload擷取excel檔案路徑
protected void btnReadExcelFromFileUpload_Click(object sender, EventArgs e) { if (fupExcel.PostedFile.ContentLength > 0) { //擷取全路徑 string fullFileName = fupExcel.PostedFile.FileName.ToString(); //擷取檔案名稱 string fileName = fupExcel.FileName.ToString(); //擷取檔案類型 string type = fileName.Substring(fileName.LastIndexOf(".") + 1); //擷取上傳路徑 string path = Server.MapPath("UploadFile\\")+fileName; Response.Write(path); //檔案大小 FileInfo file = new FileInfo(fullFileName); float size=(file.Length/1024)/1024; if (type != "xls") { Response.Write("<script language=‘javascript‘>alert(‘不是Excel檔案!‘)</script>"); } else { // fupExcel.PostedFile.SaveAs(path);//上傳到伺服器 DataSet ds = ImportExcel(fullFileName); gvFirst.DataSource = ds; gvFirst.DataBind(); } } }
讀取excel檔案裡的資料到DataSet裡
/// <summary> /// 讀取Excel資料到DataSet /// </summary> /// <param name="filename"></param> /// <returns></returns> public DataSet ImportExcel(string filename) { //檔案路徑 string ExcelName = filename; //HDR=YES 有兩個值:YES/NO,表示第一行是否欄位名,預設是YES,第一行是欄位名 /* IMEX有三個值0,1,2,其他兩個值分別表示什麼 當 IMEX=0 時為“匯出模式”,這個模式開啟的 Excel 檔案只能用來做“寫入”用途。 當 IMEX=1 時為“匯入模式”,這個模式開啟的 Excel 檔案只能用來做“讀取”用途。 當 IMEX=2 時為“連結模式”,這個模式開啟的 Excel 檔案可同時支援“讀取”與“寫入”用途。 詳見:http://www.cnblogs.com/goto/archive/2012/04/12/2443670.html */ string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelName + ";Extended Properties=‘Excel 8.0;HDR=No;IMEX=1‘;";//串連excel檔案的字串 if (ExcelName == null) { return null; } OleDbConnection odcon = new OleDbConnection(strcon);//建立串連 odcon.Open();//開啟串連 System.Data.DataTable sTable = odcon.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); //Sheets Name string tableName = sTable.Rows[0][2].ToString().Trim(); if (tableName == "") { return null; } else { tableName = "[" + tableName + "]"; } OleDbDataAdapter odda = new OleDbDataAdapter("select * from " + tableName, odcon); DataSet ds = new DataSet(); try { odda.Fill(ds); } catch (Exception ex) { ClientScript.RegisterStartupScript(this.Page.GetType(), "", "<script language=‘javascript‘ defer>alert(‘"+ex.Message+"‘);</script>"); } return ds; }
asp.net讀取Excel資料