In this article I will explain with an example, how to upload, read and display
Excel file data using
OLEDB in ASP.Net Core (.Net Core 7) Razor Pages.
The uploaded
Excel file data will be read using
OLEDB library and the read data will be displayed in View using HTML Table (Grid) format.
Download System.Data.OleDb DLL
There are two ways you can download the System.Data.OleDb DLL.
Connection Strings in AppSettings.json file
The connection string to the Database and
Excel file are saved in the
AppSettings.json file.
The DataSource property has been assigned a Placeholder {0}, which will be replaced by actual path of the File.
{
"ConnectionStrings": {
"Excel03ConString": "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'",
"Excel07ConString": "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"
}
}
Model
The Model class consists of following properties.
public class CustomerModel
{
///<summary>
/// Gets or sets CustomerId.
///</summary>
public int CustomerId { get; set; }
///<summary>
/// Gets or sets Name.
///</summary>
public string Name { get; set; }
///<summary>
/// Gets or sets Country.
///</summary>
public string Country { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Data;
using System.Data.OleDb;
PageModel (Code-Behind)
The Controller consists of following Handler methods.
Handler method for handling GET operation
This Handler method left empty as it is not required.
Handler method for handling POST operation for uploading and reading Excel file
This Handler method gets called when the Import Button is clicked and it accepts IFormFile class as a parameter.
Note: The name of the IFormFile parameter and the name of HTML FileUpload element must be exact same, otherwise the IFormFile parameter will be NULL.
First a check is performed if the file is selected or not, if selected then the selected file is saved into a Folder (Directory) named Uploads using IWebHostEnvironment interface.
Then, using the switch case statement, the Excel file extension is determined and the connection string is built.
A connection is established with the Excel file using
OLEDB classes and the name of the first sheet is determined and the first sheet data is read into a
DataTable.
Finally, a FOR EACH loop is executed over the DataTable and the records are copied into the Generic List collection of CustomerModel class objects which is then set to the public property of CustomerModel class.
public class IndexModel : PageModel
{
private IWebHostEnvironment Environment;
private IConfiguration Configuration;
public IndexModel(IWebHostEnvironment _environment, IConfiguration _configuration)
{
this.Environment = _environment;
this.Configuration = _configuration;
}
public List<CustomerModel> Customer { get; set; }
publicvoid OnGet()
{
}
public void OnPostSubmit(IFormFile postedFile)
{
List<CustomerModel> customers = new List<CustomerModel>();
if (postedFile != null)
{
//Create a Folder.
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//Save the uploaded Excel file.
string fileName = Path.GetFileName(postedFile.FileName);
string filePath = Path.Combine(path, fileName);
string extension = Path.GetExtension(postedFile.FileName);
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
postedFile.CopyTo(stream);
}
//Read the connection string for the Excel file.
string constr = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03.
constr = this.Configuration.GetConnectionString("Excel03ConString");
break;
case ".xlsx": //Excel 07 and above.
constr = this.Configuration.GetConnectionString("Excel07ConString");
break;
}
DataTable dt = new DataTable();
constr = string.Format(constr, filePath);
using (OleDbConnection connExcel = new OleDbConnection(constr))
{
using (OleDbCommand cmdExcel = new OleDbCommand())
{
using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
{
cmdExcel.Connection = connExcel;
//Get the name of First Sheet.
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet.
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
odaExcel.SelectCommand = cmdExcel;
odaExcel.Fill(dt);
connExcel.Close();
foreach (DataRow row in dt.Rows)
{
customers.Add(new CustomerModel
{
CustomerId = Convert.ToInt32(row["Customer Id"]),
Name = row["Name"].ToString(),
Country = row["Country"].ToString()
});
}
}
}
}
}
this.Customer = customers;
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, first the TagHelpers is inherited.
The Razor Page consists of an HTML Form which has been created using the following TagHelpers attribute.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files.
The Form consists of an HTML FileUpload element and a Submit Button.
Submitting the Form
For displaying the records, an HTML Table is used. A FOR loop will be executed over the Model which will generate the HTML Table rows with the
Excel file data.
@page
@model Read_Excel_OLEDB_Core_Razor.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using Read_Excel_OLEDB_Core_Razor.Models
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="postedFile" />
<input type="submit" value="Import" asp-page-handler="Submit" />
</form>
<hr />
@if (Model.Customer != null)
{
<table cellpadding="0" cellspacing="0">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (CustomerModel customer in Model.Customer)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
}
</body>
</html>
Screenshots
The Excel File
Grid displaying Excel data
Downloads