Loading a Excel File From a Web Upload With Npoi
Nosotros are using NPOI library here, which will assist to perform import and export operations. In lodge to run across how to create a .Cyberspace Core Web Awarding with Razor Pages and retrieve data from SQL Server using Entity Framework, yous tin visit my previous article.
Beneath are the software/concepts used in this document.
- Visual Studio 2019
- NPOI Library
- NuGet Packages
- Razor Pages
- .NET Core two.0
- .NETCore Spider web Application
- C# Language
Brief description of NPOI
NPOI is an open up source project which can aid you read/write XLS, DOC, PPT file extensions. This tool is the .NET version of POI Coffee project (http://poi.apache.org/). It covers almost of the features of Excel like styling, formatting, data formulas, extract images, etc. The good affair is that it does non crave Microsoft Role on the server. For example, you can use information technology to -
- Generate an Excel written report without Microsoft Part suite installed on your Server, which is more than efficient than calling Microsoft Excel ActiveX in the background.
- Extract text from Office documents to help y'all implement full-text indexing feature (most of the times, this feature is used to create search engines).
- Extract images from Role documents.
- Generate Excel sheets which contain formulas.
How Razor Pages handle incoming HTTP Requests
Razor pages use handler methods to deal with the incoming HTTP request (GET/POST/PUT/Delete). They are prefixed with "On" and the name of HTTP verbs like -
- OnGet
- OnPost
- OnPut
- OnGetAsync
- OnPostAsync
- OnPutAsync
Besides these default handlers, we tin can also specify custom names. The custom proper name must come later on the followed naming convention similar, for example -
- OnGetCountries()
- OnPostUserMaster()
- OnPostUserDetails()
We will be using custom names for our Import and Export handler methods.
Open up your project in Visual Studio 2019
In my case, I am opening the before created project where Razor pages are present.
Add NuGet Packages to the higher up-created projection
In the Visual Studio carte, browse to Tools >> NuGet Package Director >> Bundle Manager Panel.
Then, execute the following control to install the NPOI.
Install-Packet DotNetCore.NPOI
Export to Excel by creating Excel (.xlsx/.xls) with dummy data
Open the Index page (Razor page) where the data is present. In my instance, I am opening Alphabetize.cshtml under "Customers" folder where my customer data is displayed.
Put the beneath lawmaking within the Alphabetize.cshtml folio which would call the handler method "asp-page-handler="ExporttoExcel"".
- <form method= "post" enctype= "multipart/grade-information" >
- <divcourse = "row" >
- <divform = "col-md-viii" way= "padding-top:10px;" >
- <button asp-folio-handler="ExporttoExcel" >Export to Excel</push button>
- </div>
- </div>
- <div id="divData" ></div>
- </form>
Open Index.cshtml.cs file and put the below lawmaking which would create .xlsx file in the wwwroot folder by injecting IHostingEnvironment in the constructor.
- individual IHostingEnvironment _hostingEnvironment;
- public IndexModel(IHostingEnvironment hostingEnvironment)
- {
- _hostingEnvironment = hostingEnvironment;
- }
The NPOI package supports both "xls" and "xlsx" extensions using HSSFWorkbook and XSSFWorkbook classes respectively. In my example, I would be using XSSFWorkbook class, as I volition work with the .xlsx file. In the Index.cshtml.cs file, put the below new method.
- public async Job<IActionResult> OnPostExporttoExcel()
- {
- cord webRootPath = _hostingEnvironment.WebRootPath;
- cord fileName = @ "Testingdummy.xlsx" ;
- string URL = string .Format( "{0}://{one}/{two}" , Request.Scheme, Request.Host, fileName);
- FileInfo file =new FileInfo(Path.Combine(webRootPath, fileName));
- var memoryStream =new MemoryStream();
- using (var fs = new FileStream(Path.Combine(webRootPath, fileName), FileMode.Create, FileAccess.Write))
- {
- IWorkbook workbook =new XSSFWorkbook();
- ISheet excelSheet = workbook.CreateSheet("Testingdummy" );
- IRow row = excelSheet.CreateRow(0);
- row.CreateCell(0).SetCellValue("ID" );
- row.CreateCell(one).SetCellValue("Name" );
- row = excelSheet.CreateRow(1);
- row.CreateCell(0).SetCellValue(ane);
- row.CreateCell(1).SetCellValue("Mike" );
- row = excelSheet.CreateRow(2);
- row.CreateCell(0).SetCellValue(two);
- row.CreateCell(1).SetCellValue("James" );
- workbook.Write(fs);
- }
- using (var fileStream = new FileStream(Path.Combine(webRootPath, fileName), FileMode.Open))
- {
- await fileStream.CopyToAsync(memoryStream);
- }
- memoryStream.Position = 0;
- return File(memoryStream, "awarding/vnd.openxmlformats-officedocument.spreadsheetml.sail" , fileName);
- }
Test the files by right-clicking on the Alphabetize file and opening it in browser. And then, click on the "Export to Excel" button. The "Testingdummy.xlsx" file is downloaded.
Export to Excel by taking information from the screen
Open up the Index page (Razor page) where the data is present. In my example, I am opening Index.cshtml under "Customers" binder where my customer data is displayed.
- Repeat the two steps from above (where nosotros put Grade and IHostingEnvironment code on the index.cshtml and index.cshtml.cs pages).
- My data already gets loaded on the folio and the aforementioned data I want to export to the Excel.
- The NPOI package supports both "xls" and "xlsx" extensions using HSSFWorkbook and XSSFWorkbook classes. In my example, I would be using XSSFWorkbook class, every bit I will piece of work with .xlsx file. In Index.cshtml.cs file, put the following code. Besides, since I have 4 columns of data to be exported to Excel, in my instance, I will have 4 columns.
- public async Chore<IActionResult> OnPostExporttoExcel()
- {
- string webRootPath = _hostingEnvironment.WebRootPath;
- string fileName = @ "Testingdummy.xlsx" ;
- string URL = string .Format( "{0}://{1}/{2}" , Request.Scheme, Request.Host, fileName);
- FileInfo file =new FileInfo(Path.Combine(webRootPath, fileName));
- var memoryStream =new MemoryStream();
- using (var fs = new FileStream(Path.Combine(webRootPath, fileName), FileMode.Create, FileAccess.Write))
- {
- IWorkbook workbook =new XSSFWorkbook();
- ISheet excelSheet = workbook.CreateSheet("Testingdummy" );
- IRow row = excelSheet.CreateRow(0);
- row.CreateCell(0).SetCellValue("CustomerId" );
- row.CreateCell(1).SetCellValue("FirstName" );
- row.CreateCell(ii).SetCellValue("LastName" );
- row.CreateCell(iii).SetCellValue("Email" );
- cust = from due southin _context.Customers select s;
- int counter = 1;
- foreach (var customer in cust)
- {
- string FirstName = string .Empty;
- if (client.FirstName.Length > 100)
- FirstName = customer.FirstName.Substring(0, 100);
- else
- FirstName = customer.FirstName;
- row = excelSheet.CreateRow(counter);
- row.CreateCell(0).SetCellValue(customer.CustomerId);
- row.CreateCell(1).SetCellValue(FirstName);
- row.CreateCell(2).SetCellValue(customer.LastName);
- row.CreateCell(three).SetCellValue(customer.Email);
- counter++;
- }
- workbook.Write(fs);
- }
- using (var fileStream = new FileStream(Path.Combine(webRootPath, fileName), FileMode.Open))
- {
- await fileStream.CopyToAsync(memoryStream);
- }
- memoryStream.Position = 0;
- render File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sail" , fileName);
- }
- Test the files by right-clicking on the Index file and opening it with browser. So, click on the "Export to Excel" button. The "Testingdummy.xlsx" file is downloaded.
Import information from Excel (.xls or .xlsx) and display it on the screen
I would read the data from Excel and perform the client-side validation for file selection and extension checking. Once the asking is successful, information technology appends the server response to the HTML and displays information technology on the screen in tabular format.
- Create a dummy Excel with the name "Testingdummy.xlsx". In my example, I have four columns "CustomerID", "FirstName", "LastName" and "Electronic mail".
- Open the Index folio (Razor page) where the information is present. In my example, I am opening Index.cshtml nether "Customers" folder where my customer data is displayed.
- Put the below code within the Index.cshtml page.
- <form method= "post" enctype= "multipart/form-data" >
- @* New code to add file Upload and buttonfor importing the data from excel *@
- <divclass = "row" >
- <divclass = "col-md-4" >
- <input blazon="file" id= "fileUpload" name= " fileUpload" class = "form-control" />
- </div>
- <divclass = "col-md-8" >
- <input type="button" id= "btnUpload" value= "Upload File" />
- </div>
- </div>
- @*--- Existing lawmakingfor exporting data to excel----*@
- <divclass = "row" >
- <divclass = "col-md-8" way= "padding-superlative:10px;" >
- <button asp-folio-handler="ExporttoExcel" >Export to Excel</push button>
- </div>
- </div>
- <div id="divData" ></div>
- </form>
On the same Index.cshtml page, put the following code for performing the client side validation and call the Import Handler method named "ImportFromExcel".
- $(document).ready( role () {
- $('#btnUpload' ).on( 'click' , role () {
- var fileExtension = [ 'xls' , 'xlsx' ];
- var filename = $('#fileUpload').val();
- if (filename.length == 0) {
- alert("Please select a file." );
- return false ;
- }
- else {
- var extension = filename.replace(/^.*\./, '' );
- if ($.inArray(extension, fileExtension) == -1) {
- alert("Please select only excel files." );
- render faux ;
- }
- }
- var filedata = new FormData();
- var fileUpload = $( "#fileUpload" ).become(0);
- var files = fileUpload.files;
- filedata.append(files[0].proper name, files[0]);
- $.ajax({
- type:"Mail" ,
- url:"/Alphabetize?handler=ImportFromExcel" ,
- beforeSend:function (xhr) {
- xhr.setRequestHeader("XSRF-TOKEN" ,
- $('input:hidden[proper noun="__RequestVerificationToken"]' ).val());
- },
- data: filedata,
- contentType:false ,
- processData:faux ,
- success:function (response) {
- if (response.length == 0)
- warning(Fault occurredwhile uploading the excel file');
- else {
- $('#divData' ).html(response);
- }
- },
- fault:function (east) {
- $('#divData' ).html(e.responseText);
- }
- });
- })
- });
In Alphabetize.cshtml.cs file, put below code which would handle the Import handler method called from the jQuery function in the in a higher place stride.
- public ActionResult OnPostImportFromExcel()
- {
- IFormFile file = Asking.Form.Files[0];
- string folderName = "Upload" ;
- string webRootPath = _hostingEnvironment.WebRootPath;
- string newPath = Path.Combine(webRootPath, folderName);
- StringBuilder sb =new StringBuilder();
- if (!Directory.Exists(newPath))
- Directory.CreateDirectory(newPath);
- if (file.Length > 0)
- {
- cord sFileExtension = Path.GetExtension(file.FileName).ToLower();
- ISheet canvas;
- string fullPath = Path.Combine(newPath, file.FileName);
- using (var stream = new FileStream(fullPath, FileMode.Create))
- {
- file.CopyTo(stream);
- stream.Position = 0;
- if (sFileExtension == ".xls" )
- {
- HSSFWorkbook hssfwb =new HSSFWorkbook(stream);
- canvas = hssfwb.GetSheetAt(0);
- }
- else
- {
- XSSFWorkbook hssfwb =new XSSFWorkbook(stream);
- canvass = hssfwb.GetSheetAt(0);
- }
- IRow headerRow = canvas.GetRow(0);
- int cellCount = headerRow.LastCellNum;
- sb.Append("<table class='table'><tr>" );
- for ( int j = 0; j < cellCount; j++)
- {
- NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
- if (jail cell == zero || string .IsNullOrWhiteSpace(prison cell.ToString())) continue ;
- sb.Append("<th>" + cell.ToString() + "</th>" );
- }
- sb.Append("</tr>" );
- sb.AppendLine("<tr>" );
- for ( int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
- {
- IRow row = canvas.GetRow(i);
- if (row == null ) continue ;
- if (row.Cells.All(d => d.CellType == CellType.Blank)) proceed ;
- for ( int j = row.FirstCellNum; j < cellCount; j++)
- {
- if (row.GetCell(j) != null )
- sb.Append("<td>" + row.GetCell(j).ToString() + "</td>" );
- }
- sb.AppendLine("</tr>" );
- }
- sb.Append("</table>" );
- }
- }
- render this .Content(sb.ToString());
- }
Examination the files past correct-clicking on the Index file and opening it with the browser. Scan your dummy Excel file then click on the "Upload File" button. The "Testingdummy.xlsx" file is read and displayed on the screen in tabular format.
That is it. I hope you have learned something new from this article and volition use this in your work.
Source: https://www.c-sharpcorner.com/article/export-and-import-data-using-npoi-library-in-net-core-2-razor-pages/
0 Response to "Loading a Excel File From a Web Upload With Npoi"
Post a Comment