ASP.NET 使用meta content= text/html 方式,將 Gridview export to Excel


meta content= text/html and  gridview export to excel 

資料匯出

由於是meta content= text/html 格式,所以報錯

格式與網頁一樣



.ASP
......................
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="btnExport" runat="server" Text="匯出" Font-Size="X-Large" Width="100px" />      
                <asp:GridView ID="GridView1" runat="server" />  
            </ContentTemplate>
            <triggers>
                 <asp:postbacktrigger controlid="btnExport" />
            </triggers>
        </asp:UpdatePanel>
    </div>
    </form>
</body>

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

    Private Sub DatatableBindToGridview()
        Dim dt As New DataTable
        With dt
            .Columns.Add("格式1", GetType(String))
            .Columns.Add("格式2", GetType(String))

            For i As Integer = 0 To 10
                .Rows.Add()
                .Rows(i).Item(0) = Format(i, "00")
                .Rows(i).Item(1) = Format(i, "00")
            Next
        End With

        With GridView1
            .DataSource = dt
            .DataBind()
            .HorizontalAlign = HorizontalAlign.Center
            .GridLines = GridLines.Both
            .HeaderStyle.BorderColor = Drawing.Color.Black
            .HeaderStyle.BackColor = Drawing.Color.Gray
            .HeaderStyle.ForeColor = Drawing.Color.White
            .Font.Size = 14
        End With
    End Sub

    Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

        If GridView1.Rows.Count < 0 Then Exit Sub

        If e.Row.RowType = DataControlRowType.DataRow Then
            If e.Row.RowIndex Mod 2 = 0 Then
                e.Row.BackColor = Drawing.Color.LemonChiffon
            Else
                e.Row.BackColor = Drawing.Color.AliceBlue
            End If
        End If
    End Sub

    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        '少了這個Sub
        'GridView1.RenderControl 時會產生
        '型別 'GridView' 的控制項 
        'GridView1 必須置於有 runat=server 的表單標記之中。
    End Sub

    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnExport.Click
        Dim sw As New System.IO.StringWriter
        Dim hw As New System.Web.UI.HtmlTextWriter(sw)
        GridView1.RenderControl(hw)

        With Response
            .ClearContent()
            .AppendHeader("Content-Disposition", "attachment; filename=" & Format(Now, "yyyyMMdd HHmmss") & ".xls")
            .ContentType = "application/vnd.ms-excel"
            .Write("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>")
            .Write("<style type=text/css>")
            .Write("td{mso-number-format:\@;}")
            .Write("</style>")
            .Write(sw.ToString())
            .End()
        End With
    End Sub

gridview 分頁 mssql 語法



先使用 select count 做總筆數與每頁幾筆與分頁的安排

layout 如右《 1 2 3 4 5 6 7 8 9 10 》
一次秀十頁與超過十頁後下拉選項的頁數

如程式點 8 且每頁10筆
則 Row BETWEEN (8 - 1) * 10 + 1 AND 8 * 10

如程式點 2 且每頁20筆
則 Row BETWEEN (2 - 1) * 20 + 1 AND 2 * 20

WITH tmpTable AS
(
SELECT ROW_NUMBER() OVER (ORDER BY A001 DESC) AS Row , A001, A002, A003, A004, 
A005, Pass
FROM              DSN001
WHERE A004 like '%2%'  
)
select * from tmpTable WHERE Row BETWEEN 2 AND 5

紅字為原本 sql 語法
除了排序的部份
要拆放在 row number
其他直接套用

這會有效減少頻寬的浪費

jquery ajax ashx

        function DivRemove(obj, str) {      
            var text = obj.name;
            var formdata = new FormData();
            formdata.append("myText", text);
            var ajax = new XMLHttpRequest();
            ajax.open("POST", "Dol.ashx");
            ajax.send(formdata);

            var newobj = '#' + str
            $(str).remove();
        }


<%@ WebHandler Language="VB" Class="Dol" %>

Imports System
Imports System.Web
Imports System.IO
Imports System.Web.SessionState

Public Class Dol: Implements IHttpHandler, IRequiresSessionState
   
  Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim savepath As String = ""
        Dim tempPath As String = ""
        tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
        savepath = context.Server.MapPath(tempPath)

        Dim FileName As String = context.Request("myText")
        'Dim FileNameArr As String() = Split(FileName, "\")
        'FileName = Format(Now, "yyyyMMdd HHmmss") & "." & FileNameArr(FileNameArr.Length - 1)

        If File.Exists(savepath & "\" & FileName) = True Then
            File.Delete(savepath & "\" & FileName)
        End If

    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

文字長度測試

<script type="text/javascript">
    function CountStrLen(obj1, obj2) {
        var str = obj1.value;
        obj2.value = str.length;
    }
</script>

    <input id="txt1" onkeyup="CountStrLen(this,txt2)" type="text" />
    <input id="txt2" type="text" />

-----------------------

    <asp:textbox id="TextBox1" runat="server"></asp:textbox>
    <asp:textbox id="TextBox2" runat="server"></asp:textbox>

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        TextBox1.Attributes.Add("onkeyup", "CountStrLen(" &amp; TextBox1.ClientID &amp; "," &amp; TextBox2.ClientID &amp; ")")
        TextBox2.ReadOnly = True
    End Sub

-----------------------

如果要接收長度不是 textbox 而是 label 或 span 等等有 ID 的 html tag
要用 innerHTML

   txtState.Attributes.Add("onkeyup", "CountStrLen1(" & txtState.ClientID & "," & Label1.ClientID & ")")

   function CountStrLen1(obj1, obj2) {
        var str = obj1.value;
        obj2.innerHTML = str.length;
    }

用二個DIV做出立體按鈕

 <div class="gradO parent" onclick="myFunction()">

    <div class="gradI parent">

        <div id="demo" style="width:100%;

            /*border:1px solid gray;*/

            word-break: break-all;

            text-align:center;

            padding:4px;

            color:white;

            font:20px arial;

            text-shadow: 2px 2px 4px #000000;">查詢</div>

    </div>

</div>

<style>

.gradO {

    /* border:1px solid gray;*/

    width:72px;

    height:72px;

    padding: 8px;

    border-radius:50%;

    background-image: linear-gradient(45deg, rgb(255,0,0), rgb(255,182,193));

}

.gradO:hover {

  box-shadow: 5px 10px 18px #d5d5d5;

 }

.parent {

  display: flex;

  justify-content: center;    

  align-content: center;      

  flex-wrap: wrap;

  cursor:default;

}

.parent:hover {

    cursor:pointer;

 }

.gradI {

    padding: 6px;

    width:56px;

    height:56px;

    border-radius:50%;

    background-image: linear-gradient(45deg, rgb(255,182,193), rgb(255,0,0));

}

</style>

省略 myFunction