Asp.Net Mvc Excel Export (EPPlus) | C#

Merhaba, daha evvelden bir listeyi XLS olarak kaydetmeye yarayan makale eklemiştim.

http://www.zamkinos.net/blog/2019/11/24/asp-net-mvc-excel-export-c/

Bu örnekte herhangi bir ekstra paket kullanmamıştık ve XLS olarak dosya oluşturmuştuk.

EPPlus paketi ile XLSX formatında excel üretmek mümkün. Diğer makaledeki tüm metotlar aynı kalmak kaydıyla sadece şu iki metodu kullanmamız yeterli.

public byte[] OlusturExcel<T>(IEnumerable<T> liste, string calismaSayfasiAdi, List<string> excelHariciKolonlar)
        {
            ExcelPackage pck = new ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add(calismaSayfasiAdi);
            // Once basliklari yazalim.
            Dictionary<string, string> dictIngilizce = GenelIslemler.GetirIngilizceKarsilik();
            IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            int kolonSayac = 1;
            int satirSayac = 1;
            foreach (PropertyInfo prop in properties)
            {
                if (!excelHariciKolonlar.Contains(prop.Name))
                {
                    string baslik = "";
                    if (dictIngilizce.TryGetValue(prop.Name, out baslik) == false)
                    {
                        baslik = prop.Name;
                    }
                    ws.Cells[satirSayac, kolonSayac].Value = baslik;
                    ws.Cells[satirSayac, kolonSayac].Style.Font.Bold = true;
                    ws.Cells[satirSayac, kolonSayac].Style.Fill.PatternType = ExcelFillStyle.Solid;
                    ws.Cells[satirSayac, kolonSayac].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Yellow);
                    kolonSayac++;
                }
            }
            // Sonra iceriklere gecelim.
            satirSayac = 2;
            foreach (T item in liste)
            {
                kolonSayac = 1;
                foreach (PropertyInfo prop in properties)
                {
                    if (!excelHariciKolonlar.Contains(prop.Name))
                    {
                        object propValue = prop.GetValue(item, null);
                        if (propValue == null)
                        {
                            propValue = "";
                        }
                        ws.Cells[satirSayac, kolonSayac].Value = propValue.ToString().Trim();
                        kolonSayac++;
                    }
                }
                satirSayac++;
            }
            return pck.GetAsByteArray();
        }


   public static void ExcelResponseAyarlaEp(HttpResponseBase response, string dosyaAdi)
        {
            response.AddHeader("content-disposition", "attachment; filename=" + GenelIslemler.StrTarihGetir() + dosyaAdi);
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        }

Selamlar.

Leave a Reply

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