Align (Style) ClosedXML Cell in each row in excel using C# and VB.Net in ASP.Net

Last Reply 3 days ago By pandeyism

Posted 4 days ago

Here is my Code fill the grideview

Its working fine but the cells in Excel does not in center

how i make it centerd and how i make lines between cells and rows

Dim mydb As String
mydb = ConfigurationManager.ConnectionStrings("dbstring").ConnectionString.ToString
Dim cony As New OleDb.OleDbConnection
cony.ConnectionString = mydb
Dim drpcmd As New OleDbCommand
drpcmd.Connection = cony
drpcmd.CommandType = CommandType.StoredProcedure
drpcmd.CommandText = "Resr1"
Dim cnt As Integer
cnt = drp.SelectedValue
Dim dts As Date
dts = Now.Date.ToShortDateString
drpcmd.Parameters.Add("@dats", OleDbType.Date).Value = dts
drpcmd.Parameters.Add("@cnt", OleDbType.Integer).Value = cnt
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
cony.Open()
da.SelectCommand = drpcmd
da.Fill(dt)
' Label2.Text = "عدد الحجوزات بتاريخ اليوم فى مركز:   " & dt.Rows.Count & ""
Label2.Text = "عدد الحجوزات بتاريخ اليوم  " & dt.Rows.Count & ""
grd.DataSource = dt
grd.DataBind()
cony.Close()
cony = Nothing
btnexl.Visible = True

Using wb As New XLWorkbook()
    For i As Integer = 0 To grd.PageCount - 1
        grd.PageIndex = i
        ' grd.BindGrid()
        Dim dt As DataTable = New DataTable("Page_" & (i + 1))
        For cell As Integer = 0 To grd.HeaderRow.Cells.Count - 1 - 1
            dt.Columns.Add(grd.HeaderRow.Cells(cell).Text)

        Next
        For Each row As GridViewRow In grd.Rows
            dt.Rows.Add()
            For j As Integer = 0 To row.Cells.Count - 1 - 1
                If row.Cells(j).Controls.Count > 0 Then
                    dt.Rows(dt.Rows.Count - 1)(j) = (TryCast(row.Cells(j).Controls(1), Label)).Text
                Else
                    dt.Rows(dt.Rows.Count - 1)(j) = row.Cells(j).Text
                End If
            Next
        Next
        wb.Worksheets.Add(dt)

    Next
    wb.Worksheets.FirstOrDefault().RightToLeft = True
    Response.Clear()
    Response.Buffer = True
    Response.Charset = ""
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    Response.AddHeader("content-disposition", "attachment;filename=Resrv.xlsx")
    Using MyMemoryStream As MemoryStream = New MemoryStream()
        wb.SaveAs(MyMemoryStream)
        MyMemoryStream.WriteTo(Response.OutputStream)
        Response.Flush()
        Response.[End]()
    End Using
End Using      

And I have another button on Form when user clicked it, It will export data to excel

Thank you

Posted 3 days ago

Hi y.alim,

Refer below sample.

HTML

<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>
<br />
<asp:Button Text="Export" OnClick="ExportExcel" runat="server" />

Namespaces

C#

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

VB.Net

Imports System.IO
Imports System.Data
Imports ClosedXML.Excel

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "الولايات المتحدة الأمريكية");
        dt.Rows.Add(2, "Mudassar Khan", "الهند");
        dt.Rows.Add(3, "Suzanne Mathews", "فرنسا");
        dt.Rows.Add(4, "Robert Schidner", "روسيا");
        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(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())
    {
        var ws = wb.Worksheets.Add(dt);
        for (int i = 1; i <= dt.Rows.Count + 1; i++)
        {
            for (int j = 1; j <= dt.Columns.Count; j++)
            {
                ws.Cell(i, j).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                ws.Cell(i, j).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
            }
        }
        wb.Worksheets.FirstOrDefault().RightToLeft = true;
        ws.Table(0).ShowAutoFilter = false;
        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
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
        dt.Rows.Add(1, "John Hammond", "الولايات المتحدة الأمريكية")
        dt.Rows.Add(2, "Mudassar Khan", "الهند")
        dt.Rows.Add(3, "Suzanne Mathews", "فرنسا")
        dt.Rows.Add(4, "Robert Schidner", "روسيا")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub

Protected Sub ExportExcel(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = New DataTable("GridView_Data")
    For Each cell As TableCell In GridView1.HeaderRow.Cells
        dt.Columns.Add(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) = row.Cells(i).Text
        Next
    Next

    Using wb As XLWorkbook = New XLWorkbook()
        Dim ws = wb.Worksheets.Add(dt)
        For i As Integer = 1 To dt.Rows.Count + 1
            For j As Integer = 1 To dt.Columns.Count
                ws.Cell(i, j).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center)
                ws.Cell(i, j).Style.Border.OutsideBorder = XLBorderStyleValues.Thin
            Next
        Next

        wb.Worksheets.FirstOrDefault().RightToLeft = True
        ws.Table(0).ShowAutoFilter = False
        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