Export to Excel c# (.Net) Dot Net using EPPlus

Code Snippets 4 U

The below class object have to be initialized with path and list of names for the sheets.

The Save method arguments must be equal to the sheetNames provided. Use the below code in try catch block because I have not handled any exception.

 class SaveToExcel<T> where T : List<Object>
    {
        List<string> sheetNames;
        string path;
        public SaveToExcel(List<string> sheetNames, string path)
        {
            this.sheetNames = sheetNames;
            this.path = path;
        }
        public void Save(params T[] data)
        {
            // check if data and sheetnames are equal in count
            if (sheetNames.Count != data.Length)
            {
                Console.WriteLine("Names and Lists are not of same count");
                return;
            }

            // check if any name is empty in the sheetNames if yes give any arbitraroy name
            sheetNames.ForEach(item =>
            {
                if (item == string.Empty)
                {
                    sheetNames[sheetNames.IndexOf(item)] = new Random().Next().ToString();
                }
            });

            ExcelPackage excelPackage = new ExcelPackage(); // created a excel package

            // create sheet and save data for each object to corresponding sheet
            int index = 0;
            sheetNames.ForEach(item =>
            {
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(item);
                var cols = data[index][0].GetType().GetProperties().Select(item1 => item1.Name);

                int col = 1;
                cols.ToList().ForEach(column =>
                {
                    worksheet.Cells[1, col].Value = column;
                    col++;
                });

                // add data
                int row = 2;
                data[index].ForEach(dataObject =>
                {
                    col = 1;
                    cols.ToList().ForEach(column =>
                    {
                        worksheet.Cells[row, col].Value = dataObject.GetType().GetProperty(column).GetValue(dataObject);
                        col++;
                    });
                    row++;
                });
                
            });
            excelPackage.SaveAs(new FileInfo(path));
            excelPackage.Dispose();
        }
    }

Example Usage :

 class Program
    {
        static void Main(string[] args)
        {
            model1 one = new model1() { a = 4, b = 5 };
            model1 two = new model1() { a = 6, b = 7 };
            model2 three = new model2() { a = "four", b = 5 };
            model2 four = new model2() { a = "six", b = 8 };

            List<Object> list1 = new List<Object>();
            list1.Add(one); list1.Add(two);

            List<Object> list2 = new List<Object>();
            list2.Add(three); list2.Add(four);

            List<string> names = new List<string>() { "List1", "List2" };
            string path = @"D:\result.xlsx";

            new SaveToExcel<List<Object>>(names, path).Save(list1, list2);
            Console.ReadKey();
        }

Used Models :

 class model1
    {
        public int a { get; set; }
        public int b { get; set; }
    }

    class model2
    {
        public string a { get; set; }
        public int b { get; set; }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 62 = seventy