2021 European Technology Winner 2021 European Technology Winner
BLOG
MVC Kayıtları Excele Aktarma
Yazılım     2017-05-09 11:21:11
MVC Kayıtları Excele Aktarma
Controller

public void GridExportToExcel()
{
    string dosyaAdi = "ornek_dosya_adi";
    var table = // Buraya veritabanınından gelen herhangi bir dataSource gelebilir.( DataTable, DataSet, kendi oluşturduğunuz, herhangi bir ICollection tipinde entitiy model)
    var grid = new GridView();
    grid.DataSource = table;
    grid.DataBind();
 
    Response.ClearContent();
    Response.AddHeader("content-disposition", "attachment; filename=" + dosyaAdi + ".xls");
 
    Response.ContentType = "application/excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
 
    grid.RenderControl(htw);
 
    Response.Write(sw.ToString());
    Response.End();
}


Script

<script>
    $(document).ready(function () {
        $("#export").click(function () {
            ExportToExcel();
        });
    });
 
    function ExportToExcel() 
    {
        var url = '@Url.Action("GridExportToExcel", "ExportController")';
        window.open(url);
    }
</script>

Html

<a href="#" id="export">Excele Aktar</a>