一、准备工作
1、新建文件夹:存放上传的Excel文件。
2、控件:使用FileUpload
控件来上传Excel文件,使用Button
控件触发上传操作。
3、Excel表格式:确保Excel表头与数据库表字段对应。
4、修改数据库插入方法:确保数据能正确插入到数据库中。
二、前台控件
<div style="margin-top: 0px; margin-left: 0px;"> <div style="height: 38px"> <asp:Label ID="Label1" runat="server" Text="文件*:" Width="60px"></asp:Label> <asp:FileUpload ID="fulImport" runat="server" Height="20px" Width="450px" /> <asp:Button ID="btnImport" runat="server" Text="一键上传" Width="80px" Height="20px" OnClick="btnImport_Click" /> </div> </div>
三、后台响应程序
1. 将Excel上传到服务器
protected string GetExcel() { string fileUrl = ""; try { string excelFile = this.fulImport.PostedFile.FileName; string fileName = Path.GetFileNameWithoutExtension(fulImport.PostedFile.FileName); string extentionName = excelFile.Substring(excelFile.LastIndexOf(".") + 1); if (fileName == "" || fileName == null) { Response.Write("<script>alert('请先选择Excel文件!')</script>"); return null; } if (extentionName != "xls" && extentionName != "xlsx") { Response.Write("<script>alert('您上传的不是Excel文件!')</script>"); return null; } string dateTime = DateTime.Now.Date.ToString("yyyyMMdd"); string time = DateTime.Now.ToShortTimeString().Replace(":", ""); string newFileName = dateTime + time + DateTime.Now.Millisecond.ToString() + ".xls"; ; fileUrl = Server.MapPath("..\\excel") + "\\" + newFileName; this.fulImport.PostedFile.SaveAs(fileUrl); return fileUrl; } catch { Response.Write("<script>alert('数据上传失败,请重新导入')</script>"); return null; } }
2. Excel数据导入DataTable
protected System.Data.DataTable GetExcelDatatable(string fileUrl) { const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; System.Data.DataTable dt = null; OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl)); if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed) { conn.Open(); } System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString(); string strSql = $"select * from [{sheetName}]"; OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn); DataSet ds = new DataSet(); da.Fill(ds); dt = ds.Tables[0]; return dt; }
3. 从DataTable导入数据到数据库
protected void InsetData(System.Data.DataTable dt) { string connectionString = "your_connection_string_here"; // 替换为你的数据库连接字符串 using (SqlBulkCopy bcp = new SqlBulkCopy(connectionString)) { bcp.DestinationTableName = "your_table_name"; // 替换为你的目标数据库表名 bcp.BatchSize = 100; // 每次传输的行数 bcp.BulkCopyTimeout = 600; // 超时时间(秒) bcp.WriteToServer(dt); // 执行批量写入操作 } }
4. btnImport_Click事件处理程序
protected void btnImport_Click(object sender, EventArgs e) { string fileUrl = this.GetExcel(); if (!string.IsNullOrEmpty(fileUrl)) { System.Data.DataTable dt = this.GetExcelDatatable(fileUrl); this.InsetData(dt); Response.Write("<script>alert('数据导入成功!')</script>"); } }
四、相关问题与解答
1、如何更改数据库连接字符串?
答:在InsetData
方法中的connectionString
变量处,替换为你的数据库连接字符串。"Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
。
2、如何处理Excel文件中的特殊字符或空值?
答:在读取Excel数据时,可以通过检查和处理特殊字符或空值来避免错误,可以在GetExcelDatatable
方法中添加对空值和特殊字符的处理逻辑。
以上就是关于“asp实现excel中的数据导入数据库”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/55436.html<