首页 > 代码库 > C#Excel上传批量导入sqlserver
C#Excel上传批量导入sqlserver
前台:
<x:FileUpload ID="btnUpField" runat="server" Label="上传Excel批量导入用户信息" ShowLabel="true" > </x:FileUpload> <x:Button ID="Button1" Text="上传" runat="server" Icon="SystemSaveNew" OnClick="btnUpField_Click"> </x:Button>
后台:
protected void btnUpField_Click(object sender, EventArgs e) { //将需要导入的文件上传到服务器 string filePath = ""; string fileExtName = ""; string myFileName;//用不到,但也写上吧 string myPath; string FullName = "";//保存文件的完整文件名 if (btnUpField.PostedFile.FileName != "") { //取得文件路径 filePath = btnUpField.PostedFile.FileName; //取得文件扩展名 fileExtName = filePath.Substring(filePath.LastIndexOf(".") + 1); //判断是否为Excel文件 if (fileExtName == "xls" || fileExtName == "xlsx") { try { //取得与web服务器上指定的虚拟路径相对应的物理路径 myPath = Server.MapPath("~/UpFile/"); //取得文件名 myFileName = filePath.Substring(filePath.LastIndexOf(".") + 1); //取得当前时间,以“时时分分秒秒”来命名,以免重复 string strDateName = DateTime.Now.ToString("hhmmss"); FullName = myPath + strDateName + "." + fileExtName; btnUpField.PostedFile.SaveAs(FullName); } catch (Exception ex) { Response.Write(ex.Message); } } else { Alert.Show("文件格式不正确", MessageBoxIcon.Error); return; } } //读取Excel中的内容 //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FullName + ";Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1;‘";//Excel2003 //string strConn = String.Empty; string strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + FullName + ";Extended Properties=‘Excel 12.0; HDR=YES; IMEX=1‘";//Excel2007以上 OleDbConnection connxls = new OleDbConnection(strConn); if (connxls.State.ToString() == "Closed") { connxls.Open(); } string sqlExcel = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter myDa = new OleDbDataAdapter(sqlExcel, connxls); //DataTable m_tableName=new DataTable(); DataSet myDs = new DataSet(); //m_tableName = connxls.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); //if (m_tableName != null && m_tableName.Rows.Count > 0) //{ // m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString(); //} try { myDa.Fill(myDs, "[Sheet1$]"); } catch (Exception ex) { Response.Write("数据格式不对!" + ex.Message); } if (myDs.Tables[0].Rows.Count > 0)//数据绑定 { int i = 0; try { } catch (Exception ex) { Response.Write("读取出错" + ex.Message); } for (i = 0; i < myDs.Tables[0].Rows.Count; i++) { txtLoginName.Text = myDs.Tables[0].Rows[i][0].ToString(); txtName.Text = myDs.Tables[0].Rows[i][1].ToString(); txtPassword.Text = myDs.Tables[0].Rows[i][2].ToString(); txtAfreshPwd.Text = myDs.Tables[0].Rows[i][3].ToString(); if (myDs.Tables[0].Rows[i][4].ToString().Equals("男")) { rbSex.SelectedItem.Value = "男"; } else { rbSex.SelectedItem.Value = "女"; } Save(); } Alert.Show("恭喜您保存成功" + "共有" + myDs.Tables[0].Rows.Count + "条数据," + "正在保存第" + i + "条", MessageBoxIcon.Information); } PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference()); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。