简体   繁体   中英

Load data from local excel file to an ASP.NET MVC web app to store in database

  1. When I run the web app, I want to automatically open an Excel file that's on my computer, get the data from it, and create a table with Entity Framework and C# in my database
  2. Then I want to store that data retrieved from the Excel file into the table created
  3. Would be repeated for each sheet or Excel file opened

I have read some other posts related to this and they all created like an upload file input box on the web app,

But I want it to be done as soon as I run the web app.

I would really appreciate suggestions/help/guidance on how to go about this without having to upload the file or click anything from the user.

To acheive your goal you could try below things:

Create a Resource folder to your current project root directory and put your excel file on that path.

var pathToExcelFile = Server.MapPath("~/Resource/Demo.xlsx");

If you want to read excel file from your Local Drive eg D: Drive: (keep in mind this is not recommended)

var pathToExcelFile = @"D:\Demo.xlsx"; 

Then you have to take help of OleDb to read excel file data.

string oleConnStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", oleConnStr);
var ds = new DataSet();
adapter.Fill(ds, "ExcelTable");
DataTable dt = ds.Tables["ExcelTable"];

After that build your database connection and write insert logic:

var mssqlConnStr = "Data Source= .; DataBase= Demo; Integrated Security = true;";

using (SqlConnection conn = new SqlConnection(mssqlConnStr))
{
       conn.Open();

       foreach (DataRow dataRow in dt.Rows)
       {
            var query = "INSERT INTO UserWiseSales (UserId, Sales) VALUES (@UserId, @Sales)";
            SqlCommand sqlCommand = new SqlCommand(query, conn);
            sqlCommand.Parameters.AddWithValue("@UserId", dataRow["UserId"].ToString());
            sqlCommand.Parameters.AddWithValue("@Sales", dataRow["Sales"].ToString());
            sqlCommand.ExecuteNonQuery();
       }
}

To run the above code as soon as your web app run, you have to put the code inside a method and call it from Application_Start method under Global.asax.cs file.

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM