DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Implementing Effective Document Fraud Detection in C#
  • A Guide for Deploying .NET 10 Applications Using Docker's New Workflow
  • SHAP-Based Explainable AI (XAI) Integration With .Net Application
  • Why Architecture Matters: Structuring Modern Web Apps

Trending

  • When One MVP Is Really Four Systems: A Better Way to Plan Multi-Role Apps
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  • LLM-Powered Deep Parsing for Industrial Inventory Search
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  1. DZone
  2. Coding
  3. Languages
  4. Import and Export Excel file in ASP .NET Core 3.1 Razor age

Import and Export Excel file in ASP .NET Core 3.1 Razor age

Home .NET Core In this article we will discuss how to import and export excel file using ASP .NET Core 3.1 razor pages. We will discuss the below points >> H...

By 
Jayant Tripathy user avatar
Jayant Tripathy
·
Apr. 24, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
67.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this article we will discuss how to import and export excel file using ASP .NET Core 3.1 razor pages. We will discuss the below points:

>>  How to import Excel file in .NET Core and preview the uploaded excel file?
>>  How to export the excel file ? 


NPOI Package
NPOI is a free tool, which supports xls, xlsx, and docx extensions. This project is the .NET version of POI Java project at http://poi.apache.org/. POI is an open source project, which can help you read/write XLS, DOC, PPT files. It covers most features of Excel, like styling, formatting, data formulas, extract images, etc. The good thing is, it doesn't require Microsoft Office to be installed on the server. NPOI is an open source component, and you can use it everywhere. 

This post shows you the basic functionalities of NPOI, but you can do much more with NPOI like styling the individual cell or rows, creating excel formulas, and other stuff. The NPOI package supports both "xls" and "xlsx" extensions, using HSSFWorkbook and XSSFWorkbook classes. The HSSFWorkbook class is for "xls", where the other one is for "xlsx". To know more about NPOI, Refer the official documentation.

Import and Export Excel in ASP.NET Core 3.1 Razor Pages  

Let's create a .NET Core web application with .NET Core 3.1 . Open VS 2019 ➠ Select ASP .NET Core web application

Creating an ASP.NET Core application

In this example, we create an input file for upload the Excel file, and after uploading it, append the Excel data into DIV. Then, we download that Excel data and also create an Excel file using dummy data. The design is shown below:

Application design


HTML
 




x
21


 
1
<form asp-controller="Home" asp-action="Export">
2
    <div class="container">
3
        <div class="row">
4
            <div class="col-md-4">
5
                <input type="file" id="fileupload" name="files" class="form-control" />
6
            </div>
7
            <div class="col-md-3">
8
                <input type="button" name="Upload" value="Upload" id="btnupload" class="btn btn-primary" />
9
                <a href="@Url.Action("Download", "Home")">Download</a>
10
            </div>
11
            <div class="col-md-5">
12
                <input type="submit" name="Export" value="Create and Export" id="btnExport"
13
                       class="btn btn-primary" asp-action="Export" />
14
            </div>
15
        </div>
16
        <div class="clearfix">&nbsp;</div>
17
        <div class="row">
18
            <div id="divPrint"></div>
19
        </div>
20
    </div>
21
</form>



Code Snippet Explanation

The HTML code has the file upload control and a button to upload the file. The below JQuery code uploads the Excel file using Ajax. The code also performs client-side validation for file selection and extension checking. 

Once the request is successful, it appends the server response to the HTML. Read this post for handling Ajax request with ASP.NET Core 3.1 razor pages and this post for uploading files in ASP.NET Core 3.1 Razor Pages.

JavaScript
 




xxxxxxxxxx
1
53


 
1
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
2
<script type="text/javascript">
3
    $(function () {
4
        $('#btnupload').on('click', function () {
5
            var fileExtension = ['xls', 'xlsx'];
6
            var filename = $('#fileupload').val();
7
            if (filename.length == 0) {
8
                alert("Please select a file.");
9
                return false;
10
            }
11
            else {
12
                var extension = filename.replace(/^.*\./, '');
13
                if ($.inArray(extension, fileExtension) == -1) {
14
                    alert("Please select only excel files.");
15
                    return false;
16
                }
17
            }
18
            var fdata = new FormData();
19
            var fileUpload = $("#fileupload").get(0);
20
            var files = fileUpload.files;
21
            fdata.append(files[0].name, files[0]);
22
            $.ajax({
23
                type: "POST",
24
                url: "/Home/Import",
25
                beforeSend: function (xhr) {
26
                    xhr.setRequestHeader("XSRF-TOKEN",
27
                        $('input:hidden[name="__RequestVerificationToken"]').val());
28
                },
29
                data: fdata,
30
                contentType: false,
31
                processData: false,
32
                success: function (response) {
33
                    if (response.length == 0)
34
                        alert('Some error occured while uploading');
35
                    else {
36
                        $('#divPrint').html(response);
37
                    }
38
                },
39
                error: function (e) {
40
                    $('#divPrint').html(e.responseText);
41
                }
42
            });
43
        })
44
        $('#btnExport').on('click', function () {
45
            var fileExtension = ['xls', 'xlsx'];
46
            var filename = $('#fileupload').val();
47
            if (filename.length == 0) {
48
                alert("Please select a file then Import");
49
                return false;
50
            }
51
        });
52
    });
53
</script>



To import the file, create a post method in the Homecontroller.cs file and save the uploaded file into wwwroot folder then append it into the div.

C#
xxxxxxxxxx
1
58
 
1
public ActionResult Import()
2
        {
3
            IFormFile file = Request.Form.Files[0];
4
            string folderName = "UploadExcel";
5
            string webRootPath = _hostingEnvironment.WebRootPath;
6
            string newPath = Path.Combine(webRootPath, folderName);
7
            StringBuilder sb = new StringBuilder();
8
            if (!Directory.Exists(newPath))
9
            {
10
                Directory.CreateDirectory(newPath);
11
            }
12
            if (file.Length > 0)
13
            {
14
                string sFileExtension = Path.GetExtension(file.FileName).ToLower();
15
                ISheet sheet;
16
                string fullPath = Path.Combine(newPath, file.FileName);
17
                using (var stream = new FileStream(fullPath, FileMode.Create))
18
                {
19
                    file.CopyTo(stream);
20
                    stream.Position = 0;
21
                    if (sFileExtension == ".xls")
22
                    {
23
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats  
24
                        sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook  
25
                    }
26
                    else
27
                    {
28
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format  
29
                        sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook   
30
                    }
31
                    IRow headerRow = sheet.GetRow(0); //Get Header Row
32
                    int cellCount = headerRow.LastCellNum;
33
                    sb.Append("<table class='table table-bordered'><tr>");
34
                    for (int j = 0; j < cellCount; j++)
35
                    {
36
                        NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
37
                        if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
38
                        sb.Append("<th>" + cell.ToString() + "</th>");
39
                    }
40
                    sb.Append("</tr>");
41
                    sb.AppendLine("<tr>");
42
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
43
                    {
44
                        IRow row = sheet.GetRow(i);
45
                        if (row == null) continue;
46
                        if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
47
                        for (int j = row.FirstCellNum; j < cellCount; j++)
48
                        {
49
                            if (row.GetCell(j) != null)
50
                                sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
51
                        }
52
                        sb.AppendLine("</tr>");
53
                    }
54
                    sb.Append("</table>");
55
                }
56
            }
57
            return this.Content(sb.ToString());
58
        }


To download the file, follow the code below:

C#
xxxxxxxxxx
1
 
1
public ActionResult Download()
2
        {
3
            string Files = "wwwroot/UploadExcel/CoreProgramm_ExcelImport.xlsx";
4
            byte[] fileBytes = System.IO.File.ReadAllBytes(Files);
5
            System.IO.File.WriteAllBytes(Files, fileBytes);
6
            MemoryStream ms = new MemoryStream(fileBytes);
7
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "employee.xlsx");
8
        }


To create and export the file, let's take dummy data for an employee and export it.

C#
xxxxxxxxxx
1
64
 
1
public async Task<IActionResult> Export()
2
        {
3
            string sWebRootFolder = _hostingEnvironment.WebRootPath;
4
            string sFileName = @"Employees.xlsx";
5
            string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
6
            FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
7
            var memory = new MemoryStream();
8
            using (var fs = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Create, FileAccess.Write))
9
            {
10
                IWorkbook workbook;
11
                workbook = new XSSFWorkbook();
12
                ISheet excelSheet = workbook.CreateSheet("employee");
13
                IRow row = excelSheet.CreateRow(0);
14
15
                row.CreateCell(0).SetCellValue("EmployeeId");
16
                row.CreateCell(1).SetCellValue("EmployeeName");
17
                row.CreateCell(2).SetCellValue("Age");
18
                row.CreateCell(3).SetCellValue("Sex");
19
                row.CreateCell(4).SetCellValue("Designation");
20
21
                row = excelSheet.CreateRow(1);
22
                row.CreateCell(0).SetCellValue(1);
23
                row.CreateCell(1).SetCellValue("Jack Supreu");
24
                row.CreateCell(2).SetCellValue(45);
25
                row.CreateCell(3).SetCellValue("Male");
26
                row.CreateCell(4).SetCellValue("Solution Architect");
27
28
                row = excelSheet.CreateRow(2);
29
                row.CreateCell(0).SetCellValue(2);
30
                row.CreateCell(1).SetCellValue("Steve khan");
31
                row.CreateCell(2).SetCellValue(33);
32
                row.CreateCell(3).SetCellValue("Male");
33
                row.CreateCell(4).SetCellValue("Software Engineer");
34
35
                row = excelSheet.CreateRow(3);
36
                row.CreateCell(0).SetCellValue(3);
37
                row.CreateCell(1).SetCellValue("Romi gill");
38
                row.CreateCell(2).SetCellValue(25);
39
                row.CreateCell(3).SetCellValue("FeMale");
40
                row.CreateCell(4).SetCellValue("Junior Consultant");
41
42
                row = excelSheet.CreateRow(4);
43
                row.CreateCell(0).SetCellValue(4);
44
                row.CreateCell(1).SetCellValue("Hider Ali");
45
                row.CreateCell(2).SetCellValue(34);
46
                row.CreateCell(3).SetCellValue("Male");
47
                row.CreateCell(4).SetCellValue("Accountant");
48
49
                row = excelSheet.CreateRow(5);
50
                row.CreateCell(0).SetCellValue(5);
51
                row.CreateCell(1).SetCellValue("Mathew");
52
                row.CreateCell(2).SetCellValue(48);
53
                row.CreateCell(3).SetCellValue("Male");
54
                row.CreateCell(4).SetCellValue("Human Resource");
55
56
                workbook.Write(fs);
57
            }
58
            using (var stream = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open))
59
            {
60
                await stream.CopyToAsync(memory);
61
            }
62
            memory.Position = 0;
63
            return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);
64
        }


Let's run the application and see the output.

Application output


Find the Source Code in Github.com/CoreProgramm/.

File structure

You can see after upload the file it save it into the specified path. For more details, go through the following link:  https://www.coreprogramm.com/2020/01/import-and-export-excel-file-in-dotnet-core.html.


Active Server Pages .NET

Published at DZone with permission of Jayant Tripathy. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Implementing Effective Document Fraud Detection in C#
  • A Guide for Deploying .NET 10 Applications Using Docker's New Workflow
  • SHAP-Based Explainable AI (XAI) Integration With .Net Application
  • Why Architecture Matters: Structuring Modern Web Apps

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook