FIX REPATER HEADER WHILE SCROLLING AND EXPORT TO EXCEL

RAVI 896 Reputation points
2024-02-26T11:09:28.23+00:00

Hello

This is my aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default3" %>
<html>
<head runat="server">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script> 
 <script type="text/javascript" src="dt.js"></script>
<link rel="stylesheet" type="text/css" href=dt.css />
<link rel="stylesheet" type="text/css" href=select.css />
     <script type="text/javascript" src="select.js"></script>
   
    <script type="text/javascript">
        $(document).ready(function () {
            var rowCount = $('table#list tbody tr').length;
            sessionStorage.setItem("rowCount", rowCount);
            // Remove the formatting to get integer data for summation
            var intVal = function (i) {
                return typeof i === 'string' ?
                    i.replace(/[\$,]/g, '') * 1 :
                    typeof i === 'number' ?
                        i : 0;
            };
            $('#list').DataTable({
                "ordering": false,
                
                 
    lengthMenu: [
            [2000, 1500, 1000, 500, -1],
            [2000, 1500, 1000, 500, 'All'],
        ],
                
                initComplete: function () {
                    this.api().columns([2]).every(function () {
                        var title = this.header();
                        //replace spaces with dashes
                        title = $(title).html().replace(/[\W]/g, '-');
                        var column = this;
                        var select = $('<select id="' + title + '" class="select2" ></select>')
                            .appendTo($(column.header()).empty())
                            .on('change', function () {
                                //Get the "text" property from each selected data 
                                //regex escape the value and store in array
                                var data = $.map($(this).select2('data'), function (value, key) {
                                    return value.text ? '^' + $.fn.dataTable.util.escapeRegex(value.text) + '$' : null;
                                });
                                //if no data selected use ""
                                if (data.length === 0) {
                                    data = [""];
                                }
                                //join array into string with regex or (|)
                                var val = data.join('|');
                                //search for the option(s) selected
                                column
                                    .search(val ? val : '', true, false)
                                    .draw();
                            });
                        column.data().unique().sort().each(function (d, j) {
                            select.append('<option value="' + d + '">' + d + '</option>');
                        });
                        //use column title as selector and placeholder
                        $('#' + title).select2({
                            multiple: true,
                            closeOnSelect: false,
                            width: '100%',
                            placeholder: "" + title
                        });
                        //initially clear select otherwise first option is selected
                        $('.select2').val(null).trigger('change');
                    });
                },
                footerCallback: function (tfoot, data, start, end, display) {
                    let api = this.api();
                    api.column(0).footer().innerHTML = "GRAND TOTAL";
                    // Total over all pages
                    total = api
                        .column(2, { search: 'applied' })
                        .data()
                        .reduce((a, b) => intVal(a) + intVal(b), 0);
                           
                         
                        
                    // Update footer
                    api.column(2).footer().innerHTML = total;
           
                }
            });
        });
    </script>
    <style>
        .select2-results__options[aria-multiselectable="true"] li {
            padding-left: 30px;
            position: relative;           
        }
            .select2-results__options[aria-multiselectable="true"] li:before {
                position: absolute;
                left: 8px;
                opacity: .6;
                top: 6px;
                font-family: "FontAwesome";
                content: "\f0c8";
            }
            .select2-results__options[aria-multiselectable="true"] li[aria-selected="true"]:before {
                content: "\f14a";
            }
    </style>
         
         
          <script src="table2excel.js"></script>

<script type="text/javascript">
    function Export() {
        $("[id*=list]").table2excel({
            filename: "LEATHER_STOCK.xls"               
        });
      
    }
</script> 
      
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <div class="container">
          <br />
        <table cellspacing="0" class="myClass" id="list" style="width: 400px; font-family: Calibri; font-size: 11px; border-collapse: collapse; border: 1px solid black;">
            <thead>
                <tr>
                    <th style="width:150px;">FIELD 1 </th>
                    <th style="width:150px;">FIELD 2 </th>
                    <th style="width:150px;">FIELD 3 </th>
                    <th style="width:150px;">FIELD 4 </th>
                  
                    
                </tr>
            </thead>
            <tbody style="border-collapse: collapse; border: 1px solid black;">
                <asp:Repeater ID="Repeater1" runat="server">
                    <ItemTemplate>
                        <tr>
                            <td style="border-collapse: collapse; border: 1px solid black; font-size: larger;"><%#Eval("FIELD1")%></td>
                            <td style="border-collapse: collapse; border: 1px solid black; font-size: larger;"><%#Eval("FIELD2")%></td>
                          
                            <td style="border-collapse: collapse; border: 1px solid black; font-size: larger;"><%#Eval("FIELD3")%></td>
                              <td style="border-collapse: collapse; border: 1px solid black; font-size: larger;"><%#Eval("FIELD4")%></td>
                                
                        
                        
                        
                        </tr>
                    </ItemTemplate>
                </asp:Repeater>
            </tbody>
            <tfoot>
                <tr>
                     
                         <td style="border-collapse: collapse; background: sandybrown; border: 1px solid black; font-size: larger; font-weight: bold;"></td>
                    
                    <td style="border-collapse: collapse; background: sandybrown; border: 1px solid black; font-size: larger; font-weight: bold;"></td>
                    <td style="border-collapse: collapse; background: sandybrown; border: 1px solid black; font-size: larger; font-weight: bold;"></td>
                
               </tr>
            </tfoot>
        </table>
    </div>
    </div>
    </form>
</body>
</html>

This is my c# page

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Configuration;
public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            
                DataTable dt = new DataTable();
                SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["CHEMIMSConnectionString"].ConnectionString);
                con1.Open();
                SqlCommand cmd1 = new SqlCommand("select * from Table1", con1);
                SqlDataAdapter ada1 = new SqlDataAdapter(cmd1);
                ada1.Fill(dt);
                con1.Close();
                con1.Dispose();
                Repeater1.DataSource = dt;
                Repeater1.DataBind();
                
           
        }
    }
    
    protected void Button3_Click1(object sender, EventArgs e)
    {
        Response.Redirect(Request.RawUrl);
    }
 
}

This is Sql code

USE [TEST]
GO
/****** Object:  Table [dbo].[Table1]    Script Date: 02/26/2024 16:36:01 ******/
SET IDENTITY_INSERT [dbo].[Table1] ON
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (1, N'B1/A1', N'APPLE', 10, N'10')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (2, N'B2/23-24', N'MANGO', 5, N'3')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (3, N'B2/23-24', N'BANANA', 5, N'2')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (4, N'B3/B1', N'CHERRY', 2, N'20')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (5, N'B4/A2', N'GUAVA', 4, N'25')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (6, N'B1/A1', N'APPLE', 10, N'10')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (7, N'B2/23-24', N'MANGO', 5, N'3')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (8, N'B2/23-24', N'BANANA', 5, N'2')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (9, N'B3/B1', N'CHERRY', 2, N'20')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (10, N'B4/A2', N'GUAVA', 4, N'25')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (11, N'B1/A1', N'APPLE', 10, N'10')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (12, N'B2/23-24', N'MANGO', 5, N'3')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (13, N'B2/23-24', N'BANANA', 5, N'2')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (14, N'B3/B1', N'CHERRY', 2, N'20')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (15, N'B4/A2', N'GUAVA', 4, N'25')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (16, N'B1/A1', N'APPLE', 10, N'10')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (17, N'B2/23-24', N'MANGO', 5, N'3')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (18, N'B2/23-24', N'BANANA', 5, N'2')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (19, N'B3/B1', N'CHERRY', 2, N'20')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (20, N'B4/A2', N'GUAVA', 4, N'25')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (21, N'B1/A1', N'APPLE', 10, N'10')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (22, N'B2/23-24', N'MANGO', 5, N'3')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (23, N'B2/23-24', N'BANANA', 5, N'2')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (24, N'B3/B1', N'CHERRY', 2, N'20')
INSERT [dbo].[Table1] ([ID], [Field1], [Field2], [Field3], [Field4]) VALUES (25, N'B4/A2', N'GUAVA', 4, N'25')
SET IDENTITY_INSERT [dbo].[Table1] OFF

  1. I want to fix header while scrolling
  2. On button click the data should export to excel with perfect alignment
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,265 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,636 Reputation points Microsoft Vendor
    2024-02-27T03:18:20.7333333+00:00

    Hi @RAVI,

    I want to fix header while scrolling

    You can try using the CSS below.

     table {
         margin: 0 auto;
         margin-top: 20px;
         width: 100%;
         position: relative;
         overflow: auto;
     }
     th, thead {
         position: sticky;
         top: 0;
         border: 1px solid #dddddd;
         background-color: #1f2d54;
         text-align: center;
         table-layout: fixed;
         word-break: break-word;
         height: 45px;
     }
    

    On button click the data should export to excel with perfect alignment

    Just add a button to your current code.

    <asp:Button ID="btnExport" Text="Export" runat="server" OnClientClick="return Export();" />
    All Code

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css" />
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                var rowCount = $('table#list tbody tr').length;
                sessionStorage.setItem("rowCount", rowCount);
                // Remove the formatting to get integer data for summation
                var intVal = function (i) {
                    return typeof i === 'string' ?
                        i.replace(/[\$,]/g, '') * 1 :
                        typeof i === 'number' ?
                            i : 0;
                };
                $('#list').DataTable({
                    "ordering": false,
                    lengthMenu: [
                        [2000, 1500, 1000, 500, -1],
                        [2000, 1500, 1000, 500, 'All'],
                    ],
                    initComplete: function () {
                        this.api().columns([2]).every(function () {
                            var title = this.header();
                            //replace spaces with dashes
                            title = $(title).html().replace(/[\W]/g, '-');
                            var column = this;
                            var select = $('<select id="' + title + '" class="select2" ></select>')
                                .appendTo($(column.header()).empty())
                                .on('change', function () {
                                    //Get the "text" property from each selected data 
                                    //regex escape the value and store in array
                                    var data = $.map($(this).select2('data'), function (value, key) {
                                        return value.text ? '^' + $.fn.dataTable.util.escapeRegex(value.text) + '$' : null;
                                    });
                                    //if no data selected use ""
                                    if (data.length === 0) {
                                        data = [""];
                                    }
                                    //join array into string with regex or (|)
                                    var val = data.join('|');
                                    //search for the option(s) selected
                                    column
                                        .search(val ? val : '', true, false)
                                        .draw();
                                });
                            column.data().unique().sort().each(function (d, j) {
                                select.append('<option value="' + d + '">' + d + '</option>');
                            });
                            //use column title as selector and placeholder
                            $('#' + title).select2({
                                multiple: true,
                                closeOnSelect: false,
                                width: '100%',
                                placeholder: "" + title
                            });
                            //initially clear select otherwise first option is selected
                            $('.select2').val(null).trigger('change');
                        });
                    },
                    footerCallback: function (tfoot, data, start, end, display) {
                        let api = this.api();
                        api.column(0).footer().innerHTML = "GRAND TOTAL";
                        // Total over all pages
                        total = api
                            .column(2, { search: 'applied' })
                            .data()
                            .reduce((a, b) => intVal(a) + intVal(b), 0);
                        // Update footer
                        api.column(2).footer().innerHTML = total;
                    }
                });
            });
        </script>
        <style>
            .select2-results__options[aria-multiselectable="true"] li {
                padding-left: 30px;
                position: relative;
            }
                .select2-results__options[aria-multiselectable="true"] li:before {
                    position: absolute;
                    left: 8px;
                    opacity: .6;
                    top: 6px;
                    font-family: "FontAwesome";
                    content: "\f0c8";
                }
                .select2-results__options[aria-multiselectable="true"] li[aria-selected="true"]:before {
                    content: "\f14a";
                }
            table {
                margin: 0 auto;
                margin-top: 20px;
                width: 100%;
                position: relative;
                overflow: auto;
            }
            th, thead {
                position: sticky;
                top: 0;
                border: 1px solid #dddddd;
                background-color: #1f2d54;
                text-align: center;
                table-layout: fixed;
                word-break: break-word;
                height: 45px;
            }
        </style>
        <script src="https://cdn.jsdelivr.net/npm/jquery-table2excel@1.1.1/dist/jquery.table2excel.min.js"></script>
        <script type="text/javascript">
            function Export() {
                $("[id*=list]").table2excel({
                    filename: "LEATHER_STOCK.xls"
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Button ID="btnExport" Text="Export" runat="server" OnClientClick="return Export();" />
                <div class="container">
                    <br />
                    <table cellspacing="0" class="myClass" id="list" style="width: 400px; font-family: Calibri; font-size: 11px; border-collapse: collapse; border: 1px solid black;">
                        <thead>
                            <tr>
                                <th style="width: 150px;">FIELD 1 </th>
                                <th style="width: 150px;">FIELD 2 </th>
                                <th style="width: 150px;">FIELD 3 </th>
                                <th style="width: 150px;">FIELD 4 </th>
                            </tr>
                        </thead>
                        <tbody style="border-collapse: collapse; border: 1px solid black;">
                            <asp:Repeater ID="Repeater1" runat="server">
                                <ItemTemplate>
                                    <tr>
                                        <td style="border-collapse: collapse; border: 1px solid black; font-size: larger;"><%#Eval("FIELD1")%></td>
                                        <td style="border-collapse: collapse; border: 1px solid black; font-size: larger;"><%#Eval("FIELD2")%></td>
                                        <td style="border-collapse: collapse; border: 1px solid black; font-size: larger;"><%#Eval("FIELD3")%></td>
                                        <td style="border-collapse: collapse; border: 1px solid black; font-size: larger;"><%#Eval("FIELD4")%></td>
                                    </tr>
                                </ItemTemplate>
                            </asp:Repeater>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td style="border-collapse: collapse; background: sandybrown; border: 1px solid black; font-size: larger; font-weight: bold;"></td>
                                <td style="border-collapse: collapse; background: sandybrown; border: 1px solid black; font-size: larger; font-weight: bold;"></td>
                                <td style="border-collapse: collapse; background: sandybrown; border: 1px solid black; font-size: larger; font-weight: bold;"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </form>
    </body>
    </html>
    

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. laab 0 Reputation points
    2024-02-28T16:39:51.7666667+00:00

    To fix the header while scrolling on your ASPX page, you can utilize CSS or JavaScript techniques. One approach is to use CSS to make the header sticky by setting its position to "fixed" and adjusting its styling accordingly. Here's an example CSS code: thead th { position: sticky; top: 0; background-color: #f5f5f5; /* Adjust as needed */ z-index: 999; }

    0 comments No comments