[Solved] Export ASP.Net GridView to Excel file using ClosedXML shown Encoded Text

Last Reply 6 months ago By dharmendr

Posted 6 months ago

Hi,

I used the code below to export a gridview to an Excel file. However after export, I face a problem with special characters(é instead of é as I'm using french). Moreover, i am getting   instead of blank fields.

How can i deal with this?

Thank you.

        public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
        {
            //required to avoid the run time error "  
            //Control 'GridView1' of type 'Grid View' must be placed inside a form tag with runat=server."  
        }

        protected void ExportGridToExcel()
        {
       
            DataTable dt = new DataTable("GridView_Data");
            foreach (TableCell cell in GridView1.HeaderRow.Cells)
            {
                dt.Columns.Add(cell.Text);
            }
            foreach (GridViewRow row in GridView1.Rows)
            {
                dt.Rows.Add();
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
                }
            }
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt);                
                Response.Clear();                
                Response.Buffer = true;
                Response.Charset = "";              
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";               
                Response.AddHeader("content-disposition", "attachment;filename=Test.xlsx");                               
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();
                }
            }
        }

        protected void btnExporter_Click(object sender, ImageClickEventArgs e)
        {
            ExportGridToExcel();
        }  

 

Posted 6 months ago Modified on 6 months ago

Hi Ikhlass,

Ikhlass says:
dt.Columns.Add(cell.Text);

 Change above line with

dt.Columns.Add(HttpUtility.HtmlDecode(cell.Text));

And

Ikhlass says:
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;

above line with

dt.Rows[dt.Rows.Count - 1][i] = HttpUtility.HtmlDecode(row.Cells[i].Text);

Check this example. Now please take its reference and correct your code.

Database

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

Download Northwind Database

Namespaces

C#

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

VB.Net

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

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string query = "SELECT TOP 10 CustomerID,ContactName,Country FROM Customers";
        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(conString))
        {
            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 ExportExcel(object sender, EventArgs e)
{
    DataTable dt = new DataTable("GridView_Data");
    foreach (TableCell cell in GridView1.HeaderRow.Cells)
    {
        dt.Columns.Add(HttpUtility.HtmlDecode(cell.Text));
    }
    foreach (GridViewRow row in GridView1.Rows)
    {
        dt.Rows.Add();
        for (int i = 0; i < row.Cells.Count; i++)
        {
            dt.Rows[dt.Rows.Count - 1][i] = HttpUtility.HtmlDecode(row.Cells[i].Text);
        }
    }
    using (XLWorkbook wb = new XLWorkbook())
    {
        wb.Worksheets.Add(dt);

        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(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "SELECT TOP 10 CustomerID,ContactName,Country FROM Customers"
        Dim cmd As SqlCommand = New SqlCommand(query)
        Using con As SqlConnection = New SqlConnection(conString)
            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 If
End Sub

Protected Sub ExportExcel(sender As Object, e As EventArgs)
    Dim dt As New DataTable("GridView_Data")
    For Each cell As TableCell In GridView1.HeaderRow.Cells
        dt.Columns.Add(HttpUtility.HtmlDecode(cell.Text))
    Next
    For Each row As GridViewRow In GridView1.Rows
        dt.Rows.Add()
        For i As Integer = 0 To row.Cells.Count - 1
            dt.Rows(dt.Rows.Count - 1)(i) = HttpUtility.HtmlDecode(row.Cells(i).Text)
        Next
    Next
    Using wb As New XLWorkbook()
        wb.Worksheets.Add(dt)

        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 New MemoryStream()
            wb.SaveAs(MyMemoryStream)
            MyMemoryStream.WriteTo(Response.OutputStream)
            Response.Flush()
            Response.End()
        End Using
    End Using
End Sub

Screenshot