Tôi sẽ chỉ cho bạn cách kết nối với Microsoft Excel Workbook bằng cách sử dụng nhà cung cấp dữ liệu OLEDB.NET, trích xuất dữ liệu và sau đó chèn nó vào & nbsp; bảng cơ sở dữ liệu.
Để bắt đầu, chúng tôi sẽ tạo ra một exceltodatabase trong bộ điều khiển gia đình trả về chế độ xem. Phương thức này sẽ trả về một chế độ xem từ nơi chúng ta phải tải lên tệp Excel. Bây giờ chúng tôi sẽ tạo một phương thức khác Exceltodatabase. & nbsp; Bây giờ nếu chúng tôi thực hiện yêu cầu nhận thì Exceltodatabase sẽ được gọi và để yêu cầu POST, Exceltodatabase sẽ được gọi. Sau đây là mã để đọc các tệp Excel.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data; using System.Data.OleDb; using System.IO; namespace ExcelReadData { public class HomeController : Controller { // GET: ClonePanel public ActionResult ExcelToDatabase() { return View(); } [HttpPost] public ActionResult ExcelToDatabase() { bool result = false; ViewBag.data = null; if (Request.Files["FileUpload1"].ContentLength > 0) { string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower(); string query = null; string connString = ""; string[] validFileTypes = { ".xls", ".xlsx" }; string path2 = string.Format("{0}/{1}", Server.MapPath("~/Content/Uploads"), Request.Files["FileUpload1"].FileName); if (!Directory.Exists(path2)) { Directory.CreateDirectory(Server.MapPath("~/Content/Uploads")); } if (validFileTypes.Contains(extension)) { if (System.IO.File.Exists(path2)) { System.IO.File.Delete(path2); } Request.Files["FileUpload1"].SaveAs(path2); //Connection String to Excel Workbook if (extension.Trim() == ".xls") { connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path2 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; result = Service.ImportExceltoDatabase(path2, connString, userId); } else if (extension.Trim() == ".xlsx") { connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path2 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; result = Service.ImportExceltoDatabase(path2, connString,userId); } } else { ViewBag.Error = "Please Upload Files in .xls, .xlsx or .csv format"; } } if (result) { ViewBag.data = "Data Import Successfully from excel to database."; } else { ViewBag.data = "there is some issue while importing the Data."; } return View(); } } }Ở đây tôi đã tạo một dịch vụ lớp A & nbsp; có chứa 1 & nbsp; Phương thức & nbsp; convertXSlxToDataTable. Sau đây là mã cho lớp dịch vụ.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.OleDb; using System.Data; namespace ExcelReadData { public class Service : IDisposable { #region **Private Variables** private TestDatabaseEntities _dbContext; #region **Constructor** public ImportExceltoDatabase() { _dbContext = new TestDatabaseEntities(); } #endregion public bool ImportExceltoDatabase(string strFilePath, string connString) { bool result = false; OleDbConnection oledbConn = new OleDbConnection(connString); DataTable dt = new DataTable(); try { oledbConn.Open(); using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn)) { OleDbDataAdapter oleda = new OleDbDataAdapter(); oleda.SelectCommand = cmd; DataSet ds = new DataSet(); oleda.Fill(ds); dt = ds.Tables[0]; if (dt.Rows.Count > 0) { table tblObj = new table(); foreach (DataRow row in dt.Rows) { tblObj.Name = row["Name"].ToString(); tblObj.Name = row["Address"].ToString(); tblObj.Salary = (int)row["Salary"]; tblObj.Age = (int)row["Age"]; } } } } catch(Exception ex) { result = false; } finally { oledbConn.Close(); } return result; } } }Bây giờ chúng tôi phải & nbsp; tạo chế độ xem có chứa điều khiển tải lên tệp và nút. Khi một yêu cầu cho exceltodatabase của bộ điều khiển gia đình được thực hiện, nó sẽ hiển thị điều khiển tải lên tệp với điều khiển nút. Khi người dùng & NBSP; chọn một tệp và nhấn nút, nó sẽ thực hiện yêu cầu POST đến bộ điều khiển gia đình và phương thức Exceltodatabase sẽ được gọi. Sau đây là chế độ xem dao cạo cho cả hai yêu cầu.
@using (Html.BeginForm("ImportExcel", "ExcelToDB", FormMethod.Post, new { enctype = "multipart/form-data" })) { <table> <tr><td>Excel file</td><td><input type="file" id="FileUpload1" name="FileUpload1" /></td></tr> <tr><td></td><td><input type="submit" id="Submit" name="Submit" value="Submit" /></td></tr> <tr><td></td><td><lable>@(viewbag.data)</lable></td></tr> </table> }