Wednesday 27 May 2020

Export HTML string / table to Excel file formatted way with fixed width of column in ASP.Net using C#



protected void Button2_Click(object sender, EventArgs e)
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("RollNo");
        dt.Columns.Add("Name");
        dt.Columns.Add("College Name");
        DataRow dr;
        int rn = 1001;
        for (int i = 0; i < 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = (rn).ToString();
            dr[1] = "Raja_"+i.ToString();
            dr[2] = "Name of IT College_"+i.ToString();
            dt.Rows.Add(dr);
            rn++;
        }
        dt.AcceptChanges();
       
        StrExport.Append(@"<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'><head><title>Time</title>");
        StrExport.Append(@"<body lang=EN-US style='mso-element:header' id=h1><span style='mso--code:DATE'></span><div class=Section1>");
        StrExport.Append("<div style='font-size:12px;'>");
        // StrExport.Append(dvInfo.InnerHtml);
        StrExport.Append("<div><center style='font-size: 12pt;'><b>This excel generated by Krishna kumar chaturvedi</b></center></div><br />");

        StrExport.Append("<table align='center' border='1' bordercolor='#00aeef' class='reporttable1' cellspacing='0' cellpadding='0' style='font-size: 10pt;'>");
        //StrExport.Append("<tr align='center'>");
        string[] sty = {"70","300","90" };
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            StrExport.Append("<th style='width: "+ sty [i]+ "px;word-break: break-word;'>" + dt.Columns[i].ColumnName+"</th>");
        }
        StrExport.Append("</tr>");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            StrExport.Append("<tr>");
            for (int c = 0; c < dt.Columns.Count; c++)
            {
                StrExport.Append("<td>"+Convert.ToString(dt.Rows[i][c])+"</td>");
            }
            StrExport.Append("</tr>");
        }
        StrExport.Append("</table>");
        StrExport.Append("</div></body></html>");
        string strFile = "testexl.xls";
        string strcontentType = "application/excel";
        Response.ContentEncoding = Encoding.UTF8;
        Response.ClearContent();
        Response.ClearHeaders();
        Response.BufferOutput = true;
        Response.ContentType = strcontentType;
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
        Response.Write(StrExport.ToString());
        Response.Flush();
        Response.Close();
        Response.End();
    }



------------------------------------ Result



No comments:

Post a Comment

Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...