try { string physicspath = "D:\\" + FileUpload.FileName; //excel檔案存放的位置 //產生串連Excel資料表格的字串 string strOdbcCon = @"Provider=Microsoft.ACE.OLEDB.12.0; Persist Security Info=False;Data Source=" + physicspath + "; Extended Properties=Excel 8.0"; //定義OleDbConnection對象執行個體並串連Excel表格 OleDbConnection OleDB = new OleDbConnection(strOdbcCon); //定義OleDbDataAdapter對象執行個體並調用Select查詢語句提取Excel資料資訊 OleDbDataAdapter OleDat = new OleDbDataAdapter("select * from [Sheet1$]", OleDB); DataTable dt = new DataTable(); //定義DataTable對象執行個體 OleDat.Fill(dt); //調用Fill方法 //串連資料表格,顯示資料 DataSet ds = new DataSet(); if (dt.Rows.Count > 0) { List<Tb_RDUserInfo> list = new List<Tb_RDUserInfo>(); //這裡寫的例子,是用的是架構,但其思路:先讀取excel裡面的值填充到dataset然後insert到資料庫中 foreach (DataRow dr in dt.Rows) { Tb_RDUserInfo model = new Tb_RDUserInfo(); model.UsersId = dr["編號"].ToString(); model.UsersName = dr["姓名"].ToString(); model.LoginName = dr["登入使用者名稱"].ToString(); string RoleId = dr["角色"].ToString(); Tb_RDRoleInfo Tb_RDRole_4 = new Tb_RDRoleInfo(); Tb_RDRoleService Tb_RDRole_5 = new Tb_RDRoleService(); Tb_RDRole_4 = Tb_RDRole_5.GetModel(RoleId); model.RoleId = Tb_RDRole_4; model.PassWord = dr["密碼"].ToString(); model.Mobile = dr["手機號碼"].ToString(); model.Birthday = dr["出生日期"].ToString(); model.Sex = dr["性別"].ToString(); model.DentityCard = dr["身份證"].ToString(); model.OrgName = dr["單位名稱"].ToString(); model.DeptName = dr["部門名稱"].ToString(); model.Post = dr["職務資訊"].ToString(); model.PeriodName = dr["屆次"].ToString(); model.Email = dr["電子郵箱"].ToString(); model.Phone = dr["固定電話"].ToString(); model.Address = dr["郵寄地址"].ToString(); model.ZipCodeId = dr["郵遞區號"].ToString(); model.IsAdmin = dr["是否管理員"].ToString(); model.CurrentState = dr["目前狀態"].ToString(); model.Memo = dr["備忘"].ToString(); string DelegationId = dr["所屬代表團"].ToString(); Tb_DelegationInfo Tb_Delegation_21 = new Tb_DelegationInfo(); Tb_DelegationService Tb_Delegation_22 = new Tb_DelegationService(); Tb_Delegation_21 = Tb_Delegation_22.GetModel(DelegationId); model.DelegationId = Tb_Delegation_21; model.ManageWork = dr["分管工作"].ToString(); model.UserType = dr["使用者分類個體"].ToString(); list.Add(model); } UserManager.Add(list); MessageBox.Show(this, "大量新增使用者成功!"); } else { MessageBox.Show(this, "對不起,無資料無法添加!"); } } catch (Exception ey) { MessageBox.Show(this, ey.Message); //提示對話方塊 }
添加引用:using System.Data.OleDb;
在頁面設計中拖入FileUpload控制項
代碼部分: