Export list entities to excel using C#


17/08/2021- duocnt    1983 Views    

Cài đặt thư viện.

  • Microsoft.Office.Interop.Excel.


Source code.

https://github.com/ntduoc/Export-to-excel.git

Code C#

  • Sử dụng thư viện
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.IO;

  • Phương thức.
public static void ExportToExcelFromListEntity<T>(List<T> entities, string FolderPath, string FileName)
        {
            var excel = new Application();
            var workBook = excel.Workbooks.Add();
            var sheet = (Worksheet)workBook.ActiveSheet;
            sheet.Name = FileName;
            try
            {
                int col = 1;
                foreach (var propInfo in entities[0].GetType().GetProperties())
                {
                    sheet.Cells[1, col] = propInfo.Name;
                    sheet.Cells[1, col].Font.Bold = true;
                    col++;
                }
                //put the data
                int k = 0;
                foreach (var entity in entities)
                {
                    int j = 1;
                    foreach (var propInfo in entity.GetType().GetProperties())
                    {
                        try
                        {
                            sheet.Cells[k + 2, j].Value = propInfo.GetValue(entity);
                            j++;
                        }
                        catch (System.Runtime.InteropServices.COMException comex)
                        {
                            Console.WriteLine(string.Format("{0}, Error - { 1} ",
                                comex.Message,propInfo.GetValue(entity)));
                            sheet.Cells[k + 2, j].Value = $"'{propInfo.GetValue(entity)}'";
                            j++;
                            continue;
                        }
                    }
                    k++;
                }
                if (!Directory.Exists(FolderPath))
                {
                    Directory.CreateDirectory(FolderPath);
                    var filePath = $"{FolderPath}\\" + FileName + ".xlsx";
                    workBook.Close(true, filePath);
                    Console.WriteLine($"Exported Successfully to {filePath}");
                }
            }
            catch (Exception ex)
            {
                workBook.Close(false);
                Console.WriteLine(ex.Message);
                Console.WriteLine("Export Failed.");
            }
        }


  • Gọi phương thức.

        -    Giả sử chúng ta đã có class DbContext với tên ExportExcelDb.


        -    Giả sử chúng ta đã có Entity Vendors.



        -    Gọi Phương thức như sau.

        static void Main(string[] args)
        {
 
            ExportExcelDb db = new ExportExcelDb();
            List<Vendor> vendors = db.Vendors.ToList();
            ExportFromListEntity.ExportToExcelFromListEntity<Vendor>(vendors, @"E:\Temp\ExportExcel", "Export from List Entity.xlsx");           
 
            Console.WriteLine("Done");
            Console.ReadLine();
        }


  • Kết quả.



Góp ý kiến

;
;