2025年2月17日 星期一

WebClient Download json

 參考引用:How To Display JSON Data Into GridView

----

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;


namespace _5M_Solution

{

  public partial class Harqat_Maqbozat_Grid : System.Web.UI.Page

  {

    protected void Page_Load(object sender, EventArgs e)

    {

      if (!this.IsPostBack)

      {

        this.GetJsonData();

      }

    }


    public void GetJsonData()

    {

      ServicePointManager.Expect100Continue = true;

      ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

      string json = (new WebClient()).DownloadString("https://receipt-voucher-default-rtdb.firebaseio.com/receipts.json");

      Dictionary<string, object> values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

      List<Receipt> receipts = new List<Receipt>();

      foreach (var entry in values)

      {

        receipts.Add(JsonConvert.DeserializeObject<Receipt>(entry.Value.ToString()));

      }

      gvDetails.DataSource = receipts;

      gvDetails.DataBind();

    }


    public class Receipt

    {

      public string amount { get; set; }

      public string branch_num { get; set; }

      public string machineID { get; set; }

      public string shift { get; set; }

      public string userID { get; set; }

      public string voucher_date { get; set; }

      public string voucher_number { get; set; }

    }


    public void ExportExcel()

    {

      try

      {

        Response.Clear();

        Response.Buffer = true;

        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "5M_MaqbozatDetails.xls"));

        Response.ContentType = "application/ms-excel";

        Response.Charset = "";

        this.EnableViewState = false;

        System.IO.StringWriter writer = new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter html = new System.Web.UI.HtmlTextWriter(writer);

        GetJsonData();

        //dl_JsonDetails.DataBind();

        gvDetails.RenderControl(html);

        Response.Write(writer.ToString());

        Response.Flush();

        Response.End();

      }

      catch (Exception ex)

      {

      }

    }


    protected void btn_ExportExcel_Click(object sender, EventArgs e)

    {

      ExportExcel();

    }


    protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

      gvDetails.PageIndex = e.NewPageIndex;

      this.GetJsonData();

    }


    protected void dd_SearchByBranchNo_SelectedIndexChanged(object sender, EventArgs e)

    {


    }

  }

}


沒有留言:

張貼留言