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 -

SQL Database part

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

Create Database

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

Create Table

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

Customers Table

  1. USE [DbCustomers]
  2. GO
  3. /****** Object: Table [dbo].[Customers] Script Date: 2/18/2018 2:20:40 AM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. SET ANSI_PADDING ON
  9. GO
  10. CREATE TABLE [dbo].[Customers](
  11. [CustomerID] [int] IDENTITY(1,1) NOT NULL,
  12. [CustomerName] [varchar](50) NULL,
  13. [CustomerEmail] [varchar](50) NULL,
  14. [CustomerCountry] [varchar](50) NULL,
  15. CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
  16. (
  17. [CustomerID] ASC
  18. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  19. ) ON [PRIMARY]
  20. GO
  21. SET ANSI_PADDING OFF
  22. 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. namespace EPPlusCore.Models.DBF
  4. {
  5. public partial class Customers
  6. {
  7. public int CustomerId { get; set; }
  8. public string CustomerName { get; set; }
  9. public string CustomerEmail { get; set; }
  10. public string CustomerCountry { get; set; }
  11. }
  12. }

DbCustomersContext.cs

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

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. namespace EPPlusCore.Controllers
  13. {
  14. [Produces("application/json")]
  15. [Route("api/Customer")]
  16. public class CustomerController : Controller
  17. {
  18. private readonly IHostingEnvironment _hostingEnvironment;
  19. private readonly DbCustomersContext _db;
  20. public CustomerController(IHostingEnvironment hostingEnvironment, DbCustomersContext db)
  21. {
  22. _hostingEnvironment = hostingEnvironment;
  23. _db = db;
  24. }
  25. [HttpGet]
  26. [Route("ImportCustomer")]
  27. public IList<Customers> ImportCustomer()
  28. {
  29. string rootFolder = _hostingEnvironment.WebRootPath;
  30. string fileName = @"ImportCustomers.xlsx";
  31. FileInfo file = new FileInfo(Path.Combine(rootFolder, fileName));
  32. using (ExcelPackage package = new ExcelPackage(file))
  33. {
  34. ExcelWorksheet workSheet = package.Workbook.Worksheets["Customer"];
  35. int totalRows = workSheet.Dimension.Rows;
  36. List<Customers> customerList = new List<Customers>();
  37. for (int i = 2; i <= totalRows; i++)
  38. {
  39. customerList.Add(new Customers
  40. {
  41. CustomerName = workSheet.Cells[i, 1].Value.ToString(),
  42. CustomerEmail = workSheet.Cells[i, 2].Value.ToString(),
  43. CustomerCountry = workSheet.Cells[i, 3].Value.ToString()
  44. });
  45. }
  46. _db.Customers.AddRange(customerList);
  47. _db.SaveChanges();
  48. return customerList;
  49. }
  50. }
  51. [HttpGet]
  52. [Route("ExportCustomer")]
  53. public string ExportCustomer()
  54. {
  55. string rootFolder = _hostingEnvironment.WebRootPath;
  56. string fileName = @"ExportCustomers.xlsx";
  57. FileInfo file = new FileInfo(Path.Combine(rootFolder, fileName));
  58. using (ExcelPackage package = new ExcelPackage(file))
  59. {
  60. IList<Customers> customerList = _db.Customers.ToList();
  61. ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Customer");
  62. int totalRows = customerList.Count();
  63. worksheet.Cells[1, 1].Value = "Customer ID";
  64. worksheet.Cells[1, 2].Value = "Customer Name";
  65. worksheet.Cells[1, 3].Value = "Customer Email";
  66. worksheet.Cells[1, 4].Value = "customer Country";
  67. int i = 0;
  68. for (int row = 2; row <= totalRows + 1; row++)
  69. {
  70. worksheet.Cells[row, 1].Value = customerList[i].CustomerId;
  71. worksheet.Cells[row, 2].Value = customerList[i].CustomerName;
  72. worksheet.Cells[row, 3].Value = customerList[i].CustomerEmail;
  73. worksheet.Cells[row, 4].Value = customerList[i].CustomerCountry;
  74. i++;
  75. }
  76. package.Save();
  77. }
  78. return " Customer list has been exported successfully";
  79. }
  80. }
  81. }

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.