Export Data In EXCEL, PDF, CSV, Word, JSON, XML And Text File In .NET Core 3.1 Using MVC Core

This article demonstrates how to export functionality with different types of file formats like excel, pdf, word, csv, json, xml and text files using a MVC core and .net core 3.1 application. I have implemented the most frequently used file format to export data in real time projects.
 
Here I will explain step by step from scrach, an application to each file export option with an effective way in mvc core. Source code is attached so if you wish to download full flaged functionlity then you can download from .zip file attached with this article.
 
Tchknology tools and version used 
  • SQL Server management studio 2017
  • Visual stuio 2019
  • .net core 3.1 installed
Lets start with create new table in SQL server and insert 5k data in table using below script, 
  1. -- ==================== Create Table ============================    
  2. CREATE TABLE [dbo].[Products](    
  3.     [ProductID] [int] IDENTITY(1,1) NOT NULL,    
  4.     [ProductName] [nvarchar](max) NULL,    
  5.     [Price] [int] NOT NULL,    
  6.     [ProductDescription] [nvarchar](max) NULL,    
  7.  CONSTRAINT [PK_dbo.Products] PRIMARY KEY CLUSTERED     
  8. (    
  9.     [ProductID] ASC    
  10. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]    
  11. ) ON [PRIMARY]    
  12. GO    
  13.     
  14. -- ===============================================    
  15. declare @productId int     
  16. select @productId = 1    
  17. declare @ProductName varchar(100)    
  18. declare @Price int    
  19. declare @Productdescription varchar(500)    
  20.     
  21. -- ================================================    
  22. --Loop through 1000 records and insert into table    
  23. -- ================================================    
  24.     
  25. while @productId >=1 and @productId <= 5000    
  26. begin    
  27. set @ProductName = 'PENT - '+ CAST(@productId as nvarchar(10))     
  28.     set @Price = 1000    
  29.     set @Productdescription = 'PENT - Description - '+ CAST(@productId as nvarchar(10))     
  30.     
  31. if (@productId%2 = 0)    
  32. begin    
  33.     set @ProductName = 'PENT - '+ CAST(@productId as nvarchar(10))     
  34.     set @Price = 2000    
  35.     set @Productdescription = 'PENT - Description - '+ CAST(@productId as nvarchar(10))     
  36. end    
  37. if(@productId%3 = 0)    
  38. begin    
  39.     set @ProductName = 'Color T-SHIRT - '+ CAST(@productId as nvarchar(10))     
  40.     set @Price = 3000    
  41.     set @Productdescription = 'Color T-SHIRT - Description - '+ CAST(@productId as nvarchar(10))     
  42. end    
  43. if(@productId%5=0)    
  44. begin    
  45.     set @ProductName = 'Designed Shirt - '+ CAST(@productId as nvarchar(10))     
  46.     set @Price = 5000    
  47.     set @Productdescription = 'Designed Shirt - Description - '+ CAST(@productId as nvarchar(10))    
  48. end    
  49.     insert into products(ProductName, Price,ProductDescription)     
  50.                 values( @ProductName ,@Price, @Productdescription)    
  51.     select @productId = @productId + 1    
  52. end    
  53. ---====================================================   
Once table created and data inserted in table we can create new project in visual studio.
 
If you do not have installed .net core 3.1 yet then you can download .net core different version from here Click Here
 
Lets start step by step with new project in visual studio. 
  • Start Visual Studio and click on click on create new project
  •  Click on Asp .Net Core Web application and click on next.
  • Give project name as per your requirement, Here I have given "ExportData"
  •  Select Web application Model-View-Controller and click on Create.
  • Once you click on create you are ready with your new project with default files and folders.
 
  • Click on project solution and check Target framework and confirm that its .net core 3.1. Lets run application and check its up and running without error. 
  • Lets start with require nuget pakages for export data in different file format. Here I am going to use two different nuget packages 
    1. ItextSharp
    2. XMLClosed
  • Lest install both packege from nuget package manager.
 
  
  • Now lets check under installed package we should be able to see both packages as below.
 
Lets create Model class, Service Interface and service class which implement service interface to get data from database using entity framework core. 
  1. public class Product  
  2.     {  
  3.         public int ProductID { getset; }  
  4.   
  5.         public string ProductName { getset; }  
  6.   
  7.         public int Price { getset; }  
  8.   
  9.         public string ProductDescription { getset; }  
  10.     }  
Add connection string value in Appsetting.json file
  1. {  
  2.   "ConnectionStrings": {  
  3.     "ExportDataContext""Data Source=.;Initial Catalog=MyTestDV;Persist Security Info=True;User ID=sa;Password=password"  
  4.   },  
  5.   "Logging": {  
  6.     "LogLevel": {  
  7.       "Default""Information",  
  8.       "Microsoft""Warning",  
  9.       "Microsoft.Hosting.Lifetime""Information"  
  10.     }  
  11.   },  
  12.   "AllowedHosts""*"  
  13. }  
Create DBContext class with name ExportContext
  1. public class ExportContext : DbContext  
  2.    {  
  3.        protected readonly IConfiguration _configuration;  
  4.   
  5.        public ExportContext(IConfiguration configuration)  
  6.        : base()  
  7.        {  
  8.            _configuration = configuration;  
  9.        }  
  10.   
  11.   
  12.        public virtual DbSet<Product> ProductsDetails { getset; }  
  13.   
  14.        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  15.        {  
  16.            if (!optionsBuilder.IsConfigured)  
  17.            {  
  18.                var connectionString = _configuration.GetConnectionString("ExportDataContext");  
  19.                optionsBuilder.UseSqlServer(connectionString, options => options.EnableRetryOnFailure());  
  20.            }  
  21.        }  
  22.   
  23.        protected override void OnModelCreating(ModelBuilder modelBuilder)  
  24.        {  
  25.            base.OnModelCreating(modelBuilder);  
  26.            modelBuilder.HasDefaultSchema("dbo");  
  27.            modelBuilder.Entity<Product>().ToTable("Products");  
  28.        }  
  29.    }  
Create Interface for repository and Product Repository 
  1. public interface IProductRepository   
  2.     {  
  3.         List<Product> GetProducts();  
  4.     }  
  1. public class ProductRepository : IProductRepository  
  2.    {  
  3.        public readonly ExportContext _context;  
  4.        public ProductRepository(ExportContext exportContext)   
  5.        {  
  6.            _context = exportContext;  
  7.        }  
  8.   
  9.        public List<Product> GetProducts()  
  10.        {  
  11.            return _context.ProductsDetails.ToList();  
  12.        }  
  13.    }  
Create Service interface and service class
  1. public interface IProductService  
  2.    {  
  3.        List<Product> GetProductData();  
  4.    }  
  1. public class ProductService : IProductService  
  2.    {  
  3.        public IProductRepository _productRepository;  
  4.        public ProductService(IProductRepository productRepository)  
  5.        {  
  6.            _productRepository = productRepository;  
  7.        }  
  8.        List<Product> IProductService.GetProductData()  
  9.        {  
  10.            return _productRepository.GetProducts();  
  11.        }  
  12.    }  
Create new controller with ExportDataController
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Xml;  
  8. using ClosedXML.Excel;  
  9. using CsvHelper;  
  10. using ExportData.Common;  
  11. using ExportData.IService;  
  12. using ExportData.Models;  
  13. using Grpc.Core;  
  14. using iTextSharp.text;  
  15. using iTextSharp.text.pdf;  
  16. using Microsoft.AspNetCore.Hosting;  
  17. using Microsoft.AspNetCore.Http;  
  18. using Microsoft.AspNetCore.Mvc;  
  19. using Nancy.Json;  
  20.   
  21. namespace ExportData.Controllers  
  22. {  
  23.     public class ExportDataController : Controller  
  24.     {  
  25.         private IProductService _productService;  
  26.         public ExportDataController(IProductService productService)  
  27.         {  
  28.             _productService = productService;  
  29.         }  
  30.         public IActionResult Index()  
  31.         {  
  32.             return View();  
  33.         }  
  34.   
  35.         [HttpPost]  
  36.         public IActionResult ExporDataToFile()  
  37.         {  
  38.             var dictioneryexportType = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());  
  39.             var exportType = dictioneryexportType["Export"];  
  40.             var products = GetProductsDetail();  
  41.             switch (exportType)  
  42.             {  
  43.                 case "Excel":  
  44.                     ExportToExcel(products);  
  45.                     break;  
  46.                 case "Csv":  
  47.                     ExportToCsv(products);  
  48.                     break;  
  49.                 case "Pdf":  
  50.                      ExportToPdf(products);  
  51.                     break;  
  52.                 case "Word":  
  53.                      ExportToWord(products);  
  54.                     break;  
  55.                 case "Json":  
  56.                      ExportToJson(products);  
  57.                     break;  
  58.                 case "Xml":  
  59.                      ExportToXML(products);  
  60.                     break;  
  61.                 case "Text":  
  62.                      ExportToText(products);  
  63.                     break;  
  64.             }  
  65.             return null;  
  66.         }  
  67.         private void ExportToExcel(DataTable products)  
  68.         {  
  69.             using (var workbook = new XLWorkbook())  
  70.             {  
  71.                 var worksheet = workbook.Worksheets.Add("Products");  
  72.                 var currentRow = 1;  
  73.                 worksheet.Cell(currentRow, 1).Value = "ProductID";  
  74.                 worksheet.Cell(currentRow, 2).Value = "ProductName";  
  75.                 worksheet.Cell(currentRow, 3).Value = "Price";  
  76.                 worksheet.Cell(currentRow, 4).Value = "ProductDescription";  
  77.   
  78.                 for (int i = 0; i < products.Rows.Count; i++)  
  79.                 {  
  80.                     {  
  81.                         currentRow++;  
  82.                         worksheet.Cell(currentRow, 1).Value = products.Rows[i]["ProductID"];  
  83.                         worksheet.Cell(currentRow, 2).Value = products.Rows[i]["ProductName"];  
  84.                         worksheet.Cell(currentRow, 3).Value = products.Rows[i]["Price"];  
  85.                         worksheet.Cell(currentRow, 4).Value = products.Rows[i]["ProductDescription"];  
  86.   
  87.                     }  
  88.                 }  
  89.                 using var stream = new MemoryStream();  
  90.                 workbook.SaveAs(stream);  
  91.                 var content = stream.ToArray();  
  92.                 Response.Clear();  
  93.                 Response.Headers.Add("content-disposition""attachment;filename=ProductDetails.xls");  
  94.                 Response.ContentType = "application/xls";  
  95.                 Response.Body.WriteAsync(content);  
  96.                 Response.Body.Flush();  
  97.             }  
  98.         }  
  99.         private void ExportToCsv(DataTable products)  
  100.         {  
  101.             StringBuilder sb = new StringBuilder();  
  102.   
  103.             IEnumerable<string> columnNames = products.Columns.Cast<DataColumn>().  
  104.                                               Select(column => column.ColumnName);  
  105.             sb.AppendLine(string.Join(",", columnNames));  
  106.   
  107.             foreach (DataRow row in products.Rows)  
  108.             {  
  109.                 IEnumerable<string> fields = row.ItemArray.Select(field =>  
  110.                   string.Concat("\"", field.ToString().Replace("\"""\"\""), "\""));  
  111.                 sb.AppendLine(string.Join(",", fields));  
  112.             }  
  113.             byte[] byteArray = ASCIIEncoding.ASCII.GetBytes(sb.ToString());  
  114.             Response.Clear();  
  115.             Response.Headers.Add("content-disposition""attachment;filename=ProductDetails.csv");  
  116.             Response.ContentType = "application/text";  
  117.             Response.Body.WriteAsync(byteArray);  
  118.             Response.Body.Flush();  
  119.         }  
  120.         private void ExportToPdf(DataTable products)  
  121.         {  
  122.   
  123.             if (products.Rows.Count > 0)  
  124.             {  
  125.                 int pdfRowIndex = 1;  
  126.                 string filename = "ProductDetails-" + DateTime.Now.ToString("dd-MM-yyyy hh_mm_s_tt");  
  127.                 string filepath = MyServer.MapPath("\\") + "" + filename + ".pdf";  
  128.                 Document document = new Document(PageSize.A4, 5f, 5f, 10f, 10f);  
  129.                 FileStream fs = new FileStream(filepath, FileMode.Create);  
  130.                 PdfWriter writer = PdfWriter.GetInstance(document, fs);  
  131.                 document.Open();  
  132.   
  133.                 Font font1 = FontFactory.GetFont(FontFactory.COURIER_BOLD, 10);  
  134.                 Font font2 = FontFactory.GetFont(FontFactory.COURIER, 8);  
  135.   
  136.                 float[] columnDefinitionSize = { 2F, 5F, 2F, 5F };  
  137.                 PdfPTable table;  
  138.                 PdfPCell cell;  
  139.   
  140.                 table = new PdfPTable(columnDefinitionSize)  
  141.                 {  
  142.                     WidthPercentage = 100  
  143.                 };  
  144.   
  145.                 cell = new PdfPCell  
  146.                 {  
  147.                     BackgroundColor = new BaseColor(0xC0, 0xC0, 0xC0)  
  148.                 };  
  149.   
  150.                 table.AddCell(new Phrase("ProductId", font1));  
  151.                 table.AddCell(new Phrase("ProductName", font1));  
  152.                 table.AddCell(new Phrase("Price", font1));  
  153.                 table.AddCell(new Phrase("ProductDescription", font1));  
  154.                 table.HeaderRows = 1;  
  155.   
  156.                 foreach (DataRow data in products.Rows)  
  157.                 {  
  158.                     table.AddCell(new Phrase(data["ProductId"].ToString(), font2));  
  159.                     table.AddCell(new Phrase(data["ProductName"].ToString(), font2));  
  160.                     table.AddCell(new Phrase(data["Price"].ToString(), font2));  
  161.                     table.AddCell(new Phrase(data["ProductDescription"].ToString(), font2));  
  162.   
  163.                     pdfRowIndex++;  
  164.                 }  
  165.   
  166.                 document.Add(table);  
  167.                 document.Close();  
  168.                 document.CloseDocument();  
  169.                 document.Dispose();  
  170.                 writer.Close();  
  171.                 writer.Dispose();  
  172.                 fs.Close();  
  173.                 fs.Dispose();  
  174.   
  175.                 FileStream sourceFile = new FileStream(filepath, FileMode.Open);  
  176.                 float fileSize = 0;  
  177.                 fileSize = sourceFile.Length;  
  178.                 byte[] getContent = new byte[Convert.ToInt32(Math.Truncate(fileSize))];  
  179.                 sourceFile.Read(getContent, 0, Convert.ToInt32(sourceFile.Length));  
  180.                 sourceFile.Close();  
  181.                 Response.Clear();  
  182.                 Response.Headers.Clear();  
  183.                 Response.ContentType = "application/pdf";  
  184.                 Response.Headers.Add("Content-Length", getContent.Length.ToString());  
  185.                 Response.Headers.Add("Content-Disposition""attachment; filename=" + filename + ".pdf;");  
  186.                 Response.Body.WriteAsync(getContent);  
  187.                 Response.Body.Flush();  
  188.             }  
  189.         }  
  190.         private void ExportToWord(DataTable products)  
  191.         {  
  192.             DataTable dtProduct = GetProductsDetail();  
  193.   
  194.             if (dtProduct.Rows.Count > 0)  
  195.             {  
  196.                 StringBuilder sbDocumentBody = new StringBuilder();  
  197.   
  198.                 sbDocumentBody.Append("<table width=\"100%\" style=\"background-color:#ffffff;\">");  
  199.                 if (dtProduct.Rows.Count > 0)  
  200.                 {  
  201.                     sbDocumentBody.Append("<tr><td>");  
  202.                     sbDocumentBody.Append("<table width=\"600\" cellpadding=0 cellspacing=0 style=\"border: 1px solid gray;\">");  
  203.   
  204.                     // Add Column Headers dynamically from datatable  
  205.                     sbDocumentBody.Append("<tr>");  
  206.                     for (int i = 0; i < dtProduct.Columns.Count; i++)  
  207.                     {  
  208.                         sbDocumentBody.Append("<td class=\"Header\" width=\"120\" style=\"border: 1px solid gray; text-align:center; font-family:Verdana; font-size:12px; font-weight:bold;\">" + dtProduct.Columns[i].ToString().Replace(".""<br>") + "</td>");  
  209.                     }  
  210.                     sbDocumentBody.Append("</tr>");  
  211.   
  212.                     // Add Data Rows dynamically from datatable  
  213.                     for (int i = 0; i < dtProduct.Rows.Count; i++)  
  214.                     {  
  215.                         sbDocumentBody.Append("<tr>");  
  216.                         for (int j = 0; j < dtProduct.Columns.Count; j++)  
  217.                         {  
  218.                             sbDocumentBody.Append("<td class=\"Content\"style=\"border: 1px solid gray;\">" + dtProduct.Rows[i][j].ToString() + "</td>");  
  219.                         }  
  220.                         sbDocumentBody.Append("</tr>");  
  221.                     }  
  222.                     sbDocumentBody.Append("</table>");  
  223.                     sbDocumentBody.Append("</td></tr></table>");  
  224.                 }  
  225.                 byte[] byteArray = ASCIIEncoding.ASCII.GetBytes(sbDocumentBody.ToString());  
  226.   
  227.                 Response.Clear();  
  228.                 Response.Headers.Add("Content-Type""application/msword");  
  229.                 Response.Headers.Add("Content-disposition""attachment; filename=ProductDetails.doc");  
  230.                 Response.Body.WriteAsync(byteArray);  
  231.                 Response.Body.FlushAsync();  
  232.             }  
  233.         }  
  234.         private void ExportToJson(DataTable products)  
  235.         {  
  236.             var listProduct = (from DataRow row in products.Rows  
  237.   
  238.                                select new Product()  
  239.                                {  
  240.                                    ProductID = row["ProductID"] != null ? Convert.ToInt32(row["ProductID"]) : 0,  
  241.                                    ProductName = Convert.ToString(row["ProductName"]),  
  242.                                    Price = row["Price"] != null ? Convert.ToInt32(row["Price"]) : 0,  
  243.                                    ProductDescription = Convert.ToString(row["ProductDescription"])  
  244.                                }).ToList();  
  245.             string jsonProductList = new JavaScriptSerializer().Serialize(listProduct);  
  246.             byte[] byteArray = ASCIIEncoding.ASCII.GetBytes(jsonProductList);  
  247.   
  248.             Response.Clear();  
  249.             Response.Headers.Clear();  
  250.             Response.ContentType = "application/json";  
  251.             Response.Headers.Add("Content-Length", jsonProductList.Length.ToString());  
  252.             Response.Headers.Add("Content-Disposition""attachment; filename=ProductDetails.json;");  
  253.             Response.Body.WriteAsync(byteArray);  
  254.             Response.Body.FlushAsync();  
  255.         }  
  256.         private void ExportToXML(DataTable products)  
  257.         {  
  258.             var listProduct = (from DataRow row in products.Rows  
  259.   
  260.                                select new Product()  
  261.                                {  
  262.                                    ProductID = row["ProductID"] != null ? Convert.ToInt32(row["ProductID"]) : 0,  
  263.                                    ProductName = Convert.ToString(row["ProductName"]),  
  264.                                    Price = row["Price"] != null ? Convert.ToInt32(row["Price"]) : 0,  
  265.                                    ProductDescription = Convert.ToString(row["ProductDescription"])  
  266.                                }).ToList();  
  267.             XmlDocument xml = new XmlDocument();  
  268.             XmlElement root = xml.CreateElement("Products");  
  269.             xml.AppendChild(root);  
  270.             foreach (var product in listProduct)  
  271.             {  
  272.                 XmlElement child = xml.CreateElement("Product");  
  273.                 child.SetAttribute("ProductID", product.ProductID.ToString());  
  274.                 child.SetAttribute("ProductName", product.ProductName);  
  275.                 child.SetAttribute("Price", product.Price.ToString());  
  276.                 child.SetAttribute("ProductDescription", product.ProductDescription);  
  277.                 root.AppendChild(child);  
  278.             }  
  279.             byte[] byteArray = ASCIIEncoding.ASCII.GetBytes(xml.OuterXml.ToString());  
  280.   
  281.             Response.Clear();  
  282.             Response.Headers.Clear();  
  283.             Response.ContentType = "application/xml";  
  284.             Response.Headers.Add("Content-Disposition""attachment; filename=ProductDetails.xml;");  
  285.             Response.Body.WriteAsync(byteArray);  
  286.             Response.Body.Flush();  
  287.         }  
  288.         private void ExportToText(DataTable products)  
  289.         {  
  290.             var delimeter = ",";  
  291.             var lineEndDelimeter = ";";  
  292.               
  293.   
  294.             StringBuilder sb = new StringBuilder();  
  295.             string Columns = string.Empty;  
  296.   
  297.             foreach (DataColumn column in products.Columns)  
  298.             {  
  299.                 Columns += column.ColumnName + delimeter;  
  300.             }  
  301.             sb.Append(Columns.Remove(Columns.Length - 1, 1) + lineEndDelimeter);  
  302.             foreach (DataRow datarow in products.Rows)  
  303.             {  
  304.                 string row = string.Empty;  
  305.                 foreach (object items in datarow.ItemArray)  
  306.                 {  
  307.                     row += items.ToString() + delimeter;  
  308.                 }  
  309.   
  310.                 sb.Append(row.Remove(row.Length - 1, 1) + lineEndDelimeter);  
  311.             }  
  312.             byte[] byteArray = ASCIIEncoding.ASCII.GetBytes(sb.ToString());  
  313.   
  314.             Response.Clear();  
  315.             Response.Headers.Clear();  
  316.             Response.ContentType = "application/Text";  
  317.             Response.Headers.Add("Content-Disposition""attachment; filename=ProductDetails.txt;");  
  318.             Response.Body.WriteAsync(byteArray);  
  319.             Response.Body.FlushAsync();  
  320.         }  
  321.         private DataTable GetProductsDetail()  
  322.         {  
  323.             var products = _productService.GetProductData().ToList();  
  324.   
  325.             DataTable dtProduct = new DataTable("ProductDetails");  
  326.             dtProduct.Columns.AddRange(new DataColumn[4] { new DataColumn("ProductID"),  
  327.                                             new DataColumn("ProductName"),  
  328.                                             new DataColumn("Price"),  
  329.                                             new DataColumn("ProductDescription") });  
  330.             foreach (var product in products)  
  331.             {  
  332.                 dtProduct.Rows.Add(product.ProductID, product.ProductName, product.Price, product.ProductDescription);  
  333.             }  
  334.   
  335.             return dtProduct;  
  336.         }  
  337.     }  
  338. }  
Add Index.cshtml for for ExportDataController
  1. @{  
  2.     ViewData["Title"] = "Index";  
  3. }  
  4. <div class="text-center">  
  5.     <h1 class="display-4">Welcome To Demo</h1>  
  6.     <h1 class="display-4">Export Data In Differnt File Format</h1>  
  7. </div>  
  8. <div class="jumbotron">  
  9.     <div class="lead">  
  10.         <div class="table-responsive col-md-12" id="divajaxCall">  
  11.                 @using (Html.BeginForm("ExporDataToFile""ExportData", FormMethod.Post))  
  12.                 {  
  13.                     <div class="row">  
  14.                         <div class="col-md-3">  
  15.                             <label>  
  16.                                 <input checked="checked" id="ExportExcel" name="Export"  
  17.                                        type="radio" value="Excel" />  
  18.                                 <i class="far fa-file-excel">  Export To Excel</i>  
  19.                             </label>  
  20.                         </div>  
  21.                         <div class="col-md-3">  
  22.                             <label>  
  23.                                 <input id="ExportCSV" name="Export" type="radio"  
  24.                                        value="Csv" />  
  25.                                 <i class="fas fa-file-csv">  Export To Csv</i>  
  26.                             </label>  
  27.                         </div>  
  28.                         <div class="col-md-3">  
  29.                             <label>  
  30.                                 <input id="ExportPdf" name="Export" type="radio"  
  31.                                        value="Pdf" />  
  32.                                 <i class="far fa-file-pdf">  Export To Pdf</i>  
  33.                             </label>  
  34.                         </div>  
  35.                         <div class="col-md-3">  
  36.                             <label>  
  37.                                 <input id="ExportToWord" name="Export" type="radio"  
  38.                                        value="Word" />  
  39.                                 <i class="far fa-file-word">  Export To Word</i>  
  40.                             </label>  
  41.                         </div>  
  42.                     </div>  
  43.                     <div class="row">  
  44.                         <div class="col-md-3">  
  45.                             <label>  
  46.                                 <input id="ExportToJson" name="Export" type="radio"  
  47.                                        value="Json" />  
  48.                                 <i class="fab fa-js-square">  Export To Json</i>  
  49.                             </label>  
  50.                         </div>  
  51.                         <div class="col-md-3">  
  52.                             <label>  
  53.                                 <input id="ExportToXml" name="Export" type="radio"  
  54.                                        value="Xml" />  
  55.                                 <i class="far fa-file-code">  Export To XML</i>  
  56.                             </label>  
  57.                         </div>  
  58.                         <div class="col-md-3">  
  59.                             <label>  
  60.                                 <input id="ExportToText" name="Export" type="radio"  
  61.                                        value="Text" />  
  62.                                 <i class="far fa-file-alt">  Export To Text</i>  
  63.                             </label>  
  64.                         </div>  
  65.                     </div>  
  66.                     <div class="row">  
  67.                         <div class="col-md-12" style="text-align:center; padding : 5px 5px 5px 5px">  
  68.                             <button id="btnExportData" type="submit" value="ExportData" name="action">  
  69.                                 <i class="fas fa-file-download"> Export Data </i>  
  70.                             </button>  
  71.                         </div>  
  72.                     </div>  
  73.                     <div class="row" style="text-align:center; padding : 5px 5px 5px 5px"></div>  
  74.                     <div class="divfooter">  
  75.                     </div>  
  76.                 }  
  77.             </div>  
  78.         </div>  
  79. </div>  
  80.   
  81. <script src="https://kit.fontawesome.com/00267cf40d.js" crossorigin="anonymous"></script>  
Add dependency for Dbcontext, ProductRepository and ProductServive as below in startup.cs file
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.             services.AddControllersWithViews();  
  4.             services.AddDbContext<ExportContext>();  
  5.             services.AddTransient<IProductRepository, ProductRepository>();  
  6.             services.AddTransient<IProductService, ProductService>();  
  7. }  
Add Default EndPoint which you want set as dafault route. Here I have put ExportData controller and Index method as default endpoint.
  1. app.UseEndpoints(endpoints =>  
  2.            {  
  3.                endpoints.MapControllerRoute(  
  4.                    name: "default",  
  5.                    pattern: "{controller=ExportData}/{action=Index}/{id?}");  
  6.            });  
Now we are ready with all require set up. Lets press F5 and run our application and it should display with all option for different type of file as below screen
  • Now lets select desire option and click on Export Data button. File will generate with desire output with selected option. Here I have tried all option one by one so you will be able to see all files downloaded at down in browser.
 
  • As per above snippet you able to see downloaded files.
In this article, I have demonstrated how to export data in different file formats using MVC core applications and .net core 3.1 which are most commonly used in real time projects. IAs reporting pupose we need to generate files as per need of client requirement. I thought to write this article which helps to get all solutions in a single article which will help users who are beginners or who need to export data in different types of file formats. Here I have attached source code as well so it might be useful for beginer for reference.
 
Happy Coding !!! I hope this article is useful. 


Similar Articles