In this blog we will see how to convert HTML string to Excel in asp.net using c# with example. Converting html to excel in this blog does not contain any third party library. All the classes and namespaces available in .Net framework. 

Create HTML page

Step 1. Create one .html page in your project and design it according to your requirements. Or you can download any sample html template from internet and put it to proper folder in project.

Sample.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

</head>

<body>

    <h1>My Invoice Sample</h1>

    <table border="1">

        <tr>

            <td>

                <img src="http://localhost:49625/images/logo.jpg" style="width: 200px; height: 70px;" />

            </td>

        </tr>

    </table>

    <table border="1">

        <tr>

            <td>PROJECT : 

            </td>

            <td>[ProjectTitle]

            </td>

        </tr>

        <tr>

            <td>CLIENT : 

            </td>

            <td>[ClientName]

            </td>

        </tr>

        <tr>

            <td>ADDRESS : 

            </td>

            <td>[ClientAddress]

            </td>

        </tr>

        <tr>

            <td>EMAIL : 

            </td>

            <td>[ClientEmailAddress]

            </td>

        </tr>

        <tr>

            <td>DATE : 

            </td>

            <td>[Date]

            </td>

        </tr>

    </table>

    <table border="1">

        <thead>

            <tr>

                <th>SERVICE</th>

                <th>DESCRIPTION</th>

                <th>PRICE</th>

                <th>QTY</th>

                <th>TOTAL</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>Data collection</td>

                <td>Collected data</td>

                <td>Rs.500.00</td>

                <td>1</td>

                <td>Rs. 500.00</td>

            </tr>

            <tr>

                <td colspan='4'>SUBTOTAL</td>

                <td>----</td>

            </tr>

            <tr>

                <td colspan='4'>GST 18%</td>

                <td>----</td>

            </tr>

            <tr>

                <td colspan='4'>GRAND TOTAL</td>

                <td>Rs. 500.00</td>

            </tr>

        </tbody>

    </table>

    <table border="1">

        <tr>

            <td>Invoice generated automatic through computer. Do not required seal and signature.  

            </td>

        </tr>

    </table>

</body>

</html>

In this sample html page I have used some text with square brackets, which will be replace with dynamic values entered by user.

Generate Excel and Save to folder

Step 1. Create a folder with name excels in your project where generated excel from code will be save.

Step to create new folder: Right click on project-> Add-> New Folder.

Step 2. Now create ConvertHTMLtoExcel.aspx page to write below code. Here I have used two namespaces System.IO and System.Text. Please read my comments to understand code properly.

Step to create new page: Right click on project-> Add-> Add New Item-> Select Web Form-> Add.

ConvertHTMLtoExcel.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ConvertHTMLtoExcel.aspx.cs" Inherits="ConvertHTMLtoExcel" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Convert HTML to Excel</title>

    <style type="text/css">

        h2, table {

            display: table;

            margin: 40px auto;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <h2>Generate HTML to Excel</h2>

            <table>

                <tr>

                    <td>Project Title

                    </td>

                    <td>

                        <asp:TextBox ID="txtProjectTitle" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Cilent Name

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientName" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Cilent Address

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientAddress" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Client Email Address

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientEmailAddress" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Date

                    </td>

                    <td>

                        <asp:TextBox ID="txtDate" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <asp:Button Text="Generate Excel" ID="btnGenerateExcel" runat="server" OnClick="btnGenerateExcel_Click" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <asp:Label Text="" ID="lblMsg" runat="server" />

                    </td>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

ConvertHTMLtoExcel.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO; /* Add this Namespace */

using System.Text; /* Add this Namespace */

  

public partial class ConvertHTMLtoExcel : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

  

    }

  

    /* Generate button click event */

    protected void btnGenerateExcel_Click(object sender, EventArgs e)

    {

        string htmlstring = "", Filename = DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".xls", Filepath = "";

        htmlstring = File.ReadAllText(HttpContext.Current.Server.MapPath("~/template/Sample.html")); /* Read Sample.html from folder in our project */

  

        /* Replace square braket text with dynamic value insert by user. ie. [ProjectTitle] -> value */

        htmlstring = htmlstring.Replace("[ProjectTitle]", txtProjectTitle.Text);

        htmlstring = htmlstring.Replace("[ClientName]", txtClientName.Text);

        htmlstring = htmlstring.Replace("[ClientAddress]", txtClientAddress.Text);

        htmlstring = htmlstring.Replace("[ClientEmailAddress]", txtClientEmailAddress.Text);

        htmlstring = htmlstring.Replace("[Date]", txtDate.Text);

  

        Filepath = "~/excels/" + Filename; /* Path to save generated Excel */

        fnGenerateExcel(htmlstring, Filepath);

    }

  

    /* Function to generate Excel */

    public void fnGenerateExcel(string html, string Filepath)

    {

        try

        {

            StringWriter sw = new StringWriter(new StringBuilder(html));

            HtmlTextWriter hw = new HtmlTextWriter(sw);

            StreamWriter sWriter = new StreamWriter(HttpContext.Current.Server.MapPath(Filepath));

            sWriter.Write(sw.ToString());

            sWriter.Close();

  

            lblMsg.Text = "Excel generated successfully. Please check your folder..!!";

        }

        catch (Exception ex)

        {

        }

    }

}

Excel would be save to folder in your project. Here I have used "excels" folder.

Generate Excel and Download

You can create a new page to write code for downloading generated excel. Your design page will remain same. Only the code of button click event will change. Code for generate excel and download is given below.

ConvertAndDownload.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO; /* Add this Namespace */

using System.Text; /* Add this Namespace */

  

public partial class ConvertAndDownload : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

  

    }

  

    /* Generate button click event */

    protected void btnGenerateExcel_Click(object sender, EventArgs e)

    {

        string htmlstring = "", Filename = DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".xls";

        htmlstring = File.ReadAllText(HttpContext.Current.Server.MapPath("~/template/Sample.html")); /* Read Sample.html from folder in our project */

  

        /* Replace square braket text with dynamic value insert by user. ie. [ProjectTitle] -> value */

        htmlstring = htmlstring.Replace("[ProjectTitle]", txtProjectTitle.Text);

        htmlstring = htmlstring.Replace("[ClientName]", txtClientName.Text);

        htmlstring = htmlstring.Replace("[ClientAddress]", txtClientAddress.Text);

        htmlstring = htmlstring.Replace("[ClientEmailAddress]", txtClientEmailAddress.Text);

        htmlstring = htmlstring.Replace("[Date]", txtDate.Text);

  

        fnGenerateExcel(htmlstring, Filename);

    }

  

    /* Function to generate Excel */

    public void fnGenerateExcel(string html, string Filename)

    {

        try

        {

            StringBuilder strBody = new StringBuilder(html);

  

            /* Code to download Excel */

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.Charset = "";

            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + Filename);

            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            HttpContext.Current.Response.Write(strBody);

            HttpContext.Current.Response.End();

            HttpContext.Current.Response.Flush();

        }

        catch (Exception ex)

        {

        }

    }

}

Hope this blog will help you. If I missed something or you have doubts comment below. Thank you..!!