Remove all style and Table format when exporting to Excel using ClosedXML in ASP.Net

Last Reply 4 months ago By pandeyism

Posted 4 months ago

Hello Everyone.

I am sure you are also going through this problem.

I have export my datatable to excel,for reading and writing i am using closedXML library.
But the problem is when i export the closedxml by default set some style in columns and set table format.

I want to remove these formats , and want to export like normal excel. Please advise.

Posted 4 months ago

Hi BugHunter,

Refer below sample.

Database

For this sample I have used of NorthWind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
    OnPageIndexChanging="OnPageIndexChanging" PageSize="5">
    <Columns>
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" ItemStyle-Width="150px" />
        <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100px" />
    </Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export To Excel" OnClick="ExportExcel" />

Namespaces

C#

using System.IO;
using System.Data;
using ClosedXML.Excel;
using System.Data.SqlClient;
using System.Configuration;

VB.Net

Imports System.IO
Imports System.Data
Imports ClosedXML.Excel
Imports System.Data.SqlClient
Imports System.Configuration

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}

private void BindGrid()
{
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 7 * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}

protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    this.BindGrid();
}

protected void ExportExcel(object sender, EventArgs e)
{
    using (XLWorkbook wb = new XLWorkbook())
    {
        //Set the Current Page.
        GridView1.AllowPaging = false;
        this.BindGrid();

        //Create a DataTable with schema same as GridView columns.
        DataTable dt = new DataTable("Customers");
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            dt.Columns.Add(cell.Text);
        }

        DataRow dr = dt.NewRow();
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            dr[cell.Text] = cell.Text;
        }
        //Add Header rows from GridView to DataTable.
        dt.Rows.Add(dr);
        //Loop and add rows from GridView to DataTable.
        foreach (GridViewRow row in GridView1.Rows)
        {
            dt.Rows.Add();
            for (int j = 0; j < row.Cells.Count; j++)
            {
                dt.Rows[dt.Rows.Count - 1][j] = HttpUtility.HtmlDecode(row.Cells[j].Text);
            }
        }

        var ws = wb.Worksheets.Add(dt.TableName);
        ws.Cell(1, 1).InsertData(dt.Rows);
        ws.Columns().AdjustToContents();

        //Export the Excel file.
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
        using (MemoryStream MyMemoryStream = new MemoryStream())
        {
            wb.SaveAs(MyMemoryStream);
            MyMemoryStream.WriteTo(Response.OutputStream);
            Response.Flush();
            Response.End();
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub

Private Sub BindGrid()
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(strConnString)
        Using cmd As SqlCommand = New SqlCommand("SELECT TOP 7 * FROM Customers")
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As DataTable = New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub

Protected Sub OnPageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    GridView1.PageIndex = e.NewPageIndex
    Me.BindGrid()
End Sub

Protected Sub ExportExcel(ByVal sender As Object, ByVal e As EventArgs)
    Using wb As XLWorkbook = New XLWorkbook()
        GridView1.AllowPaging = False
        Me.BindGrid()
        Dim dt As DataTable = New DataTable("Customers")
        For Each cell As TableCell In GridView1.HeaderRow.Cells
            dt.Columns.Add(cell.Text)
        Next
        Dim dr As DataRow = dt.NewRow()
        For Each cell As TableCell In GridView1.HeaderRow.Cells
            dr(cell.Text) = cell.Text
        Next
        dt.Rows.Add(dr)
        For Each row As GridViewRow In GridView1.Rows
            dt.Rows.Add()
            For j As Integer = 0 To row.Cells.Count - 1
                dt.Rows(dt.Rows.Count - 1)(j) = HttpUtility.HtmlDecode(row.Cells(j).Text)
            Next
        Next
        Dim ws = wb.Worksheets.Add(dt.TableName)
        ws.Cell(1, 1).InsertData(dt.Rows)
        ws.Columns().AdjustToContents()
        Response.Clear()
        Response.Buffer = True
        Response.Charset = ""
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx")

        Using MyMemoryStream As MemoryStream = New MemoryStream()
            wb.SaveAs(MyMemoryStream)
            MyMemoryStream.WriteTo(Response.OutputStream)
            Response.Flush()
            Response.[End]()
        End Using
    End Using
End Sub

Screenshot