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.