Import And Export Data Using EPPlus.Core

Introduction

In this post, we will see how we can import and export Excel data in ASP.NET Core. We are using EPPlus.Core library which helps us to perform import and export operations. I hope you will like it.

 

 

Prerequisites

Make sure you have installed Visual Studio 2017 (.Net Framework 4.6.1) and SQL Server.

In this post, we are going to - 

  • Create Database.
  • Create MVC application.
  • Install EPPlus.Core library
  • Use Entity Framework Core database first approach.
  • Create our Customer Controller.

SQL Database part

Here, you can find the script to create a database and its tables.

Create Database

  1. USE [master]  
  2. GO  
  3.   
  4. /****** Object:  Database [DbCustomers]    Script Date: 2/18/2018 2:19:48 AM ******/  
  5. CREATE DATABASE [DbCustomers]  
  6.  CONTAINMENT = NONE  
  7.  ON  PRIMARY   
  8. NAME = N'DbCustomers', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbCustomers.mdf' , SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  9.  LOG ON   
  10. NAME = N'DbCustomers_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbCustomers_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  11. GO  
  12.   
  13. ALTER DATABASE [DbCustomers] SET COMPATIBILITY_LEVEL = 110  
  14. GO  
  15.   
  16. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  17. begin  
  18. EXEC [DbCustomers].[dbo].[sp_fulltext_database] @action = 'enable'  
  19. end  
  20. GO  
  21.   
  22. ALTER DATABASE [DbCustomers] SET ANSI_NULL_DEFAULT OFF   
  23. GO  
  24.   
  25. ALTER DATABASE [DbCustomers] SET ANSI_NULLS OFF   
  26. GO  
  27.   
  28. ALTER DATABASE [DbCustomers] SET ANSI_PADDING OFF   
  29. GO  
  30.   
  31. ALTER DATABASE [DbCustomers] SET ANSI_WARNINGS OFF   
  32. GO  
  33.   
  34. ALTER DATABASE [DbCustomers] SET ARITHABORT OFF   
  35. GO  
  36.   
  37. ALTER DATABASE [DbCustomers] SET AUTO_CLOSE OFF   
  38. GO  
  39.   
  40. ALTER DATABASE [DbCustomers] SET AUTO_CREATE_STATISTICS ON   
  41. GO  
  42.   
  43. ALTER DATABASE [DbCustomers] SET AUTO_SHRINK OFF   
  44. GO  
  45.   
  46. ALTER DATABASE [DbCustomers] SET AUTO_UPDATE_STATISTICS ON   
  47. GO  
  48.   
  49. ALTER DATABASE [DbCustomers] SET CURSOR_CLOSE_ON_COMMIT OFF   
  50. GO  
  51.   
  52. ALTER DATABASE [DbCustomers] SET CURSOR_DEFAULT  GLOBAL   
  53. GO  
  54.   
  55. ALTER DATABASE [DbCustomers] SET CONCAT_NULL_YIELDS_NULL OFF   
  56. GO  
  57.   
  58. ALTER DATABASE [DbCustomers] SET NUMERIC_ROUNDABORT OFF   
  59. GO  
  60.   
  61. ALTER DATABASE [DbCustomers] SET QUOTED_IDENTIFIER OFF   
  62. GO  
  63.   
  64. ALTER DATABASE [DbCustomers] SET RECURSIVE_TRIGGERS OFF   
  65. GO  
  66.   
  67. ALTER DATABASE [DbCustomers] SET  DISABLE_BROKER   
  68. GO  
  69.   
  70. ALTER DATABASE [DbCustomers] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  71. GO  
  72.   
  73. ALTER DATABASE [DbCustomers] SET DATE_CORRELATION_OPTIMIZATION OFF   
  74. GO  
  75.   
  76. ALTER DATABASE [DbCustomers] SET TRUSTWORTHY OFF   
  77. GO  
  78.   
  79. ALTER DATABASE [DbCustomers] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  80. GO  
  81.   
  82. ALTER DATABASE [DbCustomers] SET PARAMETERIZATION SIMPLE   
  83. GO  
  84.   
  85. ALTER DATABASE [DbCustomers] SET READ_COMMITTED_SNAPSHOT OFF   
  86. GO  
  87.   
  88. ALTER DATABASE [DbCustomers] SET HONOR_BROKER_PRIORITY OFF   
  89. GO  
  90.   
  91. ALTER DATABASE [DbCustomers] SET RECOVERY SIMPLE   
  92. GO  
  93.   
  94. ALTER DATABASE [DbCustomers] SET  MULTI_USER   
  95. GO  
  96.   
  97. ALTER DATABASE [DbCustomers] SET PAGE_VERIFY CHECKSUM    
  98. GO  
  99.   
  100. ALTER DATABASE [DbCustomers] SET DB_CHAINING OFF   
  101. GO  
  102.   
  103. ALTER DATABASE [DbCustomers] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  104. GO  
  105.   
  106. ALTER DATABASE [DbCustomers] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  107. GO  
  108.   
  109. ALTER DATABASE [DbCustomers] SET  READ_WRITE   
  110. GO  

Create Table

After creating the database, we will move to create the "Customers" table.

Customers Table

  1. USE [DbCustomers]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Customers]    Script Date: 2/18/2018 2:20:40 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Customers](  
  15.     [CustomerID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [CustomerName] [varchar](50) NULL,  
  17.     [CustomerEmail] [varchar](50) NULL,  
  18.     [CustomerCountry] [varchar](50) NULL,  
  19.  CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED   
  20. (  
  21.     [CustomerID] ASC  
  22. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  23. ) ON [PRIMARY]  
  24.   
  25. GO  
  26.   
  27. SET ANSI_PADDING OFF  
  28. GO                                                         

Create your MVC application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Core Web Application, name your project, and click OK.

ASP.NET Core

Next, a new dialog will pop up for selecting the template. We are going to choose Web API template and click OK.

ASP.NET Core

Once our project is created, we will add EPPlus.Core library.

Installing EPPlus.Core library

In Package Manager console, run the following command.

Install-Package EPPlus.Core

ASP.NET Core

Adding Entity Framework Core database first approach.

Here, we need to create the EF model based on the existing database.

Tools => NuGet Package Manager => Package Manager Console.

In the package manager console, let’s run the following command:

ASP.NET Core

Scaffold-DbContext " Server =.; Initial Catalog = DbCustomers; Integrated Security = True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DBF

As you can see, the command above will generate a model from the existing database within Models/DBF folder.

ASP.NET Core

Customers.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace EPPlusCore.Models.DBF  
  5. {  
  6.     public partial class Customers  
  7.     {  
  8.         public int CustomerId { get; set; }  
  9.         public string CustomerName { get; set; }  
  10.         public string CustomerEmail { get; set; }  
  11.         public string CustomerCountry { get; set; }  
  12.     }  
  13. }  

DbCustomersContext.cs

  1. using System;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using Microsoft.EntityFrameworkCore.Metadata;  
  4.   
  5. namespace EPPlusCore.Models.DBF  
  6. {  
  7.     public partial class DbCustomersContext : DbContext  
  8.     {  
  9.         public virtual DbSet<Customers> Customers { get; set; }  
  10.   
  11.         public DbCustomersContext(DbContextOptions<DbCustomersContext> options) : base(options)  
  12.         {  
  13.   
  14.         }  
  15.   
  16.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  17.         {  
  18.             modelBuilder.Entity<Customers>(entity =>  
  19.             {  
  20.                 entity.HasKey(e => e.CustomerId);  
  21.   
  22.                 entity.Property(e => e.CustomerId).HasColumnName("CustomerID");  
  23.   
  24.                 entity.Property(e => e.CustomerCountry)  
  25.                     .HasMaxLength(50)  
  26.                     .IsUnicode(false);  
  27.   
  28.                 entity.Property(e => e.CustomerEmail)  
  29.                     .HasMaxLength(50)  
  30.                     .IsUnicode(false);  
  31.   
  32.                 entity.Property(e => e.CustomerName)  
  33.                     .HasMaxLength(50)  
  34.                     .IsUnicode(false);  
  35.             });  
  36.         }  
  37.     }  
  38. }  

Startup.cs

Now, we are opening Startup.cs and we need to add the following lines of code within ConfigureServices() method.

  1. string connection = "Server =.; Initial Catalog = DbCustomers; Integrated Security = True";  
  2. services.AddDbContext<DbCustomersContext>(options => options.UseSqlServer(connection));  

Create a Controller

Now, we are going to create a Controller. Right-click on the Controllers folder> > Add >> Controller>> selecting API Controller – Empty >> click Add. In the next dialog, name the controller as CustomerController and then click Add.

ASP.NET Core

ASP.NET Core

CustomerController.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Http;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using Microsoft.AspNetCore.Hosting;  
  8. using System.IO;  
  9. using OfficeOpenXml;  
  10. using System.Text;  
  11. using EPPlusCore.Models.DBF;  
  12.   
  13. namespace EPPlusCore.Controllers  
  14. {  
  15.     [Produces("application/json")]  
  16.     [Route("api/Customer")]  
  17.     public class CustomerController : Controller  
  18.     {  
  19.         private readonly IHostingEnvironment _hostingEnvironment;  
  20.         private readonly DbCustomersContext _db;  
  21.   
  22.         public CustomerController(IHostingEnvironment hostingEnvironment, DbCustomersContext db)  
  23.         {  
  24.             _hostingEnvironment = hostingEnvironment;  
  25.             _db = db;  
  26.         }  
  27.   
  28.   
  29.         [HttpGet]  
  30.         [Route("ImportCustomer")]  
  31.         public IList<Customers> ImportCustomer()  
  32.         {  
  33.   
  34.   
  35.             string rootFolder = _hostingEnvironment.WebRootPath;  
  36.             string fileName = @"ImportCustomers.xlsx";  
  37.             FileInfo file = new FileInfo(Path.Combine(rootFolder, fileName));  
  38.   
  39.             using (ExcelPackage package = new ExcelPackage(file))  
  40.             {  
  41.                 ExcelWorksheet workSheet = package.Workbook.Worksheets["Customer"];  
  42.                 int totalRows = workSheet.Dimension.Rows;  
  43.   
  44.                 List<Customers> customerList = new List<Customers>();  
  45.   
  46.                 for (int i = 2; i <= totalRows; i++)  
  47.                 {  
  48.                     customerList.Add(new Customers  
  49.                     {  
  50.                         CustomerName = workSheet.Cells[i, 1].Value.ToString(),  
  51.                         CustomerEmail = workSheet.Cells[i, 2].Value.ToString(),  
  52.                         CustomerCountry = workSheet.Cells[i, 3].Value.ToString()  
  53.                     });  
  54.                 }  
  55.   
  56.                 _db.Customers.AddRange(customerList);  
  57.                 _db.SaveChanges();  
  58.   
  59.                 return customerList;  
  60.             }  
  61.         }  
  62.   
  63.         [HttpGet]  
  64.         [Route("ExportCustomer")]  
  65.         public string ExportCustomer()  
  66.         {  
  67.             string rootFolder = _hostingEnvironment.WebRootPath;  
  68.             string fileName = @"ExportCustomers.xlsx";  
  69.   
  70.             FileInfo file = new FileInfo(Path.Combine(rootFolder, fileName));  
  71.   
  72.             using (ExcelPackage package = new ExcelPackage(file))  
  73.             {  
  74.   
  75.                 IList<Customers> customerList = _db.Customers.ToList();  
  76.   
  77.                 ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Customer");  
  78.                 int totalRows = customerList.Count();  
  79.   
  80.                 worksheet.Cells[1, 1].Value = "Customer ID";  
  81.                 worksheet.Cells[1, 2].Value = "Customer Name";  
  82.                 worksheet.Cells[1, 3].Value = "Customer Email";  
  83.                 worksheet.Cells[1, 4].Value = "customer Country";  
  84.                 int i = 0;  
  85.                 for (int row = 2; row <= totalRows + 1; row++)  
  86.                 {  
  87.                     worksheet.Cells[row, 1].Value = customerList[i].CustomerId;  
  88.                     worksheet.Cells[row, 2].Value = customerList[i].CustomerName;  
  89.                     worksheet.Cells[row, 3].Value = customerList[i].CustomerEmail;  
  90.                     worksheet.Cells[row, 4].Value = customerList[i].CustomerCountry;  
  91.                     i++;  
  92.                 }  
  93.   
  94.                 package.Save();   
  95.   
  96.             }  
  97.   
  98.             return " Customer list has been exported successfully";  
  99.         }  
  100.   
  101.          
  102.     }  
  103. }  

As you can see, we have two methods which will be used to perform the import and export operations.

So, let’s begin with ImportCustomer() method which is responsible to import data from excel file to customers table.

Note, in solution explorer, precisely in wwwroot folder, I added ImportCustomers.xlsx with data rows that are used to import data. To get path of the Excel file, we used the following lines of code

  1. string rootFolder = _hostingEnvironment.WebRootPath;  
  2. string fileName = @"ImportCustomers.xlsx";  
  3. FileInfo file = new FileInfo(Path.Combine(rootFolder, fileName));  

Then, we have an ExportCustomer() method which is used to export the data from customers table to ExportCustomer.xlsx file.

ASP.NET Core

Demo

Import Customers

Now, let’s run the application and call the following URI YourLocalHost/api/Customer/ImportCustomer.

Once finished, open Customers table and you will see that the data rows have been added successfully.

ImportCustomers.xlsx

ASP.NET Core

Customers table

ASP.NET Core

Export Customers

Now, we will call the following URI for exporting data rows from Customers table to ExportCustomers.xlsx.

YourLocalHost/api/Customer/ExportCustomer
 
Once finished, open ExportCustomers.xlsx file and you will see that the data rows have been exported successfully.

ExportCustomers.xlsx

ASP.NET Core

That’s all. Please send your feedback and queries in the comments box.