Create Excel File With HtmlTextWriter Class

16-06-2016

C# Codes

private void ExportGridToExcel()
{
    Response.Clear();
    Response.Buffer = true;
    Response.ClearContent();
    Response.ClearHeaders();
    
    string fileName = "Devlet_Personel_Baskanligi_" 
    + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/ms-excel";
    Response.ContentEncoding = System.Text.Encoding.Unicode;
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
    Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
    
    StringWriter sw = new StringWriter();
    var hw = new HtmlTextWriter(sw);
    form1.RenderControl(hw);
    WriteTsv(bolKadros, htmltextwrtter);
    
    Response.Write(strwritter.ToString());
    Response.End();
}
static void WriteTsv<T>(IEnumerable<T> data, TextWriter output)
{
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    foreach (PropertyDescriptor prop in props)
    {
        output.Write(prop.DisplayName); // header
        output.Write("\t");
    }
    output.WriteLine();
    foreach (T item in data)
    {
        foreach (PropertyDescriptor prop in props)
        {
            if (prop.Converter != null)
            output.Write(prop.Converter.ConvertToString(prop.GetValue(item)));
            output.Write("\t");
        }
        output.WriteLine();
    }
}

ASPX File

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="DevletPersonelBaskanligiWebServis.Index" EnableEventValidation="false" %>
    <!--RegisterForEventValidation can only be called during Render(); hatasinin cozumu olarak yukarida  EnableEventValidation="false" eklendi -->
    <!DOCTYPE html>

        <html xmlns="http://www.w3.org/1999/xhtml">
            <head runat="server">
                <title></title>
            </head>
            <body>
                <form id="form1" runat="server">
                    <div>
                        <asp:Button ID="btnSend" OnClick="btnSend_OnClick" runat="server" Text="Gönder"  />

                        <asp:Button ID="btnSaveToExcel" OnClick="btnSaveToExcel_OnClick" runat="server" Text="Excel Dosyası Oluştur" />
                        <br />
                        <asp:GridView ID="grdAllValues" runat="server" AllowPaging="true" PageSize="100" OnPageIndexChanging="grdAllValues_OnPageIndexChanging"></asp:GridView>
                    </div>
                </form>
            </body>
        </html>

© 2019 All rights reserved. Codesenior.COM