0

I created two GridViews: Members and Sponsors respectively and provided a total count of these two groups of people. My problem is I have two buttons which open in Excel: MemSpreadshtBTN (Member) and SPSpreadshtBTN (Sponsor) and I could not figure out how to get the count just for Members and the other just for Sponsors in Excel format. Please help.

ASPX

<asp:Label ID="totalCountLBL" runat="server" Text="Total Count:" Visible="false"></asp:Label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button
        ID="MemSpreadshtBTN" runat="server" OnClick="MemSpreadshtBTN_OnClick" Text="Member Spreadsheet" Visible="false" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button
        ID="SPSpreadshtBTN" runat="server" OnClick="SPSpreadshtBTN_OnClick" Text="Sponsor Spreadsheet" Visible="false" /><br />
<asp:GridView ID="GridView1"...>
...
<asp:GridView ID="GridView2"...>
...

C#

protected void TotalCount()
{
    conn.Open();
    try
    {
        string strTotalCt = "SELECT count(ConferenceRegistrationID) FROM ConferenceRegistration cr, Conference con WHERE con.ConferenceID=cr.ConferenceIDNum AND con.ConferenceID=@confID AND cr.Deleted='N'";
        SqlCommand ChkTotal = new SqlCommand(strTotalCt, conn);
        ChkTotal.Parameters.AddWithValue("@confID", conferenceDDL.SelectedValue);

        int temp = Convert.ToInt32(ChkTotal.ExecuteScalar().ToString());
        if (temp > 0)
        {
            totalCountLBL.Text = "<strong>Total Count:" + temp + "</strong>";
            totalCountLBL.Visible = true;
            MemSpreadshtBTN.Visible = true;
            SPSpreadshtBTN.Visible = true;
            returnLBL.Text = "<div style='margin-top: 10px;'><a href='~/Admin/Participants.aspx' onclick='window.history.go(-1); return false;'>Return to previous page</a>.</div>";
            returnLBL.Visible = true;
        }
        else
        {
            ChkOther();
        }
    }
    finally
    {
        conn.Close();
    }
}


protected void MemSpreadshtBTN_OnClick(object sender, EventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=ParticipantsSpreadsheet.xls");
    Response.ContentType = "application/vnd.xls";

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

    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    htmlWrite.Write(totalCountLBL.Text.ToString() + "<br />");
    GridView1.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();
}

protected void SPSpreadshtBTN_OnClick(object sender, EventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=ParticipantsSpreadsheet.xls");
    Response.ContentType = "application/vnd.xls";

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

    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    htmlWrite.Write(totalCountLBL.Text.ToString() + "<br />");
    GridView2.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();
}
Esther B
  • 25
  • 8
  • which part of the code is not working for you.Btnclicks or execute scalar to get the count from the select statement – user2526236 Feb 19 '15 at 21:31
  • @user2526236: All work, except for a small portion. Let's say there is a total count of 10 people on my page. 6 of them are Members and 4 are Sponsors. How do I make the count of 6 people shows up in Members spreadsheet and the count of 4 shows up in Sponsor spreadsheet? – Esther B Feb 19 '15 at 21:41
  • In ConferenceRegistration table in your DB do you have a column which differentiates sponsor or members. Is there a column by which you can differentiate if it is a sponsor or member? – user2526236 Feb 19 '15 at 22:10
  • @user2526236: Yes, I have a column named SponsorIDNum. – Esther B Feb 19 '15 at 22:14

2 Answers2

0

For this to work you need to install the excel package using nuget. search for 'excelpackage' and install it.

public DataTable gettable(int SponsorIDNum)
        {
        SqlConnection thisConnection = new SqlConnection("server=.;database=local;Integrated Security=SSPI")
        string query = "select * from tbluser where companyID =" +companyID;
        SqlDataAdapter ad = new SqlDataAdapter(query, thisConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds, "Categories");
        DataTable dt = ds.Tables[0];
        return dt;
        }
    protected void Member_Click(object sender, EventArgs e)
        {
        try
            {
            var pck = new OfficeOpenXml.ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add("Name of the Worksheet");
            // get your DataTable
            var tbl = gettable(0);
            ws.Cells["A1"].LoadFromDataTable(tbl, true, OfficeOpenXml.Table.TableStyles.Medium6);

            var dataRange = ws.Cells[ws.Dimension.Address.ToString()];
            dataRange.AutoFitColumns();

            Response.Clear();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=NameOfExcelFile.xlsx");
            Response.BinaryWrite(pck.GetAsByteArray());
            }
        catch (Exception ex)
            {
            // log exception
            throw;
            }
        Response.End();

        }

    protected void Sponsor_Click(object sender, EventArgs e)
        {
        try
            {
            var pck = new OfficeOpenXml.ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add("Name of the Worksheet1");
            // get your DataTable
            var tbl = gettable(1);
            ws.Cells["A1"].LoadFromDataTable(tbl, true, OfficeOpenXml.Table.TableStyles.Medium6);

            var dataRange = ws.Cells[ws.Dimension.Address.ToString()];
            dataRange.AutoFitColumns();

            Response.Clear();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=NameOfExcelFile.xlsx");
            Response.BinaryWrite(pck.GetAsByteArray());
            }
        catch (Exception ex)
            {
            // log exception
            throw;
            }
        Response.End();
        }

In the Members button click pass the column value. This should solve the problem. Source:Inserting data into an excel sheet from a DataTable

Community
  • 1
  • 1
user2526236
  • 1,538
  • 2
  • 15
  • 29
  • Can you demo how I use this in my code? Thank you. – Esther B Feb 19 '15 at 20:50
  • I was able to figure out a solution yesterday. It was your question about a column differentiating between sponsors and members that triggered my thought process. Thank you for your help! – Esther B Feb 20 '15 at 16:04
0

Resolved my problem by adding 2 labels on ASPX:

<asp:Label ID="MembertotalCountLBL" runat="server" Text="Total Count:" Visible="false"></asp:Label>
<asp:Label ID="SponsortotalCountLBL" runat="server" Text="Total Count:" Visible="false"></asp:Label>

Then added 2 methods similar to TotalCount() in C#;, except method #1 calls for SponsorsIDNum is null for Members and method #2 calls for SponsorsIDNum is not null for Sponsors in the Select statements. Afterwhich, I changed the followings and it works:

MemSpreadshtBTN

htmlWrite.Write(MembertotalCountLBL.Text.ToString() + "<br />");

SPSpreadshtBTN

htmlWrite.Write(SponsortotalCountLBL.Text.ToString() + "<br />");
Esther B
  • 25
  • 8