Example usage for org.apache.poi.ss.util CellRangeAddress CellRangeAddress

List of usage examples for org.apache.poi.ss.util CellRangeAddress CellRangeAddress

Introduction

In this page you can find the example usage for org.apache.poi.ss.util CellRangeAddress CellRangeAddress.

Prototype

public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) 

Source Link

Document

Creates new cell range.

Usage

From source file:reports.allStaticReportsdynamic.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String monthrange = "";
    String periodlabel = "";
    String period = "Month"; //The default one
    String periodicgroupby = " "; //note that in the current query there is  an existing group by. Therefore this will be an extra infor to be added on the existing group by
    String isgroupby = "yes";
    try {//from w  w w  . j av a  2  s. com
        response.setContentType("text/html;charset=UTF-8");

        //a page to get Report of all the servlets
        String months[] = null;

        String year = "2015";
        String month = "";
        String county = "";
        String form = "moh731";

        if (request.getParameter("year") != null) {
            year = request.getParameter("year");
        }

        if (request.getParameter("county") != null) {
            county = request.getParameter("county");
        }

        if (request.getParameter("month") != null) {
            months = request.getParameterValues("month");
        }

        if (request.getParameter("form") != null) {
            form = request.getParameter("form");
        }
        if (request.getParameter("groupby") != null) {
            isgroupby = request.getParameter("groupby");
        }

        String pivotform = form;
        if (form.equalsIgnoreCase("MOH 731")) {
            form = "MOH731";
        }
        if (form.equalsIgnoreCase("MOH 711A")) {
            form = "MOH711";
        }
        if (form.equalsIgnoreCase("MOH 711 (New)")) {
            form = "moh711_new";
        }
        String facilitywhere = "";
        String yearwhere = "";
        String monthwhere = "";
        String countywhere = "";
        String districtwhere = "";
        String reporttype = "";
        String subcounty_countywhere = "";
        String indicatorslist = "all";

        String sections = "all";
        String subsections = "all";

        String indicatorswhere = "";

        //________________________________________________________________________________________________________________________________________________________            
        //________________________________________________________________________________________________________________________________________________________
        String duration = "";
        String semi_annual = "";
        String quarter = "";

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        String facil = "361";

        String yearmonthstart = "";
        String yearmonthend = "";
        //=====================================================================================================

        String header = "";

        String reportType = "";

        dbConn conn = new dbConn();

        if (request.getParameter("reportType") != null) {
            reportType = request.getParameter("reportType");
        }
        if (request.getParameter("indicators") != null) {
            indicatorslist = request.getParameter("indicators");
        }

        //--------------------------sections------------
        String sectionid[] = null;

        if (request.getParameterValues("sections") != null) {
            sectionid = request.getParameterValues("sections");
        }

        String sectionvals = "(";

        if (request.getParameterValues("sections") != null) {
            for (int a = 0; a < sectionid.length; a++) {
                if (a == sectionid.length - 1) {
                    sectionvals += sectionid[a] + "";
                } else {
                    sectionvals += sectionid[a] + ",";
                }
            }
        }
        sectionvals += ")";

        if (sectionvals.equals("()")) {
            indicatorswhere += " ";
        } else {

            indicatorswhere += " and sectionid in " + sectionvals + " ";

        }

        //______________________________________________________subsections_______________________________________

        String subsectionid[] = null;

        if (request.getParameterValues("subsection") != null) {
            subsectionid = request.getParameterValues("subsection");
        }

        String subsectionvals = "(";
        if (request.getParameterValues("subsection") != null) {
            for (int a = 0; a < subsectionid.length; a++) {
                if (a == subsectionid.length - 1) {
                    subsectionvals += subsectionid[a] + "";
                } else {
                    subsectionvals += subsectionid[a] + ",";
                }
            }
        }
        subsectionvals += ")";

        if (subsectionvals.equals("()")) {
            indicatorswhere += " ";
        } else {

            indicatorswhere += " and subsectionid in " + subsectionvals + " ";

        }

        //______________________________________________________subsections_______________________________________

        //add sections
        //special indicators

        if (indicatorslist.equals("special")) {

            indicatorswhere += " and specialindicator='1'";

        }

        String reportDuration = "";

        if (request.getParameter("reportDuration") != null) {
            reportDuration = request.getParameter("reportDuration");
        }

        if (request.getParameter("facility") != null && reportType.equals("2")) {
            try {
                facil = request.getParameter("facility");

                String getfacil = "select SubPartnerNom,CentreSanteId as mflcode from subpartnera where SubPartnerID='"
                        + facil + "'";
                conn.rs = conn.st.executeQuery(getfacil);

                while (conn.rs.next()) {

                    header += " FACILITY : " + conn.rs.getString(1).toUpperCase() + "     MFL CODE  :  "
                            + conn.rs.getString(2) + "  ";

                }
            } catch (SQLException ex) {
                Logger.getLogger(allStaticReportsdynamic.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        if (request.getParameter("county") != null && reportType.equals("2")) {
            try {
                county = request.getParameter("county");
                subcounty_countywhere = " (county.CountyID='" + county + "') and ";//20160711   
                String getcounty = "select County from county where CountyID='" + county + "'";
                conn.rs = conn.st.executeQuery(getcounty);

                while (conn.rs.next()) {

                    header += " COUNTY : " + conn.rs.getString(1).toUpperCase() + " ";

                }
            } catch (SQLException ex) {
                Logger.getLogger(allStaticReportsdynamic.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        int yearcopy = Integer.parseInt(year);
        String yearmonth = "" + year;
        int prevYear = yearcopy - 1;
        int maxYearMonth = 0;
        int monthcopy = 0;

        String currentperiodlabel = "";//a variable to hold the name of a period inside a conn.rs if .

        header += " YEAR : " + year + "";

        //        GET REPORT DURATION============================================
        //annually
        //____________________________________________________________________________________________________________Annual____________________________________
        if (reportDuration.equals("1")) {

            yearmonth = "Annual Report For " + year;
            duration = " and " + form + ".yearmonth BETWEEN '" + prevYear + "10' AND '" + year + "09'";

            period = "Year";

            periodicgroupby = ", period ";
            monthrange = year;

            // tbstatduration="year='"+year+"'";
        }
        //____________________________________________________________________________________________________________Semi_annual_____________________________          
        else if (reportDuration.equals("2")) {

            period = "Semi-Annual";

            periodicgroupby = ", period  ";

            try {
                String startMonth = "", endMonth = "";
                String semiannualarray[] = request.getParameterValues("semi_annual");

                String temporaryheader = " SEMI-ANNUAL";

                for (int p = 0; p < semiannualarray.length; p++) {

                    semi_annual = semiannualarray[p];

                    String getperiodname = "SELECT name as semiannual_name,months FROM semi_annual WHERE id='"
                            + semi_annual + "'";
                    conn.rs = conn.st.executeQuery(getperiodname);

                    if (conn.rs.next() == true) {

                        String monthsinsemiannual[] = conn.rs.getString("months").split(",");
                        currentperiodlabel = conn.rs.getString("semiannual_name");

                        //_________________add year at the end of period label                  
                        if (semi_annual.equals("1")) {
                            //periodname is in format oct-Mar we will make it to be in format Oct 2015-Mar 2016

                            currentperiodlabel = conn.rs.getString("semiannual_name").replace("-",
                                    " " + prevYear + "-") + " " + year;

                        } else {
                            //periodname is in format Apr-Sep we will make it to be in format Apr-Sep 2016      
                            currentperiodlabel = conn.rs.getString("semiannual_name") + " " + year;

                        }
                        //____________________   

                        if (p == 0) {

                            startMonth = monthsinsemiannual[0];

                            endMonth = monthsinsemiannual[5];

                            monthrange = currentperiodlabel;

                        }
                        if (p == semiannualarray.length - 1 && semiannualarray.length > 1) {
                            //last row

                            monthrange += " to " + currentperiodlabel;

                            //by now we expect monthrange to be something like Oct-Mar-Apr-Sep

                            endMonth = monthsinsemiannual[5];

                        }

                        if (periodlabel.equals("")) {
                            periodlabel = conn.rs.getString("semiannual_name");
                        }

                        else {

                            periodlabel += "_" + conn.rs.getString("semiannual_name");

                        }
                    } //end of conn.
                      //get the yearmonthstart date

                    if (p == 0 && semiannualarray.length > 1) {
                        //if the quarters selected are several
                        //this is the starting quarter                                  
                        temporaryheader += "S " + currentperiodlabel + " To ";

                        if (new Integer(semi_annual) == 1) {
                            //the year will be deducted by one if the selected months are 10, 11, 12
                            yearmonthstart = " " + form + ".yearmonth  between '" + prevYear + "" + startMonth
                                    + "' and ";

                        } else {

                            yearmonthstart = " " + form + ".yearmonth  between '" + year + "" + startMonth
                                    + "' and ";

                        }

                    }

                    else if (p == semiannualarray.length - 1 && semiannualarray.length > 1) {
                        //the last month 
                        temporaryheader += currentperiodlabel; //by now we expct something like from Semi-annuals oct-Mar to Apr -Sep
                        //this assumes that the last month can never be 
                        yearmonthend = "'" + year + "" + endMonth + "'";

                    }

                    else if (p == 0 && semiannualarray.length == 1) {
                        // the number of quarters selected is one   
                        temporaryheader += " " + currentperiodlabel + " ";

                        if (new Integer(semi_annual) == 1) {

                            yearmonthstart = " " + form + ".yearmonth between '" + prevYear + startMonth
                                    + "' and";

                        } else {

                            yearmonthstart = " " + form + ".yearmonth between '" + year + "" + startMonth
                                    + "' and ";

                        }
                        yearmonthend = "'" + year + "" + endMonth + "'"; //this assumes no end month date can come in oct-dec ..all the year month ends come on mar or sep

                    } //end of last monthly row

                } //end of for loop

                header += " " + temporaryheader + "";

            } catch (SQLException ex) {
                System.out.println(ex);
            }

            if (!semi_annual.equals("")) {

                duration = " and " + yearmonthstart + "" + yearmonthend;

            }

        }

        // ____________________________________________________________________________________________________Quarterly____________________

        else if (reportDuration.equals("3")) {
            period = "Quarter";

            periodicgroupby = ", period ";

            try {
                String startMonth = "", endMonth = "";
                String quarterarray[] = request.getParameterValues("quarter");

                String temporaryheader = " QUARTER";

                for (int p = 0; p < quarterarray.length; p++) {

                    quarter = quarterarray[p];

                    String getMonth = "SELECT months,name as qtrname FROM quarter WHERE id='" + quarter + "'";
                    conn.rs = conn.st.executeQuery(getMonth);

                    if (conn.rs.next() == true) {

                        String monthsinqtr[] = conn.rs.getString(1).split(",");

                        //_________________add year at the end of period label                  
                        if (quarter.equals("1")) {
                            //periodname is in format oct-Mar we will make it to be in format Oct 2015-Mar 2016
                            currentperiodlabel = conn.rs.getString("qtrname").replace("-", " " + prevYear + "-")
                                    + " " + year;

                        } else {
                            //periodname is in format Apr-Sep we will make it to be in format Apr-Sep 2016      
                            currentperiodlabel = conn.rs.getString("qtrname") + " " + year;

                        }
                        //____________________

                        if (p == 0) {

                            startMonth = monthsinqtr[0];

                            monthrange = conn.rs.getString("qtrname");

                            endMonth = monthsinqtr[2];
                        }
                        if (p == quarterarray.length - 1 && quarterarray.length > 1) {
                            //last row
                            monthrange += " to " + conn.rs.getString("qtrname");

                            endMonth = monthsinqtr[2];

                        }

                        if (periodlabel.equals(""))// note period label gets all the periods in my loop 
                        {
                            periodlabel = conn.rs.getString("qtrname");
                        }

                        else {

                            periodlabel += "_" + conn.rs.getString("qtrname");

                        }
                    } //end of if
                      //get the yearmonthstart date

                    if (p == 0 && quarterarray.length > 1) {
                        //if the quarters selected are several
                        //this is the starting quarter                                  
                        temporaryheader += "S " + currentperiodlabel + " To ";

                        if (new Integer(quarter) == 1) {
                            //the year will be deducted by one if the selected months are 10, 11, 12
                            yearmonthstart = " " + form + ".yearmonth  between '" + prevYear + "" + startMonth
                                    + "' and";

                        } else {

                            yearmonthstart = " " + form + ".yearmonth  between '" + year + "" + startMonth
                                    + "' and";

                        }

                    } else if (p == quarterarray.length - 1 && quarterarray.length > 1) {
                        //the last month 
                        temporaryheader += currentperiodlabel; //by now we expct something like from Quarters oct-Dec to Jan -Mar

                        yearmonthend = "'" + year + "" + endMonth + "'";

                    } else if (p == 0 && quarterarray.length == 1) {
                        // the number of quarters selected is one   
                        temporaryheader += " " + currentperiodlabel + " ";

                        if (new Integer(quarter) == 1) {

                            yearmonthstart = " " + form + ".yearmonth between '" + prevYear + startMonth
                                    + "' and ";

                            yearmonthend = " '" + prevYear + "" + endMonth + "' ";
                        } else {

                            yearmonthstart = " " + form + ".yearmonth between '" + year + "" + startMonth
                                    + "' and ";

                            yearmonthend = " '" + year + "" + endMonth + "' ";
                        }

                    } //end of last monthly row

                } //end of for loop

                header += " " + temporaryheader + "";

            } catch (SQLException ex) {
                System.out.println(ex);
            }

            if (!quarter.equals("")) {

                duration = " and " + yearmonthstart + "" + yearmonthend;

            }

        }

        //_______________________________________________________________________________________________________________monthly______________________________       
        else if (reportDuration.equals("4")) {

            period = "Month";

            periodicgroupby = ", period ";

            try {

                months = request.getParameterValues("month");

                String temporaryheader = " MONTH";

                for (int u = 0; u < months.length; u++) {

                    month = months[u];

                    String getMonth = "SELECT name FROM month WHERE id='" + month + "'";
                    conn.rs = conn.st.executeQuery(getMonth);

                    if (conn.rs.next() == true) {

                        //_________________add year at the end of period label                  
                        if (new Integer(month) >= 10 && new Integer(month) <= 12) {
                            //periodname is in format oct-Mar we will make it to be in format Oct 2015-Mar 2016
                            currentperiodlabel = conn.rs.getString("name").substring(0, 3) + " " + prevYear;

                        } else {
                            //periodname is in format Apr-Sep we will make it to be in format Apr-Sep 2016      
                            currentperiodlabel = conn.rs.getString("name").substring(0, 3) + " " + year;

                        }
                        //____________________    

                        if (u == 0) {
                            monthrange = conn.rs.getString(1);
                        }
                        if (u == months.length - 1 && months.length > 1) {
                            monthrange += " to " + conn.rs.getString(1);
                        }

                        if (periodlabel.equals("")) {
                            periodlabel = conn.rs.getString("name");
                        } else {
                            periodlabel += "_" + conn.rs.getString("name");
                        }
                    }
                    //get the yearmonthstart date

                    if (u == 0 && months.length > 1) {
                        //if the month selected are several
                        //this is the starting month                                  
                        temporaryheader += "S " + currentperiodlabel + " To ";

                        if (new Integer(month) >= 10) {

                            //the year will be deducted by one if the selected months are 10, 11, 12
                            yearmonthstart = " " + form + ".yearmonth  between '" + prevYear + "" + month
                                    + "' and ";

                        } else {
                            yearmonthstart = " " + form + ".yearmonth  between '" + year + "0" + month
                                    + "' and ";

                        }

                    } else if (u == months.length - 1 && months.length > 1) {
                        //the last month 

                        if (new Integer(month) >= 10) {

                            yearmonthend = "'" + prevYear + month + "'";

                        } else {

                            yearmonthend = "'" + year + "0" + month + "'";

                        }

                    } else if (u == 0 && months.length == 1) {
                        // the number of months selected is one   
                        temporaryheader += " " + currentperiodlabel + " ";

                        if (new Integer(month) >= 10) {

                            yearmonthstart = " " + form + ".yearmonth = " + prevYear + month;

                        } else {

                            yearmonthstart = " " + form + ".yearmonth = " + year + "0" + month;

                        }
                        yearmonthend = "";

                    } //end of last monthly row

                } //end of for loop

                header += " " + temporaryheader + "";

            } catch (SQLException ex) {
                Logger.getLogger(allStaticReportsdynamic.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (!month.equals("")) {

                duration = " and " + yearmonthstart + "" + yearmonthend;

            }

        } //end of monthly records 

        else {
            duration = "";
        }

        //if someone doest want periodic grouping, then dont add a group by in the report.. get numbers for all rows. 

        if (isgroupby.equals("No")) {

            periodicgroupby = "";

        }

        //______________________________________________________________________________________COUNTY , SUBCOUNTY AND 

        String subcountywhere = "";

        String subcounty = "";

        if (reportType.equalsIgnoreCase("2")) { //get data per county if the selected

            if (!request.getParameter("subcounty").equals("")) {

                subcounty = request.getParameter("subcounty");
                subcounty_countywhere = " (district.DistrictID='" + subcounty + "') and ";
            }

            if (!request.getParameter("county").equals("")) {
                county = request.getParameter("county");
                subcounty_countywhere = " (district.countyid='" + request.getParameter("county") + "') and ";//20160711 
            }

            if (!county.equals("")) {

                countywhere = " and district.countyid = '" + county + "'";

            }

            if (!subcounty.equals("")) {

                subcountywhere = " and subpartnera.DistrictID = '" + subcounty + "'";

            }

            if (!facil.equals("") && reportType.equalsIgnoreCase("2")) {

                facilitywhere = " and " + form + ".SubPartnerID = '" + facil + "'";

            }

        }

        String joinedwhwere = " where 1=1 " + duration + " " + countywhere + " " + subcountywhere + " "
                + facilitywhere;

        // System.out.println(""+joinedwhwere);
        //we need a case statement in our main query. This will allow for friendly display of 

        String myperiodcase = "";

        if (isgroupby.equals("No")) {

            myperiodcase = "'" + monthrange + "' as period";

        }

        else {

            if (period.equalsIgnoreCase("Year")) {

                myperiodcase = " case when Annee !='' then Annee else 'no year' end as period ";

            } else if (period.equalsIgnoreCase("Semi-Annual")) {

                myperiodcase = " case when (SUBSTRING(Yearmonth,5,6) >=01 and SUBSTRING(Yearmonth,5,6) <=03) || (SUBSTRING(Yearmonth,5,6) >=10 and SUBSTRING(Yearmonth,5,6) <=12) then 'Oct-Mar' "
                        + "when SUBSTRING(Yearmonth,5,6) >=04 and SUBSTRING(Yearmonth,5,6) <=09 then 'Apr-Sep' else 'No period' end as period ";
            } else if (period.equalsIgnoreCase("Quarter")) {

                myperiodcase = " case when (SUBSTRING(Yearmonth,5,6) >=01 and SUBSTRING(Yearmonth,5,6) <=03) then 'Jan-Mar'"
                        + "when  (SUBSTRING(Yearmonth,5,6) >=10 and SUBSTRING(Yearmonth,5,6) <=12) then 'Oct-Dec' "
                        + "when SUBSTRING(Yearmonth,5,6) >=04 and SUBSTRING(Yearmonth,5,6) <=06 then 'Apr-Jun' "
                        + "when SUBSTRING(Yearmonth,5,6) >=07 and SUBSTRING(Yearmonth,5,6) <=09 then 'Jul-Sep' "
                        + "else 'No period' end as period  ";
            } else if (period.equalsIgnoreCase("Month")) {

                myperiodcase = " case " + " when SUBSTRING(Yearmonth,5,6)= '01' then 'Jan' "
                        + " when SUBSTRING(Yearmonth,5,6)= '02' then 'Feb' "
                        + " when SUBSTRING(Yearmonth,5,6)= '03' then 'Mar' "
                        + " when SUBSTRING(Yearmonth,5,6)= '04' then 'Apr' "
                        + " when SUBSTRING(Yearmonth,5,6)= '05' then 'May' "
                        + " when SUBSTRING(Yearmonth,5,6)= '06' then 'Jun' "
                        + " when SUBSTRING(Yearmonth,5,6)= '07' then 'Jul' "
                        + " when SUBSTRING(Yearmonth,5,6)= '08' then 'Aug' "
                        + " when SUBSTRING(Yearmonth,5,6)= '09' then 'Sep' "
                        + " when SUBSTRING(Yearmonth,5,6)= '10' then 'Oct' "
                        + " when SUBSTRING(Yearmonth,5,6)= '11' then 'Nov' "
                        + " when SUBSTRING(Yearmonth,5,6)= '12' then 'Dec' "
                        + " else 'No period' end as period ";

            }

        }

        //_________________________________________________________________END OF FILTERING SECTION_______________________________________________________________            
        //________________________________________________________________________________________________________________________________________________________            
        //an array to store haeder information.
        //the header information should appear only if certain parameters are met
        //The parameters listed in here can be removed if the report type doesnt require some parameters
        ArrayList Headerorgunits = new ArrayList();
        Headerorgunits.add(period);
        Headerorgunits.add("County");
        Headerorgunits.add("Sub-County");
        Headerorgunits.add("Facility");
        Headerorgunits.add("MFL Code");
        //An arralist to store a list of columns that will be selected from the database
        ArrayList dbcolumns = new ArrayList();

        ArrayList labels = new ArrayList();

        ArrayList tablename = new ArrayList();

        ArrayList iscumulative = new ArrayList();

        ArrayList ispercent = new ArrayList();

        // ArrayList isactive=new ArrayList();
        //An arralist to store a list of worksheets that will be selected from the sections and the respective service area to determine the facilities whose data will appear in that sheet
        ArrayList worksheets = new ArrayList();
        //An arralist to store distinct worksheets. This will be derived from the the sections column
        ArrayList distinctsheets = new ArrayList();
        ArrayList distinctservicearea = new ArrayList();

        //create an array to store the number of row for each excel worksheet. 
        //This will help in retrieving the number of rows for each month since we are wring data for different months with increasing rows.
        //the size of that array will be determined by the number of excel worksheets
        String selectdistinctworksheet = "select section,servicearea from pivottable where form='"
                + form.replace("_", "") + "' and active='1' " + indicatorswhere
                + " group by section order by order_per_form";

        conn.rs = conn.st.executeQuery(selectdistinctworksheet);

        while (conn.rs.next()) {
            //add the name of distinct sections
            distinctsheets.add(conn.rs.getString(1).replace("/", "_"));

            String servicearea = "  2=2 ";
            if (conn.rs.getString(2) != null) {
                servicearea = "  " + conn.rs.getString(2) + "=1";
            }
            distinctservicearea.add(servicearea);

        }

        int rowstartpersheet[] = new int[distinctsheets.size()];

        //initialize the row start position for each workshett with 2
        for (int x = 0; x < rowstartpersheet.length; x++) {

            rowstartpersheet[x] = 2;

        }

        String getattribs = "select indicator,label,section,cumulative,percentage,active ,shortlabel from pivottable where form='"
                + form.replace("_", "") + "' " + indicatorswhere + " order by order_per_form, section";
        conn.rs = conn.st.executeQuery(getattribs);

        while (conn.rs.next()) {

            //add active indicators only
            if (conn.rs.getString("active").equals("1")) {
                //System.out.println(conn.rs.getString("indicator")+"");
                //add indicator
                dbcolumns.add(conn.rs.getString("indicator"));
                //add label
                if (form.equalsIgnoreCase("MOH731")) {

                    labels.add(conn.rs.getString("shortlabel") + " \n" + conn.rs.getString("label"));

                } else {
                    labels.add(conn.rs.getString("label"));
                }
                //add worksheets
                worksheets.add(conn.rs.getString("section").replace("/", "_"));

                String perc = "0";
                String cum = "0";

                if (conn.rs.getString("cumulative") != null) {
                    iscumulative.add(conn.rs.getString("cumulative"));
                } else {
                    iscumulative.add(cum);
                }

                if (conn.rs.getString("percentage") != null) {
                    ispercent.add(conn.rs.getString("percentage"));
                } else {
                    ispercent.add(perc);
                }

            } //end of active 

        } //end of pivot table active
        //labels.add("ART High Volume");
        //labels.add("HTC High Volume");
        //labels.add("PMTCT High Volume");

        //System.out.println(perfacilselect);
        //______________________________________________________________________________________
        //                       CREATE THE WORKSHEETS          
        //______________________________________________________________________________________  
        XSSFWorkbook wb = new XSSFWorkbook();

        XSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        XSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        XSSFCellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        XSSFCellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        XSSFCellStyle stylesum = wb.createCellStyle();
        stylesum.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylesum.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylesum.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylesum.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        XSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        stylesum.setFont(fontx);
        stylesum.setWrapText(true);
        int cellrange[] = new int[4];

        for (int b = 0; b < distinctsheets.size(); b++) {

            XSSFSheet shet = wb.createSheet(distinctsheets.get(b).toString().toUpperCase());

            //Made my life veery simple...
            shet.setDisplayGridlines(false);
            shet.createFreezePane(5, 2);
            int firstcell = 1;

            //create headers for that worksheet
            XSSFRow rw = shet.createRow(1);
            int headercellpos = 0;
            //create the orgunit header eg MONTH | COUNTY | SUBCOUNTY  | FACILITY

            for (int e = 0; e < Headerorgunits.size(); e++) {
                XSSFCell cell0 = rw.createCell(headercellpos);
                cell0.setCellValue(Headerorgunits.get(e).toString());
                cell0.setCellStyle(stylex);

                headercellpos++;
                //shet.setColumnWidth(e, 6000);  

            }

            //create the indicators header eg HV0101 | HIV 09676  | TOTAL    
            for (int c = 0; c < dbcolumns.size(); c++) {
                //compare if the indicator belongs to the specified section and hence worksheet 
                //recall, each indicator has got an associated section / worksheet
                //An indicator should be put as an header in the respective worksheet
                if (worksheets.get(c).equals(distinctsheets.get(b))) {

                    shet.setColumnWidth(headercellpos, 6000);
                    XSSFCell cell0 = rw.createCell(headercellpos);
                    cell0.setCellValue(labels.get(c).toString());
                    cell0.setCellStyle(stylex);
                    headercellpos++;
                } //end of comparing if

            } //end of for loop

            //create is validated header
            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell0 = rw.createCell(headercellpos);
            cell0.setCellValue("ART High Volume");
            cell0.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell1 = rw.createCell(headercellpos);
            cell1.setCellValue("HTC High Volume");
            cell1.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell2 = rw.createCell(headercellpos);
            cell2.setCellValue("PMTCT High Volume");
            cell2.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell2a = rw.createCell(headercellpos);
            cell2a.setCellValue("GSN");
            cell2a.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell3 = rw.createCell(headercellpos);
            cell3.setCellValue("Form Validated ?");
            cell3.setCellStyle(stylex);
            headercellpos++;

        }

        //______________________________________________________________________________________
        //______________________________________________________________________________________
        //--------------------------------------------------------------------------------------------
        //             MONTH LOOPS
        //-------------------------------------------------------------------------------------------- 
        int cumulativestatingpoint = 3;
        boolean cumstartpointnoted = false;
        int colposcopy = 0;
        //for (int w = 0; w < months.length; w++) {

        String perfacilselect = "select " + myperiodcase
                + " , CONCAT(UPPER(SUBSTRING(County,1,1)),LOWER(SUBSTRING(County,2))) as County , DistrictNom as District , SubPartnerNom as facility ,CentreSanteId as mflcode ,  district.CountyID as countyid , ";

        //have a stringto get all distinct periods before execution of the main query. This will help in knowing the last
        String getdistinctperiod = "select " + myperiodcase;
        //--------------------------------------------------------------------------------------------
        //             PREPARE SELECT
        //--------------------------------------------------------------------------------------------
        //prepare selects
        for (int a = 0; a < dbcolumns.size(); a++) {

            //if the indicator is a percent, get an avaerage
            if (ispercent.get(a).equals("1")) {
                perfacilselect += "  AVG(" + dbcolumns.get(a) + ") as " + dbcolumns.get(a);

            } else if (iscumulative.get(a).equals("1")) {
                perfacilselect += "  SUBSTRING_INDEX(GROUP_CONCAT(CAST(IFNULL(" + dbcolumns.get(a)
                        + ",0) AS CHAR) ORDER BY yearmonth DESC),',',1) as " + dbcolumns.get(a);
                //SUBSTRING_INDEX(GROUP_CONCAT(CAST(IFNULL(HV0303,0) AS CHAR) ORDER BY yearmonth DESC),',',1)

            } else {
                perfacilselect += "  SUM(" + dbcolumns.get(a) + ") as " + dbcolumns.get(a);

            }

            //if the item is not the last, append a comma
            //if(a<dbcolumns.size()-1){
            perfacilselect += " ,";

            // } 
        }

        //---------------------------------add highvolume------------------------------------------------
        perfacilselect += " IFNULL(ART_highvolume,0) as ART_highvolume,  IFNULL(HTC_highvolume,0) as HTC_highvolume,  IFNULL(PMTCT_highvolume,0) as PMTCT_highvolume,  IFNULL(GSN,0) as GSN,";

        //-------------------------------------------------------------------------------------------------
        //     FROM  
        //------------------------------------------------------------------------------------  
        perfacilselect += "  isValidated as Form_Validated from " + form
                + "  join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                + form + ".SubPartnerID = subpartnera.SubPartnerID ";

        getdistinctperiod += " from " + form
                + "  join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                + form + ".SubPartnerID = subpartnera.SubPartnerID ";

        //------------------------------------------------------------------------------------------
        // WHERE 
        //------------------------------------------------------------------------------------------ 
        perfacilselect += joinedwhwere; //contains any filterings

        getdistinctperiod += joinedwhwere; //contains any filterings

        //-----------------------------------------------------------------------------------------
        //GROUP BY 
        //----------------------------------------------------------------------------------------

        perfacilselect += " group by subpartnera.SubPartnerID " + periodicgroupby + " order by yearmonth ";

        getdistinctperiod += " group by period order by yearmonth ";

        String lastperiod = "";
        ArrayList alldistinctperiods = new ArrayList();
        //System.out.println(""+getdistinctperiod);                

        conn.rs = conn.st.executeQuery(getdistinctperiod);

        while (conn.rs.next() == true) {
            lastperiod = conn.rs.getString(1); //here am asumming the last period will appear last and so will be mantained in the                
            alldistinctperiods.add(lastperiod);
        }

        String sectioncopy = "";

        int sheetpos = 0;
        int rowpos = 2;

        //-----------------INSIDE THE DATA FORM---------------------------------
        //if the section (eg HTC, PMTCT) changes, change the current workshhet index too
        //also, reset the row position counter to begin from 2 again. 
        XSSFSheet shet = null;

        //      if(--!sectioncopy.equals(shet)){}
        //create the org unit data values e.g BARINGO | BARINGO CENTRAL |KABARNET DISTRICT HOSPITAL | MFL CODE
        for (int g = 0; g < distinctsheets.size(); g++) {

            rowpos = rowstartpersheet[g];

            shet = wb.getSheetAt(g);
            int colpos = 0;

            String finalquery = perfacilselect.replace("1=1", distinctservicearea.get(g).toString());
            //System.out.println("" + finalquery);
            conn.rs = conn.st.executeQuery(finalquery);
            while (conn.rs.next()) {

                if (lastperiod.equalsIgnoreCase(conn.rs.getString("period")) && cumstartpointnoted == false) {
                    //save the current row position.
                    //get it from the current rowstartpersheet[g]

                    cumulativestatingpoint = rowstartpersheet[0];

                    cumstartpointnoted = true;
                    //this ensures that we are fetching dataonce.
                    // System.out.println("LAST STARTING POINT__"+cumulativestatingpoint);

                }

                //the fourth cell should     
                XSSFRow rw = shet.createRow(rowpos);
                for (int e = 0; e < Headerorgunits.size(); e++) {
                    XSSFCell cell0 = rw.createCell(colpos);
                    //for mfl code, last header, output integers
                    if (e > 3) {
                        cell0.setCellValue(conn.rs.getInt(e + 1));
                    } else {
                        cell0.setCellValue(conn.rs.getString(e + 1));
                    }

                    cell0.setCellStyle(style2);
                    colpos++;

                }

                //_________________________________________________________________
                //VALUES
                //_________________________________________________________________
                //create the indicators values eg 90 | 45  | 356    
                for (int c = 0; c < dbcolumns.size(); c++) {
                    //get the section of the current dbcolumn

                    //compare if the indicator belongs to the specified section and hence worksheet 
                    //recall, each indicator has got an associated section / worksheet
                    //An indicator should be put as an header in the respective worksheet
                    if (worksheets.get(c).equals(distinctsheets.get(g))) {

                        XSSFCell cell0 = rw.createCell(colpos);
                        cell0.setCellValue(conn.rs.getInt(dbcolumns.get(c).toString()));
                        cell0.setCellStyle(stborder);
                        colpos++;
                    } //end of comparing if

                } //end of for loop

                //ART_highvolume
                XSSFCell cell0 = rw.createCell(colpos);
                cell0.setCellValue(conn.rs.getInt("ART_highvolume"));
                cell0.setCellStyle(stborder);
                colpos++;

                //HTC_highvolume
                XSSFCell cell1 = rw.createCell(colpos);
                cell1.setCellValue(conn.rs.getInt("HTC_highvolume"));
                cell1.setCellStyle(stborder);
                colpos++;

                //PMTCT_highvolume
                XSSFCell cell2 = rw.createCell(colpos);
                cell2.setCellValue(conn.rs.getInt("PMTCT_highvolume"));
                cell2.setCellStyle(stborder);
                colpos++;

                //PMTCT_highvolume
                XSSFCell cell2a = rw.createCell(colpos);
                cell2a.setCellValue(conn.rs.getInt("GSN"));
                cell2a.setCellStyle(stborder);
                colpos++;

                String isvalidated = "Yes";

                if (conn.rs.getString("Form_Validated").equals("0")) {
                    isvalidated = "No";
                }
                XSSFCell cell3 = rw.createCell(colpos);
                cell3.setCellValue(isvalidated);
                cell3.setCellStyle(stborder);

                colpos++;

                rowpos++;
                if (colpos > 1) {
                    colposcopy = colpos - 1;

                }
                colpos = 0;
            } // end of while loop getting data from the db

            //____________________________________________________________________________________
            //COLUMN AUTOSIZE COLUMN WIDTH , AUTOFILTER & AUTOSUM
            //____________________________________________________________________________________
            //At this point we are sure this is the last row and we have exhausted fetching data for all periods
            //System.out.println(" Column position Before "+colposcopy);
            //                  if (lastperiod.equalsIgnoreCase(conn.rs.getString("period"))) {

            //System.out.println(" Column after "+colposcopy);
            shet.setAutoFilter(new CellRangeAddress(1, rowpos - 1, 0, colposcopy));

            //System.out.println("1,"+rowpos+",0,"+colposcopy);
            for (int e = 0; e < Headerorgunits.size(); e++) {
                shet.autoSizeColumn(e);
            }

            //autosum

            XSSFRow initialrow = shet.getRow(2);
            XSSFRow prevrow = shet.getRow(rowpos - 1);
            XSSFRow cumrow = shet.getRow(cumulativestatingpoint);//not used for now but let it stay here may be of use in future  

            XSSFRow rwsum = shet.createRow(rowpos);
            int colpossum = 0;
            int firstcols = 5;
            int periodcolumn = 0;

            for (int f = 0; f < firstcols; f++) {

                if (f == 0) {

                    XSSFCell cellsum = rwsum.createCell(0);
                    cellsum.setCellValue("Total");
                    cellsum.setCellStyle(stylesum);
                } else if (f > 0 && f < firstcols) {
                    XSSFCell cellsum = rwsum.createCell(f);
                    cellsum.setCellValue(" ");
                    cellsum.setCellStyle(stylesum);
                }
            }

            for (int c = 0; c < dbcolumns.size(); c++) {

                if (worksheets.get(c).equals(distinctsheets.get(g))) {

                    XSSFCell cellsum = rwsum.createCell(colpossum + firstcols);
                    XSSFCell initialcell = initialrow.getCell(colpossum + firstcols);

                    String cellformula = "";
                    XSSFCell prevcell = prevrow.getCell(colpossum + firstcols);//the last cell of the current column. rem whe are looping through all the columns
                    //periodcolumncell
                    XSSFCell initialperiodcell = initialrow.getCell(periodcolumn);// the first cell of the period(month, year) column
                    XSSFCell currentperiodcell = prevrow.getCell(periodcolumn);//the last cell of the period column

                    cellsum.setCellType(cellsum.CELL_TYPE_FORMULA);
                    String startcellreference = initialcell.getReference();
                    String lastavailableperiod = currentperiodcell.getStringCellValue();
                    if (iscumulative.get(c).equals("1")) {
                        //initialcell=cumrow.getCell(colpossum+firstcols);
                        //Create a formula that sums all the data for the last column to appear in the row. This should pick the first column which is the period column.
                        cellformula = "SUMPRODUCT(--(SUBTOTAL(3,OFFSET(INDEX("
                                + initialperiodcell.getReference() + ":" + currentperiodcell.getReference()
                                + ",1,1),ROW(" + initialperiodcell.getReference() + ":"
                                + currentperiodcell.getReference() + ")-ROW(INDEX("
                                + initialperiodcell.getReference() + ":" + currentperiodcell.getReference()
                                + ",1,1)),0))=1),--(" + initialperiodcell.getReference() + ":"
                                + currentperiodcell.getReference() + "=\"" + lastavailableperiod + "\"),"
                                + startcellreference + ":" + prevcell.getReference() + ")";

                    } else if (ispercent.get(c).equals("1")) {
                        //initialcell=cumrow.getCell(colpossum+firstcols);
                        //Create a formula that sums all the data for the last column to appear in the row. This should pick the first column which is the period column.
                        cellformula = "ROUNDUP(SUBTOTAL(9," + startcellreference + ":" + prevcell.getReference()
                                + "),1)"; // round of maximum values

                    } else {

                        cellformula = "SUBTOTAL(9," + startcellreference + ":" + prevcell.getReference() + ")";
                    }

                    //for cumulative indicators, we need to do column total for the last selected month
                    //we therefore need to always track where the previous month started at.
                    cellsum.setCellFormula(cellformula);
                    cellsum.setCellStyle(stylesum);

                    colpossum++;
                }
            }
            //merge last cell
            shet.addMergedRegion(new CellRangeAddress(rowpos, rowpos, 0, 4));
            // } end of checking  if this is the last month //disbled for now

            //
            rowstartpersheet[g] = rowpos;

        } // end of distinct sheets report

        // }//end of monthly loop

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        System.out.println("" + form.toUpperCase().trim() + "_RPT_FOR_" + year.trim() + "(" + periodlabel
                + ")_GEN_" + createdOn.trim() + ".xlsx");

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition",
                "attachment; filename=" + form.toUpperCase().trim() + "_REPORT_FOR_" + year.trim() + "("
                        + periodlabel.replace(" ", "") + ")_CREATED_" + createdOn.trim() + ".xlsx");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(allStaticReportsdynamic.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:reports.allStaticReportsMonthly.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String monthrange = "";
    String periodlabel = "";
    String period = "Month"; //The default one
    try {//w w w . j  av  a 2s  .  c  om
        response.setContentType("text/html;charset=UTF-8");

        //a page to get Report of all the servlets
        String months[] = null;

        String year = "2016";
        String month = "7";
        String county = "";
        String form = "moh731";

        if (request.getParameter("year") != null) {
            year = request.getParameter("year");
        }

        if (request.getParameter("county") != null) {
            county = request.getParameter("county");
        }

        if (request.getParameter("month") != null) {
            months = request.getParameterValues("month");
        }

        if (request.getParameter("form") != null) {
            form = request.getParameter("form");
        }
        String pivotform = form;
        if (form.equalsIgnoreCase("MOH 731")) {
            form = "MOH731";
        }
        if (form.equalsIgnoreCase("MOH 711A")) {
            form = "MOH711";
        }
        if (form.equalsIgnoreCase("MOH 711 (New)")) {
            form = "moh711_new";
        }
        String facilitywhere = "";
        String yearwhere = "";
        String monthwhere = "";
        String countywhere = "";
        String districtwhere = "";
        String reporttype = "";

        if (!year.equals("")) {

            yearwhere = " and Annee = '" + year + "'";

        }
        if (!county.equals("")) {

            countywhere = " and countyid = '" + county + "'";

        }

        dbConn conn = new dbConn();

        //an array to store haeder information.
        //the header information should appear only if certain parameters are met
        //The parameters listed in here can be removed if the report type doesnt require some parameters
        ArrayList Headerorgunits = new ArrayList();
        Headerorgunits.add(period);
        Headerorgunits.add("County");
        Headerorgunits.add("Sub-County");
        Headerorgunits.add("Facility");
        Headerorgunits.add("MFL Code");

        //An arralist to store a list of columns that will be selected from the database
        ArrayList dbcolumns = new ArrayList();

        ArrayList labels = new ArrayList();

        ArrayList tablename = new ArrayList();

        ArrayList iscumulative = new ArrayList();

        ArrayList ispercent = new ArrayList();

        // ArrayList isactive=new ArrayList();
        //An arralist to store a list of worksheets that will be selected from the sections and the respective service area to determine the facilities whose data will appear in that sheet
        ArrayList worksheets = new ArrayList();
        //An arralist to store distinct worksheets. This will be derived from the the sections column
        ArrayList distinctsheets = new ArrayList();
        ArrayList distinctservicearea = new ArrayList();

        //create an array to store the number of row for each excel worksheet. 
        //This will help in retrieving the number of rows for each month since we are wring data for different months with increasing rows.
        //the size of that array will be determined by the number of excel worksheets
        String selectdistinctworksheet = "select section,servicearea from pivottable where form='"
                + form.replace("_", "") + "' and active='1' group by section order by order_per_form";

        conn.rs = conn.st.executeQuery(selectdistinctworksheet);

        while (conn.rs.next()) {
            //add the name of distinct sections
            distinctsheets.add(conn.rs.getString(1).replace("/", "_"));

            String servicearea = "  2=2 ";
            if (conn.rs.getString(2) != null) {
                servicearea = "  " + conn.rs.getString(2) + "=1";
            }
            distinctservicearea.add(servicearea);

        }

        int rowstartpersheet[] = new int[distinctsheets.size()];

        //initialize the row start with 2
        for (int x = 0; x < rowstartpersheet.length; x++) {

            rowstartpersheet[x] = 2;

        }

        String getattribs = "select indicator,label,section,cumulative,percentage,active ,shortlabel from pivottable where form='"
                + form.replace("_", "") + "' order by order_per_form, section";
        conn.rs = conn.st.executeQuery(getattribs);

        while (conn.rs.next()) {

            //add active indicators only
            if (conn.rs.getString("active").equals("1")) {
                //System.out.println(conn.rs.getString("indicator")+"");
                //add indicator
                dbcolumns.add(conn.rs.getString("indicator"));
                //add label
                if (form.equalsIgnoreCase("MOH731")) {
                    labels.add(conn.rs.getString("shortlabel") + " \n" + conn.rs.getString("label"));

                } else {
                    labels.add(conn.rs.getString("label"));
                }
                //add worksheets
                worksheets.add(conn.rs.getString("section").replace("/", "_"));

                String perc = "0";
                String cum = "0";

                if (conn.rs.getString("cumulative") != null) {
                    iscumulative.add(conn.rs.getString("cumulative"));
                } else {
                    iscumulative.add(cum);
                }

                if (conn.rs.getString("percentage") != null) {
                    ispercent.add(conn.rs.getString("percentage"));
                } else {
                    ispercent.add(perc);
                }

            } //end of active 

        } //end of pivot table active
          //labels.add("ART High Volume");
          //labels.add("HTC High Volume");
          //labels.add("PMTCT High Volume");

        //System.out.println(perfacilselect);
        //______________________________________________________________________________________
        //                       CREATE THE WORKSHEETS          
        //______________________________________________________________________________________  
        XSSFWorkbook wb = new XSSFWorkbook();

        XSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        XSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        XSSFCellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        XSSFCellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        XSSFCellStyle stylesum = wb.createCellStyle();
        stylesum.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylesum.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylesum.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylesum.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        XSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        stylesum.setFont(fontx);
        stylesum.setWrapText(true);
        int cellrange[] = new int[4];

        for (int b = 0; b < distinctsheets.size(); b++) {
            XSSFSheet shet = wb.createSheet(distinctsheets.get(b).toString().toUpperCase());

            //Made my life veery simple...
            shet.setDisplayGridlines(false);
            shet.createFreezePane(5, 2);
            int firstcell = 1;

            //shet.setAutoFilter(CellRangeAddress.valueOf("A2:N1"));
            //create headers for that worksheet
            XSSFRow rw = shet.createRow(1);
            int headercellpos = 0;
            //create the orgunit header eg COUNTY | SUBCOUNTY  | FACILITY

            for (int e = 0; e < Headerorgunits.size(); e++) {
                XSSFCell cell0 = rw.createCell(headercellpos);
                cell0.setCellValue(Headerorgunits.get(e).toString());
                cell0.setCellStyle(stylex);

                headercellpos++;
                //shet.setColumnWidth(e, 6000);  

            }

            //create the indicators header eg HV0101 | HIV 09676  | TOTAL    
            for (int c = 0; c < dbcolumns.size(); c++) {
                //compare if the indicator belongs to the specified section and hence worksheet 
                //recall, each indicator has got an associated section / worksheet
                //An indicator should be put as an header in the respective worksheet
                if (worksheets.get(c).equals(distinctsheets.get(b))) {

                    shet.setColumnWidth(headercellpos, 6000);
                    XSSFCell cell0 = rw.createCell(headercellpos);
                    cell0.setCellValue(labels.get(c).toString());
                    cell0.setCellStyle(stylex);
                    headercellpos++;
                } //end of comparing if

            } //end of for loop

            //create is validated header

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell0 = rw.createCell(headercellpos);
            cell0.setCellValue("ART High Volume");
            cell0.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell1 = rw.createCell(headercellpos);
            cell1.setCellValue("HTC High Volume");
            cell1.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell2 = rw.createCell(headercellpos);
            cell2.setCellValue("PMTCT High Volume");
            cell2.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell3 = rw.createCell(headercellpos);
            cell3.setCellValue("Form Validated ?");
            cell3.setCellStyle(stylex);
            headercellpos++;

        }

        //______________________________________________________________________________________
        //______________________________________________________________________________________
        //--------------------------------------------------------------------------------------------
        //             MONTH LOOPS
        //-------------------------------------------------------------------------------------------- 
        int cumulativestatingpoint = 3;
        boolean cumstartpointnoted = false;
        int colposcopy = 0;
        for (int w = 0; w < months.length; w++) {

            month = months[w];

            if (!month.equals("")) {

                monthwhere = " and Mois = '" + month + "'";

            }

            String getMonth = "SELECT name FROM month WHERE id='" + month + "'";
            conn.rs = conn.st.executeQuery(getMonth);

            if (conn.rs.next() == true) {
                monthrange = conn.rs.getString(1);
                if (periodlabel.equals("")) {
                    periodlabel = monthrange.substring(0, 3);
                } else {
                    periodlabel += "_" + monthrange.substring(0, 3);
                }
            }

            String perfacilselect = "select '" + monthrange
                    + "', CONCAT(UPPER(SUBSTRING(County,1,1)),LOWER(SUBSTRING(County,2))) as County , DistrictNom as District , SubPartnerNom as facility ,CentreSanteId as mflcode ,  district.CountyID as countyid , ";

            //--------------------------------------------------------------------------------------------
            //             PREPARE SELECT
            //--------------------------------------------------------------------------------------------
            //prepare selects
            for (int a = 0; a < dbcolumns.size(); a++) {

                //if the indicator is a percent, get an avaerage
                if (ispercent.get(a).equals("1")) {
                    perfacilselect += "  AVG(" + dbcolumns.get(a) + ") as " + dbcolumns.get(a);

                } else if (iscumulative.get(a).equals("1")) {
                    perfacilselect += "  " + dbcolumns.get(a) + " as " + dbcolumns.get(a);

                } else {
                    perfacilselect += "  SUM(" + dbcolumns.get(a) + ") as " + dbcolumns.get(a);

                }

                //if the item is not the last, append a comma
                //if(a<dbcolumns.size()-1){
                perfacilselect += " ,";

                // } 
            }

            //---------------------------------add highvolume------------------------------------------------

            perfacilselect += " IFNULL(ART_highvolume,0) as ART_highvolume,  IFNULL(HTC_highvolume,0) as HTC_highvolume,  IFNULL(PMTCT_highvolume,0) as PMTCT_highvolume,";

            //-------------------------------------------------------------------------------------------------
            //     FROM  
            //------------------------------------------------------------------------------------  
            perfacilselect += "  isValidated as Form_Validated from " + form
                    + "  join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                    + form + ".SubPartnerID = subpartnera.SubPartnerID ";

            //------------------------------------------------------------------------------------------
            // WHERE 
            //------------------------------------------------------------------------------------------ 
            perfacilselect += " where  1=1 " + monthwhere + yearwhere;

            //-----------------------------------------------------------------------------------------
            //GROUP BY 
            //----------------------------------------------------------------------------------------
            perfacilselect += " group by subpartnera.SubPartnerID";

            String sectioncopy = "";

            int sheetpos = 0;
            int rowpos = 2;

            //-----------------INSIDE THE DATA FORM---------------------------------
            //if the section changes, change the position of the worksheet too
            //also, reset the position counter to begin from 2 again. 
            XSSFSheet shet = null;

            //      if(--!sectioncopy.equals(shet)){}
            //create the org unit data values e.g BARINGO | BARINGO CENTRAL |KABARNET DISTRICT HOSPITAL | MFL CODE
            for (int g = 0; g < distinctsheets.size(); g++) {

                if (w == months.length - 1 && cumstartpointnoted == false) {

                    //save the current row position.
                    //get it from the current rowstartpersheet[g]  
                    cumulativestatingpoint = rowstartpersheet[0];

                    cumstartpointnoted = true; //this ensures that we are fetching dataonce.
                    // System.out.println("LAST STARTING POINT__"+cumulativestatingpoint);

                }

                rowpos = rowstartpersheet[g];

                shet = wb.getSheetAt(g);
                int colpos = 0;

                String finalquery = perfacilselect.replace("1=1", distinctservicearea.get(g).toString());
                System.out.println("" + finalquery);
                conn.rs = conn.st.executeQuery(finalquery);
                while (conn.rs.next()) {

                    //the fourth cell should     
                    XSSFRow rw = shet.createRow(rowpos);
                    for (int e = 0; e < Headerorgunits.size(); e++) {
                        XSSFCell cell0 = rw.createCell(colpos);
                        //for mfl code, last header, output integers
                        if (e > 3) {
                            cell0.setCellValue(conn.rs.getInt(e + 1));
                        } else {
                            cell0.setCellValue(conn.rs.getString(e + 1));
                        }

                        cell0.setCellStyle(style2);
                        colpos++;

                    }

                    //_________________________________________________________________
                    //VALUES
                    //_________________________________________________________________
                    //create the indicators values eg 90 | 45  | 356    
                    for (int c = 0; c < dbcolumns.size(); c++) {
                        //get the section of the current dbcolumn

                        //compare if the indicator belongs to the specified section and hence worksheet 
                        //recall, each indicator has got an associated section / worksheet
                        //An indicator should be put as an header in the respective worksheet
                        if (worksheets.get(c).equals(distinctsheets.get(g))) {

                            XSSFCell cell0 = rw.createCell(colpos);
                            cell0.setCellValue(conn.rs.getInt(dbcolumns.get(c).toString()));
                            cell0.setCellStyle(stborder);
                            colpos++;
                        } //end of comparing if

                    } //end of for loop

                    //ART_highvolume
                    XSSFCell cell0 = rw.createCell(colpos);
                    cell0.setCellValue(conn.rs.getInt("ART_highvolume"));
                    cell0.setCellStyle(stborder);
                    colpos++;

                    //HTC_highvolume
                    XSSFCell cell1 = rw.createCell(colpos);
                    cell1.setCellValue(conn.rs.getInt("HTC_highvolume"));
                    cell1.setCellStyle(stborder);
                    colpos++;

                    //PMTCT_highvolume
                    XSSFCell cell2 = rw.createCell(colpos);
                    cell2.setCellValue(conn.rs.getInt("PMTCT_highvolume"));
                    cell2.setCellStyle(stborder);
                    colpos++;

                    String isvalidated = "Yes";

                    if (conn.rs.getString("Form_Validated").equals("0")) {
                        isvalidated = "No";
                    }
                    XSSFCell cell3 = rw.createCell(colpos);
                    cell3.setCellValue(isvalidated);
                    cell3.setCellStyle(stborder);

                    colpos++;

                    rowpos++;
                    if (colpos > 1) {
                        colposcopy = colpos - 1;

                    }
                    colpos = 0;
                } // end of while loop getting data from the db

                //____________________________________________________________________________________
                //COLUMN AUTOSIZE COLUMN WIDTH , AUTOFILTER & AUTOSUM
                //____________________________________________________________________________________

                //At this point we are sure this is the last row and we have exhausted fetching data for all months

                //System.out.println(" Column position Before "+colposcopy);

                if (w == months.length - 1) {

                    //System.out.println(" Column after "+colposcopy);

                    shet.setAutoFilter(new CellRangeAddress(1, rowpos - 1, 0, colposcopy));

                    //System.out.println("1,"+rowpos+",0,"+colposcopy);

                    for (int e = 0; e < Headerorgunits.size(); e++) {
                        shet.autoSizeColumn(e);
                    }

                    //autosum
                    XSSFRow rwsum = shet.createRow(rowpos);
                    XSSFRow initialrow = shet.getRow(2);
                    XSSFRow prevrow = shet.getRow(rowpos - 1);
                    XSSFRow cumrow = shet.getRow(cumulativestatingpoint);//not used for now but let it stay here may be of use in future  

                    int colpossum = 0;
                    int firstcols = 5;
                    int periodcolumn = 0;

                    for (int f = 0; f < firstcols; f++) {

                        if (f == 0) {

                            XSSFCell cellsum = rwsum.createCell(0);
                            cellsum.setCellValue("Total");
                            cellsum.setCellStyle(stylesum);
                        } else if (f > 0 && f < firstcols) {
                            XSSFCell cellsum = rwsum.createCell(f);
                            cellsum.setCellValue(" ");
                            cellsum.setCellStyle(stylesum);
                        }
                    }

                    for (int c = 0; c < dbcolumns.size(); c++) {

                        if (worksheets.get(c).equals(distinctsheets.get(g))) {

                            XSSFCell cellsum = rwsum.createCell(colpossum + firstcols);
                            XSSFCell initialcell = initialrow.getCell(colpossum + firstcols);

                            String cellformula = "";
                            XSSFCell prevcell = prevrow.getCell(colpossum + firstcols);//the last cell of the current column. rem whe are looping through all the columns
                            //periodcolumncell
                            XSSFCell initialperiodcell = initialrow.getCell(periodcolumn);// the first cell of the period(month, year) column
                            XSSFCell currentperiodcell = prevrow.getCell(periodcolumn);//the last cell of the period column

                            cellsum.setCellType(cellsum.CELL_TYPE_FORMULA);
                            String startcellreference = initialcell.getReference();
                            String lastavailableperiod = currentperiodcell.getStringCellValue();
                            if (iscumulative.get(c).equals("1")) {
                                //initialcell=cumrow.getCell(colpossum+firstcols);
                                //Create a formula that sums all the data for the last column to appear in the row. This should pick the first column which is the period column.
                                cellformula = "SUMPRODUCT(--(SUBTOTAL(3,OFFSET(INDEX("
                                        + initialperiodcell.getReference() + ":"
                                        + currentperiodcell.getReference() + ",1,1),ROW("
                                        + initialperiodcell.getReference() + ":"
                                        + currentperiodcell.getReference() + ")-ROW(INDEX("
                                        + initialperiodcell.getReference() + ":"
                                        + currentperiodcell.getReference() + ",1,1)),0))=1),--("
                                        + initialperiodcell.getReference() + ":"
                                        + currentperiodcell.getReference() + "=\"" + lastavailableperiod
                                        + "\")," + startcellreference + ":" + prevcell.getReference() + ")";

                            } else if (ispercent.get(c).equals("1")) {
                                //initialcell=cumrow.getCell(colpossum+firstcols);
                                //Create a formula that sums all the data for the last column to appear in the row. This should pick the first column which is the period column.
                                cellformula = "ROUNDUP(SUBTOTAL(9," + startcellreference + ":"
                                        + prevcell.getReference() + "),1)"; // round of maximum values

                            } else {

                                cellformula = "SUBTOTAL(9," + startcellreference + ":" + prevcell.getReference()
                                        + ")";
                            }

                            //for cumulative indicators, we need to do column total for the last selected month
                            //we therefore need to always track where the previous month started at.

                            cellsum.setCellFormula(cellformula);
                            cellsum.setCellStyle(stylesum);

                            colpossum++;
                        }
                    }
                    //merge last cell
                    shet.addMergedRegion(new CellRangeAddress(rowpos, rowpos, 0, 4));
                }

                //

                rowstartpersheet[g] = rowpos;

            } // end of distinct sheets report

        } //end of monthly loop

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        System.out.println("" + form.toUpperCase().trim() + "_RPT_FOR_" + year.trim() + "(" + month.trim()
                + ")_GEN_" + createdOn.trim() + ".xlsx");

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition", "attachment; filename=" + form.toUpperCase().trim()
                + "_REPORT_FOR_" + year.trim() + "(" + periodlabel + ")_CREATED_" + createdOn.trim() + ".xlsx");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(allStaticReportsMonthly.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:reports.genderexcel.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/* w  ww  .  jav  a 2 s.c  o  m*/
        response.setContentType("text/html;charset=UTF-8");
        session = request.getSession();

        dbConn conn = new dbConn();
        //get the existing data for the month, year and facility that is already on session

        String month = "";
        String year = "";
        String facil = "";

        String form = "gender";

        //=====================================================================================================

        year = "2015";
        month = "5";
        String county = "";

        String header = "";

        String reportType = "";
        if (request.getParameter("reportType") != null) {
            reportType = request.getParameter("reportType");
        }
        String reportDuration = "";
        if (request.getParameter("reportDuration") != null) {
            reportDuration = request.getParameter("reportDuration");
        }
        if (request.getParameter("year") != null) {
            year = request.getParameter("year");
        }

        if (request.getParameter("facility") != null && reportType.equals("2")) {
            facil = request.getParameter("facility");

            String getfacil = "select SubPartnerNom,CentreSanteId as mflcode from subpartnera where SubPartnerID='"
                    + facil + "'";
            conn.rs = conn.st.executeQuery(getfacil);

            while (conn.rs.next()) {

                header += " FACILITY : " + conn.rs.getString(1).toUpperCase() + "     MFL CODE  :  "
                        + conn.rs.getString(2) + "  ";

            }

        }

        if (request.getParameter("county") != null && reportType.equals("2")) {
            county = request.getParameter("county");

            String getcounty = "select County from county where CountyID='" + county + "'";
            conn.rs = conn.st.executeQuery(getcounty);

            while (conn.rs.next()) {

                header += " COUNTY : " + conn.rs.getString(1).toUpperCase() + " ";

            }

        }

        if (request.getParameter("month") != null && reportDuration.equals("4")) {
            month = request.getParameter("month");

            String getmonth = "select name as monthname from month where id='" + month + "'";
            conn.rs = conn.st.executeQuery(getmonth);

            while (conn.rs.next()) {

                header += " MONTH : " + conn.rs.getString(1).toUpperCase() + " ";

            }

        }

        header += " YEAR : " + year + "";

        String facilitywhere = "";
        String yearwhere = "";
        String monthwhere = "";
        String countywhere = "";
        String duration = "";
        String semi_annual = "";
        String quarter = "";

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        int yearcopy = Integer.parseInt(year);

        //        reportType="2";
        //        year=2015;
        //        reportDuration="3";
        String yearmonth = "" + year;
        int prevYear = yearcopy - 1;
        int maxYearMonth = 0;
        int monthcopy = 0;
        //        GET REPORT DURATION============================================

        if (reportDuration.equals("1")) {
            yearmonth += "_AnnualReport";
            duration = " " + form + ".yearmonth BETWEEN " + prevYear + "10 AND " + year + "09";
        } else if (reportDuration.equals("2")) {
            semi_annual = request.getParameter("semi_annual");
            //        semi_annual="2";
            if (semi_annual.equals("1")) {
                yearmonth = prevYear + "_Oct_" + year + "_Mar";
                duration = " " + form + ".yearmonth BETWEEN " + prevYear + "10 AND " + year + "03";
            } else {
                yearmonth += "_Apr_Sep";
                duration = " " + form + ".yearmonth BETWEEN " + year + "04 AND " + year + "09";
            }
        }

        else if (reportDuration.equals("3")) {
            String startMonth, endMonth;
            quarter = request.getParameter("quarter");
            //       quarter="3";
            String getMonths = "SELECT months,name FROM quarter WHERE id='" + quarter + "'";
            conn.rs = conn.st.executeQuery(getMonths);
            if (conn.rs.next() == true) {

                String months[] = conn.rs.getString(1).split(",");
                startMonth = months[0];
                endMonth = months[2];
                if (quarter.equals("1")) {
                    duration = " " + form + ".yearmonth BETWEEN " + prevYear + "" + startMonth + " AND "
                            + prevYear + "" + endMonth;
                    yearmonth = prevYear + "_" + conn.rs.getString(2);
                } else {
                    yearmonth = year + "_" + conn.rs.getString(2);
                    duration = " " + form + ".yearmonth BETWEEN " + year + "" + startMonth + " AND " + year + ""
                            + endMonth;
                }
            }
        }

        else if (reportDuration.equals("4")) {
            monthcopy = Integer.parseInt(request.getParameter("month"));

            //     month=5;
            if (monthcopy >= 10) {
                yearmonth = prevYear + "_" + month;
                duration = " " + form + ".yearmonth=" + prevYear + "" + month;
            } else {
                duration = " " + form + ".yearmonth=" + year + "0" + month;
                yearmonth = year + "_(" + month + ")";
            }
        } else {
            duration = "";
        }

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        String getexistingdata = "";

        if (!county.equals("")) {

            countywhere = " and countyid = '" + county + "'";

        }

        if (!facil.equals("") && reportType.equalsIgnoreCase("2")) {

            facilitywhere = " and " + form + ".SubPartnerID = '" + facil + "'";

        }

        //String joinedwhwere=" where 1=1 "+yearwhere+" && "+duration;  

        String joinedwhwere = " where 1=1 " + facilitywhere + "  " + yearwhere + " && " + duration;

        //=====================================================================================================    

        //______________________________________________________________________________________
        //                       NOW CREATE THE WORKSHEETS          
        //______________________________________________________________________________________  

        HSSFWorkbook wb = new HSSFWorkbook();

        //______________________________________________________________________________________
        //______________________________________________________________________________________

        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        HSSFSheet shet = wb.createSheet(form);

        //create headers for that worksheet

        HSSFRow rw = shet.createRow(0);
        rw.setHeightInPoints(25);
        HSSFCell cl0 = rw.createCell(0);
        cl0.setCellValue("Prevention Sub Area 12: Gender");
        cl0.setCellStyle(stylex);

        for (int a = 1; a <= 5; a++) {
            HSSFCell clx = rw.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        HSSFRow rw1 = shet.createRow(1);
        rw1.setHeightInPoints(23);
        HSSFCell cl = rw1.createCell(0);
        cl.setCellValue(header);
        cl.setCellStyle(stylex);

        for (int a = 1; a <= 5; a++) {
            HSSFCell clx = rw1.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        HSSFRow rw2 = shet.createRow(2);
        rw2.setHeightInPoints(23);
        HSSFCell cl3 = rw2.createCell(0);
        cl3.setCellValue("");
        cl3.setCellStyle(stylex);

        HSSFCell cl31 = rw2.createCell(1);
        cl31.setCellValue("");
        cl31.setCellStyle(stylex);
        String head[] = { "AGE", "MALE", "FEMALE", "TOTAL" };
        for (int a = 0; a < head.length; a++) {
            HSSFCell clx = rw2.createCell(a + 2);
            clx.setCellValue(head[a]);
            clx.setCellStyle(stylex);
        }
        //shet.addMergedRegion(new CellRangeAddress(3,10,0,0));  
        shet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
        shet.addMergedRegion(new CellRangeAddress(1, 1, 0, 5));
        shet.addMergedRegion(new CellRangeAddress(2, 2, 1, 1));
        shet.setColumnWidth(0, 2500);
        shet.setColumnWidth(1, 25000);
        shet.setColumnWidth(2, 5000);
        shet.setColumnWidth(3, 5000);
        shet.setColumnWidth(4, 5000);
        shet.setColumnWidth(5, 5000);

        getexistingdata = "select sum(P121DM0) as P121DM0,    sum(P121DF0) as P121DF0,    sum(P121DM10) as P121DM10,    sum(P121DF10) as P121DF10,    sum(P121DM15) as P121DM15,   sum(P121DF15) as P121DF15,   sum(P121DM20) as P121DM20,    sum(P121DF20) as P121DF20,   sum(P121DM25) as  P121DM25,    sum(P121DF25) as P121DF25,    sum(P121DMT) as  P121DMT,    sum(P121DFT) as P121DFT,    sum(P121DTT) as P121DTT,    sum(P122DM0) as P122DM0,    sum(P122DF0) as P122DF0,    sum(P122DM15) as  P122DM15,     sum(P122DF15) as P122DF15,     sum(P122DM25) as P122DM25,     sum(P122DF25) as P122DF25,     sum(P122DMT) as P122DMT,     sum(P122DFT) as P122DFT,     sum(P122DTT) as P122DTT,     sum(P123DM0) as P123DM0,     sum(P123DF0) as P123DF0,     sum(P123DM15) as P123DM15,     sum(P123DF15) as P123DF15,     sum(P123DM25) as P123DM25,     sum(P123DF25) as P123DF25,     sum(P123DMT) as P123DMT,     sum(P123DFT) as P123DFT,     sum(P123DTT) as P123DTT,     sum(P124DM0) as P124DM0,     sum(P124DF0) as P124DF0,     sum(P124DM15) as P124DM15,     sum(P124DF15) as P124DF15,     sum(P124DM25) as P124DM25,     sum(P124DF25) as P124DF25,     sum(P124DMT) as P124DMT,     sum(P124DFT) as P124DFT,     sum(P124DTT) as P124DTT,     sum(GEND_GBV9M) as GEND_GBV9M,     sum(GEND_GBV9F) as GEND_GBV9F,     sum(GEND_GBV9) as GEND_GBV9,     sum(GEND_GBV14M) as GEND_GBV14M,     sum(GEND_GBV14F) as GEND_GBV14F,     sum(GEND_GBV14) as GEND_GBV14,     sum(GEND_GBV17M) as GEND_GBV17M,     sum(GEND_GBV17F) as GEND_GBV17F,     sum(GEND_GBV17) as GEND_GBV17,     sum(GEND_GBV24M) as GEND_GBV24M,     sum(GEND_GBV24F) as GEND_GBV24F,     sum(GEND_GBV24) as GEND_GBV24,     sum(GEND_GBV25M) as GEND_GBV25M,     sum(GEND_GBV25F) as GEND_GBV25F,     sum(GEND_GBV25) as GEND_GBV25,     sum(GEND_GBVM) as GEND_GBVM,     sum(GEND_GBVF) as GEND_GBVF,     sum(GEND_GBV) as GEND_GBV,       sum(P121D0) as P121D0,     sum(P121D10) as P121D10,     sum(P121D15) as P121D15,     sum(P121D20) as P121D20,     sum(P121D25) as P121D25,     sum(P122D0) as P122D0,     sum(P122D15) as P122D15,     sum(P122D25) as P122D25,     sum(P123D0) as P123D0,     sum(P123D15) as P123D15,     sum(P123D25) as P123D25,     sum(P124D0) as P124D0,     sum(P124D15) as P124D15,     sum(P124D25) as P124D25    from "
                + form
                + " join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                + form + ".SubPartnerID = subpartnera.SubPartnerID   " + joinedwhwere + "  ";

        System.out.println(getexistingdata);
        String P121DM0 = "";
        String P121DF0 = "";
        String P121DM10 = "";
        String P121DF10 = "";
        String P121DM15 = "";
        String P121DF15 = "";
        String P121DM20 = "";
        String P121DF20 = "";
        String P121DM25 = "";
        String P121DF25 = "";
        String P121DMT = "";
        String P121DFT = "";
        String P121DTT = "";
        String P122DM0 = "";
        String P122DF0 = "";
        String P122DM15 = "";
        String P122DF15 = "";
        String P122DM25 = "";
        String P122DF25 = "";
        String P122DMT = "";
        String P122DFT = "";
        String P122DTT = "";
        String P123DM0 = "";
        String P123DF0 = "";
        String P123DM15 = "";
        String P123DF15 = "";
        String P123DM25 = "";
        String P123DF25 = "";
        String P123DMT = "";
        String P123DFT = "";
        String P123DTT = "";
        String P124DM0 = "";
        String P124DF0 = "";
        String P124DM15 = "";
        String P124DF15 = "";
        String P124DM25 = "";
        String P124DF25 = "";
        String P124DMT = "";
        String P124DFT = "";
        String P124DTT = "";
        String GEND_GBV9M = "";
        String GEND_GBV9F = "";
        String GEND_GBV9 = "";
        String GEND_GBV14M = "";
        String GEND_GBV14F = "";
        String GEND_GBV14 = "";
        String GEND_GBV17M = "";
        String GEND_GBV17F = "";
        String GEND_GBV17 = "";
        String GEND_GBV24M = "";
        String GEND_GBV24F = "";
        String GEND_GBV24 = "";
        String GEND_GBV25M = "";
        String GEND_GBV25F = "";
        String GEND_GBV25 = "";
        String GEND_GBVM = "";
        String GEND_GBVF = "";
        String GEND_GBV = "";

        String P121D0 = "";
        String P121D10 = "";
        String P121D15 = "";
        String P121D20 = "";
        String P121D25 = "";
        String P122D0 = "";
        String P122D15 = "";
        String P122D25 = "";
        String P123D0 = "";
        String P123D15 = "";
        String P123D25 = "";
        String P124D0 = "";
        String P124D15 = "";
        String P124D25 = "";

        String distid = "";

        if (session.getAttribute("subcountyid") != null) {
            distid = session.getAttribute("subcountyid").toString();
        }

        int counter = 0;

        conn.rs = conn.st.executeQuery(getexistingdata);
        while (conn.rs.next()) {
            //now check if form was updated and if its one month after data entry
            //now load the column values here

            //====================================================================p122       
            P121DM0 = conn.rs.getString("P121DM0");
            if (P121DM0 == null) {
                P121DM0 = "";
            }

            P121DF0 = conn.rs.getString("P121DF0");
            if (P121DF0 == null) {
                P121DF0 = "";
            }

            P121DM10 = conn.rs.getString("P121DM10");
            if (P121DM10 == null) {
                P121DM10 = "";
            }

            P121DF10 = conn.rs.getString("P121DF10");
            if (P121DF10 == null) {
                P121DF10 = "";
            }

            P121DM15 = conn.rs.getString("P121DM15");
            if (P121DM15 == null) {
                P121DM15 = "";
            }

            P121DF15 = conn.rs.getString("P121DF15");
            if (P121DF15 == null) {
                P121DF15 = "";
            }

            P121DM20 = conn.rs.getString("P121DM20");
            if (P121DM20 == null) {
                P121DM20 = "";
            }

            P121DF20 = conn.rs.getString("P121DF20");
            if (P121DF20 == null) {
                P121DF20 = "";
            }

            P121DM25 = conn.rs.getString("P121DM25");
            if (P121DM25 == null) {
                P121DM25 = "";
            }

            P121DF25 = conn.rs.getString("P121DF25");
            if (P121DF25 == null) {
                P121DF25 = "";
            }

            P121DMT = conn.rs.getString("P121DMT");
            if (P121DMT == null) {
                P121DMT = "";
            }

            P121DFT = conn.rs.getString("P121DFT");
            if (P121DFT == null) {
                P121DFT = "";
            }

            P121DTT = conn.rs.getString("P121DTT");
            if (P121DTT == null) {
                P121DTT = "";
            }

            //====================================================================p122

            P122DM0 = conn.rs.getString("P122DM0");
            if (P122DM0 == null) {
                P122DM0 = "";
            }

            P122DF0 = conn.rs.getString("P122DF0");
            if (P122DF0 == null) {
                P122DF0 = "";
            }

            P122DM15 = conn.rs.getString("P122DM15");
            if (P122DM15 == null) {
                P122DM15 = "";
            }

            P122DF15 = conn.rs.getString("P122DF15");
            if (P122DF15 == null) {
                P122DF15 = "";
            }

            P122DM25 = conn.rs.getString("P122DM25");
            if (P122DM25 == null) {
                P122DM25 = "";
            }

            P122DF25 = conn.rs.getString("P122DF25");
            if (P122DF25 == null) {
                P122DF25 = "";
            }

            P122DMT = conn.rs.getString("P122DMT");
            if (P122DMT == null) {
                P122DMT = "";
            }

            P122DFT = conn.rs.getString("P122DFT");
            if (P122DFT == null) {
                P122DFT = "";
            }

            P122DTT = conn.rs.getString("P122DTT");
            if (P122DTT == null) {
                P122DTT = "";
            }

            //====================================================================p123

            P123DM0 = conn.rs.getString("P123DM0");
            if (P123DM0 == null) {
                P123DM0 = "";
            }

            P123DF0 = conn.rs.getString("P123DF0");
            if (P123DF0 == null) {
                P123DF0 = "";
            }

            P123DM15 = conn.rs.getString("P123DM15");
            if (P123DM15 == null) {
                P123DM15 = "";
            }

            P123DF15 = conn.rs.getString("P123DF15");
            if (P123DF15 == null) {
                P123DF15 = "";
            }

            P123DM25 = conn.rs.getString("P123DM25");
            if (P123DM25 == null) {
                P123DM25 = "";
            }

            P123DF25 = conn.rs.getString("P123DF25");
            if (P123DF25 == null) {
                P123DF25 = "";
            }

            P123DMT = conn.rs.getString("P123DMT");
            if (P123DMT == null) {
                P123DMT = "";
            }

            P123DFT = conn.rs.getString("P123DFT");
            if (P123DFT == null) {
                P123DFT = "";
            }

            P123DTT = conn.rs.getString("P123DTT");
            if (P123DTT == null) {
                P123DTT = "";
            }

            //====================================================================p124

            P124DM0 = conn.rs.getString("P124DM0");
            if (P124DM0 == null) {
                P124DM0 = "";
            }

            P124DF0 = conn.rs.getString("P124DF0");
            if (P124DF0 == null) {
                P124DF0 = "";
            }

            P124DM15 = conn.rs.getString("P124DM15");
            if (P124DM15 == null) {
                P124DM15 = "";
            }

            P124DF15 = conn.rs.getString("P124DF15");
            if (P124DF15 == null) {
                P124DF15 = "";
            }

            P124DM25 = conn.rs.getString("P124DM25");
            if (P124DM25 == null) {
                P124DM25 = "";
            }

            P124DF25 = conn.rs.getString("P124DF25");
            if (P124DF25 == null) {
                P124DF25 = "";
            }

            P124DMT = conn.rs.getString("P124DMT");
            if (P124DMT == null) {
                P124DMT = "";
            }

            P124DFT = conn.rs.getString("P124DFT");
            if (P124DFT == null) {
                P124DFT = "";
            }

            P124DTT = conn.rs.getString("P124DTT");
            if (P124DTT == null) {
                P124DTT = "";
            }

            //=========================================================GEND_GBV

            GEND_GBV9M = conn.rs.getString("GEND_GBV9M");
            if (GEND_GBV9M == null) {
                GEND_GBV9M = "";
            }

            GEND_GBV9F = conn.rs.getString("GEND_GBV9F");
            if (GEND_GBV9F == null) {
                GEND_GBV9F = "";
            }

            GEND_GBV9 = conn.rs.getString("GEND_GBV9");
            if (GEND_GBV9 == null) {
                GEND_GBV9 = "";
            }

            //============
            GEND_GBV14M = conn.rs.getString("GEND_GBV14M");
            if (GEND_GBV14M == null) {
                GEND_GBV14M = "";
            }

            GEND_GBV14F = conn.rs.getString("GEND_GBV14F");
            if (GEND_GBV14F == null) {
                GEND_GBV14F = "";
            }

            GEND_GBV14 = conn.rs.getString("GEND_GBV14");
            if (GEND_GBV14 == null) {
                GEND_GBV14 = "";
            }
            //=======

            //============
            GEND_GBV17M = conn.rs.getString("GEND_GBV17M");
            if (GEND_GBV17M == null) {
                GEND_GBV17M = "";
            }

            GEND_GBV17F = conn.rs.getString("GEND_GBV17F");
            if (GEND_GBV17F == null) {
                GEND_GBV17F = "";
            }

            GEND_GBV17 = conn.rs.getString("GEND_GBV17");
            if (GEND_GBV17 == null) {
                GEND_GBV17 = "";
            }
            //=======

            //============
            GEND_GBV24M = conn.rs.getString("GEND_GBV24M");
            if (GEND_GBV24M == null) {
                GEND_GBV24M = "";
            }

            GEND_GBV24F = conn.rs.getString("GEND_GBV24F");
            if (GEND_GBV24F == null) {
                GEND_GBV24F = "";
            }

            GEND_GBV24 = conn.rs.getString("GEND_GBV24");
            if (GEND_GBV24 == null) {
                GEND_GBV24 = "";
            }
            //=======

            //============
            GEND_GBV25M = conn.rs.getString("GEND_GBV25M");
            if (GEND_GBV25M == null) {
                GEND_GBV25M = "";
            }

            GEND_GBV25F = conn.rs.getString("GEND_GBV25F");
            if (GEND_GBV25F == null) {
                GEND_GBV25F = "";
            }

            GEND_GBV25 = conn.rs.getString("GEND_GBV25");
            if (GEND_GBV25 == null) {
                GEND_GBV25 = "";
            }
            //=======

            //============
            GEND_GBVM = conn.rs.getString("GEND_GBVM");
            if (GEND_GBVM == null) {
                GEND_GBVM = "";
            }

            GEND_GBVF = conn.rs.getString("GEND_GBVF");
            if (GEND_GBVF == null) {
                GEND_GBVF = "";
            }

            GEND_GBV = conn.rs.getString("GEND_GBV");
            if (GEND_GBV == null) {
                GEND_GBV = "";
            }

            //=======
            //added totals
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            P121D0 = conn.rs.getString("P121D0");
            if (P121D0 == null) {
                P121D0 = "";
            }

            P121D10 = conn.rs.getString("P121D10");
            if (P121D10 == null) {
                P121D10 = "";
            }

            P121D15 = conn.rs.getString("P121D15");
            if (P121D15 == null) {
                P121D15 = "";
            }

            P121D20 = conn.rs.getString("P121D20");
            if (P121D20 == null) {
                P121D20 = "";
            }

            P121D25 = conn.rs.getString("P121D25");
            if (P121D25 == null) {
                P121D25 = "";
            }

            P122D0 = conn.rs.getString("P122D0");
            if (P122D0 == null) {
                P122D0 = "";
            }

            P122D15 = conn.rs.getString("P122D15");
            if (P122D15 == null) {
                P122D15 = "";
            }

            P122D25 = conn.rs.getString("P122D25");
            if (P122D25 == null) {
                P122D25 = "";
            }

            P123D0 = conn.rs.getString("P123D0");
            if (P123D0 == null) {
                P123D0 = "";
            }

            P123D15 = conn.rs.getString("P123D15");
            if (P123D15 == null) {
                P123D15 = "";
            }

            P123D25 = conn.rs.getString("P123D25");
            if (P123D25 == null) {
                P123D25 = "";
            }

            P124D0 = conn.rs.getString("P124D0");
            if (P124D0 == null) {
                P124D0 = "";
            }

            P124D15 = conn.rs.getString("P124D15");
            if (P124D15 == null) {
                P124D15 = "";
            }

            P124D25 = conn.rs.getString("P124D25");
            if (P124D25 == null) {
                P124D25 = "";
            }

        }

        String createdtable = "";

        if (1 == 1) {

            int r = 3;

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("P12.1.D:");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue(
                        "GEND_NORM: Number of people completing an intervention pertaining to gender norms, that meets minimum criteria");
                cl3x1.setCellStyle(style2);
                String head1[] = { "0-9", P121DM0, P121DF0, P121D0 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r + 5, 1, 1));
                shet.addMergedRegion(new CellRangeAddress(r, r + 5, 0, 0));

                r++;

            }

            //================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "10-14", P121DM10, P121DF10, P121D10 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================  

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "15-19", P121DM15, P121DF15, P121D15 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================  

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "20-24", P121DM20, P121DF20, P121D20 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================  

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "25+", P121DM25, P121DF25, P121D25 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================      

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "Total", P121DMT, P121DFT, P121DTT };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================      
            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("P12.2.D:");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue(
                        "Gender Based Violence and Coercion: Number of people reached by an individual, small group or community?level intervention or service that explicitly addresses ");
                cl3x1.setCellStyle(style2);
                String head1[] = { "0-14", P122DM0, P122DF0, P122D0 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 1, 1));
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 0, 0));

                r++;

            }

            //================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "15-24", P122DM15, P122DF15, P122D15 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================
            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "25+", P122DM25, P122DF25, P122D25 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================
            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "Total", P122DMT, P122DFT, P122DTT };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("P12.3.D:");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue(
                        "Women's Legal Rights and Protection Number of people reached by an individual, smallgroup, or community?level intervention or service that explicitly addresses the legal ");
                cl3x1.setCellStyle(style2);
                String head1[] = { "0-14", P123DM0, P123DF0, P123D0 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 1, 1));
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 0, 0));

                r++;

            }

            //================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "15-24", P123DM15, P123DF15, P123D15 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================  

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "25+", P123DM25, P123DF25, P123D25 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================
            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "TOTAL", P123DMT, P123DFT, P123DTT };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================

            //===================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("P12.4.D:");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue(
                        "Number of people reached by an individual, small group, or community?level intervention or service that explicitly aims to increase access to income and productive ");
                cl3x1.setCellStyle(style2);
                String head1[] = { "0-14", P124DM0, P124DF0, P124D0 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 1, 1));
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 0, 0));

                r++;

            }

            //================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "15-24", P124DM15, P124DF15, P124D15 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================  

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "25+", P124DM25, P124DF25, P124D25 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "TOTAL", P124DMT, P124DFT, P124DTT };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //===================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("GEND GBV:");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("Number of people receiving post-GBV Care");
                cl3x1.setCellStyle(style2);
                String head1[] = { "<10", GEND_GBV9M, GEND_GBV9F, GEND_GBV9 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r + 5, 1, 1));
                shet.addMergedRegion(new CellRangeAddress(r, r + 5, 0, 0));

                r++;

            }

            //===================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "10-14", GEND_GBV14M, GEND_GBV14F, GEND_GBV14 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "15-17", GEND_GBV17M, GEND_GBV17F, GEND_GBV17 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "18-24", GEND_GBV24M, GEND_GBV24F, GEND_GBV24 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "25+", GEND_GBV25M, GEND_GBV25F, GEND_GBV25 };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================
            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell cl3x = rwx.createCell(0);
                cl3x.setCellValue("");
                cl3x.setCellStyle(style2);

                HSSFCell cl3x1 = rwx.createCell(1);
                cl3x1.setCellValue("");
                cl3x1.setCellStyle(style2);
                String head1[] = { "Total", GEND_GBVM, GEND_GBVF, GEND_GBV };
                for (int a = 0; a < head.length; a++) {
                    HSSFCell clx = rwx.createCell(a + 2);
                    clx.setCellValue(head1[a]);
                    clx.setCellStyle(style2);
                }

                r++;

            }

            //================================================================================================

            createdtable = header
                    + "<br/><br/><table   border='1' style='border-color: #e5e5e5;margin-bottom: 3px;font-size:10;font-family:cambria;'>"
                    + "<tr class='form-actions'><th colspan='6'><b style='text-align:center;'> Prevention Sub Area 12:Gender</b></th></tr>";

            createdtable += "<tr><td rowspan='7'><b> P12.1.D: </b></td><td rowspan='7'> GEND_NORM: Number of people completing an intervention pertaining to gender norms, that meets minimum</td><td class='form-actions'>AGE</td><td class='form-actions'>MALE</td><td style='width:80px;' class='form-actions'>FEMALE</td><td class='form-actions'>TOTAL</td></tr>";
            createdtable += "<tr><td><b>0-9</b></td><td>" + P121DM0 + "</td><td>" + P121DF0 + "</td><td>"
                    + P121D0 + "</td></tr>";
            createdtable += "<tr><td><b>10-14</b></td><td>" + P121DM10 + "</td><td>" + P121DF10 + "</td><td>"
                    + P121D10 + "</td></tr>";
            createdtable += "<tr><td><b>15-19</b></td><td>" + P121DM15 + "</td><td>" + P121DF15 + "</td><td>"
                    + P121D15 + "</td></tr>";
            createdtable += "<tr><td><b>20-24</b></td><td>" + P121DM20 + "</td><td>" + P121DF20 + "</td><td>"
                    + P121D20 + "</td></tr>";
            createdtable += "<tr><td><b>25+ </b></b></td><td>" + P121DM25 + "</td><td>" + P121DF25 + "</td><td>"
                    + P121D25 + "</td></tr>";
            createdtable += "<tr><td><b>Total</b></td><td>" + P121DMT + "</td><td>" + P121DFT + "</td><td>"
                    + P121DTT + "</td></tr>";

            createdtable += "<tr><td rowspan='4'><b> P12.2.D: </b></td><td rowspan='4'>Gender Based Violence and Coercion: Number of people reached by an individual, small group or community?level intervention or service that explicitly addresses gender?based violence and coercion related to HIV/AIDS<td><b>0-14</b></td><td>"
                    + P122DM0 + "</td><td>" + P122DF0 + "</td><td>" + P122D0 + "</td></tr>";
            createdtable += "<tr><td><b>15-24</b></td><td>" + P122DM15 + "</td><td>" + P122DF15 + "</td><td>"
                    + P122D15 + "</td></tr>";
            createdtable += "<tr><td><b>25+</b></td><td>" + P122DM25 + "</td><td>" + P122DF25 + "</td><td>"
                    + P122D25 + "</td></tr>";
            createdtable += "<tr><td><b>Total</b></td><td>" + P122DMT + "</td><td>" + P122DFT + "</td><td>"
                    + P122DTT + "</td></tr>";

            createdtable += "<tr><td rowspan='4'><b> P12.3.D: </b></td><td rowspan='4'>Women's Legal Rights and Protection Number of people reached by an individual, small group, or community?level intervention or service that explicitly addresses the legal rights and protection of women and girls impacted by HIV/AIDS<td><b>0-14</b></td><td>"
                    + P123DM0 + "</td><td>" + P123DF0 + "</td><td>" + P123D0 + "</td></tr>";
            createdtable += "<tr><td><b>15-24</b></td><td>" + P123DM15 + "</td><td>" + P123DF15 + "</td><td>"
                    + P123D15 + "</td></tr>";
            createdtable += "<tr><td><b>25+</b></td><td>" + P123DM25 + "</td><td>" + P123DF25 + "</td><td>"
                    + P123D25 + "</td></tr>";
            createdtable += "<tr><td><b>Total</b></td><td>" + P123DMT + "</td><td>" + P123DFT + "</td><td>"
                    + P123DTT + "</td></tr>";

            createdtable += "<tr><td rowspan='4'><b> P12.4.D: </b></td><td rowspan='4'>Number of people reached by an individual, small group, or community?level intervention or service that explicitly aims to increase access to income and productive resources of women and girls impacted by HIV/AIDS M 0-15<td><b>0-14</b></td><td>"
                    + P124DM0 + "</td><td>" + P124DF0 + "</td><td>" + P124D0 + "</td></tr>";
            createdtable += "<tr><td><b>15-24</b></td><td>" + P124DM15 + "</td><td>" + P124DF15 + "</td><td> "
                    + P124D15 + "</td></tr>";
            createdtable += "<tr><td><b>25+</b></td><td>" + P124DM25 + "</td><td>" + P124DF25 + "</td><td>"
                    + P124D25 + "</td></tr>";
            createdtable += "<tr><td><b>Total</b></td><td>" + P124DMT + "</td><td>" + P124DFT + "</td><td>"
                    + P124DTT + "</td></tr>";
            createdtable += "<tr><td rowspan='6'><b> GEND_GBV </b></td><td rowspan='6'>Number of people receiving post-GBV Care<td><b> less than 10 </b> </td><td>"
                    + GEND_GBV9M + "</td><td>" + GEND_GBV9F + "</td><td>" + GEND_GBV9 + "</td></tr>";
            createdtable += "<tr><td><b>10-14</b></td><td>" + GEND_GBV14M + "</td><td>" + GEND_GBV14F
                    + "</td><td>" + GEND_GBV14 + "</td></tr>";
            createdtable += "<tr><td><b>15-17</b></td><td>" + GEND_GBV17M + "</td><td>" + GEND_GBV17F
                    + "</td><td>" + GEND_GBV17 + "</td></tr>";
            createdtable += "<tr><td><b>18-24</b></td><td>" + GEND_GBV24M + "</td><td>" + GEND_GBV24F
                    + "</td><td>" + GEND_GBV24 + "</td></tr>";
            createdtable += "<tr><td><b>25+</b></td><td>" + GEND_GBV25M + "</td><td>" + GEND_GBV25F
                    + "</td><td>" + GEND_GBV25 + "</td></tr>";
            createdtable += "<tr><td><b>Total</b></td><td>" + GEND_GBVM + "</td><td>" + GEND_GBVF + "</td><td>"
                    + GEND_GBV + "</td></tr>";
            createdtable += "<tr><td></td><td></td><td class='form-actions'>AGE</td><td class='form-actions'>MALE</td><td style='width:80px;' class='form-actions'>FEMALE</td><td class='form-actions'>TOTAL</td></tr>";
            createdtable += "</table>";

        }

        //System.out.println(createdtable);

        if (conn.conn != null) {
            conn.conn.close();
        }
        if (conn.rs != null) {
            conn.rs.close();
        }
        if (conn.rs1 != null) {
            conn.rs1.close();
        }
        if (conn.rs2 != null) {
            conn.rs2.close();
        }
        if (conn.st != null) {
            conn.st.close();
        }
        if (conn.st2 != null) {
            conn.st2.close();
        }

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition",
                "attachment; filename=" + form + yearmonth + "_Generated_On_" + createdOn + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
        outStream.close();

    } catch (SQLException ex) {
        Logger.getLogger(Vmmcpdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:reports.htctracker731.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {

    dbConn conn = new dbConn();
    session = request.getSession();//from ww  w.  ja v a 2 s . c  om

    year = Integer.parseInt(request.getParameter("year"));
    //        year=2015;
    prevYear = year - 1;
    IdGenerator IG = new IdGenerator();
    allMonths.clear();
    allReports.clear();
    duration = "WHERE (moh731.yearmonth BETWEEN " + prevYear + "" + 10 + " AND " + year
            + "09) AND ( subpartnera.HTC=1) AND ( HV0103 > 0)";

    currentMonth = IG.CurrentMonth();

    monthsData = "";
    //            ^^^^^^^^^^^^^CREATE STATIC AND WRITE STATIC DATA TO THE EXCELL^^^^^^^^^^^^
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet shet1 = wb.createSheet("MOH 731 HTC REPORTS TRACKER");

    HSSFFont font = wb.createFont();
    font.setFontHeightInPoints((short) 18);
    font.setFontName("Arial Black");
    font.setColor((short) 0000);
    CellStyle style = wb.createCellStyle();
    style.setFont(font);
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    HSSFFont font2 = wb.createFont();
    font2.setFontName("Arial Black");
    font2.setColor((short) 0000);
    CellStyle style2 = wb.createCellStyle();
    style2.setFont(font2);

    HSSFCellStyle stborder = wb.createCellStyle();
    stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    stborder.setWrapText(true);

    HSSFCellStyle stylex = wb.createCellStyle();
    stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    HSSFFont fontx = wb.createFont();
    fontx.setColor(HSSFColor.DARK_BLUE.index);
    stylex.setFont(fontx);
    stylex.setWrapText(true);

    HSSFCellStyle styleHeader = wb.createCellStyle();
    styleHeader.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    styleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);
    styleHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    HSSFFont fontHeader = wb.createFont();
    fontHeader.setColor(HSSFColor.DARK_BLUE.index);
    styleHeader.setFont(fontHeader);
    styleHeader.setWrapText(true);

    for (int i = 0; i <= 2; i++) {
        shet1.setColumnWidth(i, 8000);
    }
    HSSFRow rw1S1 = shet1.createRow(0);
    HSSFCell S1cell = rw1S1.createCell(0);
    S1cell.setCellValue("COUNTY NAME");
    S1cell.setCellStyle(stylex);

    HSSFCell S1cellX = rw1S1.createCell(1);
    S1cellX.setCellValue("SUB COUNTY");
    S1cellX.setCellStyle(stylex);

    S1cellX = rw1S1.createCell(2);
    S1cellX.setCellValue("HEALTH FACILITY");
    S1cellX.setCellStyle(stylex);

    S1cellX = rw1S1.createCell(3);
    S1cellX.setCellValue("MFL CODE");
    S1cellX.setCellStyle(stylex);

    S1cellX = rw1S1.createCell(4);
    S1cellX.setCellValue("EXPECTED REPORTS");
    S1cellX.setCellStyle(stylex);

    counterHeader = 5;
    String getMaxandMin = "SELECT DISTINCT(month.name),month.id FROM moh731 JOIN month ON moh731.Mois=month.id JOIN subpartnera ON moh731.SubPartnerID=subpartnera.SubPartnerID "
            + duration + " " + " ORDER BY  moh731.yearmonth";
    conn.rs = conn.st.executeQuery(getMaxandMin);
    while (conn.rs.next()) {
        monthName = conn.rs.getString(1);
        monthid = conn.rs.getInt(2);
        if (monthid <= 9) {
            currentYear = year;
        } else {
            currentYear = prevYear;
        }
        System.out.println(" Months are : " + monthName);
        allMonths.add(monthName);
        allReports.add(0);
        S1cellX = rw1S1.createCell(counterHeader);
        S1cellX.setCellValue(monthName);
        S1cellX.setCellStyle(stylex);
        counterHeader++;
    }
    prevFacility = currentFacility = "";
    currentDistrict = prevDistrict = "";
    currentCounty = prevCounty = "";
    counter = districtCounter = countyCounter = districtsMerged = 0;
    arraySize = allReports.size();

    if (allMonths.size() > 0) {
        String checkReports = "SELECT county.County,district.DistrictNom,subpartnera.SubPartnerNom,"
                + "subpartnera.CentreSanteId,COUNT(moh731.SubPartnerID),month.name,subpartnera.SubPartnerID "
                + "FROM subpartnera " + "LEFT JOIN moh731 ON moh731.SubPartnerID=subpartnera.SubPartnerID "
                + "LEFT JOIN district ON subpartnera.DistrictID=district.DistrictID "
                + "LEFT JOIN county ON county.CountyID=district.CountyID "
                + "LEFT JOIN month ON moh731.Mois=month.id " + " " + duration + " "
                + " GROUP BY subpartnera.SubPartnerNom,moh731.Annee,moh731.Mois "
                + "ORDER BY county.County,district.DistrictNom,subpartnera.SubPartnerNom,moh731.Mois";
        System.out.println(checkReports);
        conn.rs = conn.st.executeQuery(checkReports);
        while (conn.rs.next()) {
            countyName = conn.rs.getString(1);
            districtName = conn.rs.getString(2);
            facilityName = conn.rs.getString(3);
            mflcode = conn.rs.getString(4);
            status = conn.rs.getInt(5);
            selectedMonth = conn.rs.getString(6);
            currentFacility = conn.rs.getString(7);
            currentDistrict = districtName;
            currentCounty = countyName;
            //     CHECK WHERE TO PLACE THE NUMBER; 

            monthPosition = allMonths.indexOf(selectedMonth);

            if (!prevFacility.equals(currentFacility)) {

                if (!prevDistrict.equals(currentDistrict) && !prevDistrict.equals("")) {
                    counter++;
                    noReports = districtCounter + 1;
                    HSSFRow rwTotal = shet1.createRow(counter);
                    HSSFCell SX = rwTotal.createCell(0);
                    SX.setCellStyle(stborder);

                    SX = rwTotal.createCell(1);
                    SX.setCellValue(prevDistrict + " TOTALS : ");
                    SX.setCellStyle(styleHeader);

                    SX = rwTotal.createCell(2);
                    SX.setCellStyle(styleHeader);

                    SX = rwTotal.createCell(3);
                    SX.setCellStyle(styleHeader);

                    SX = rwTotal.createCell(4);
                    SX.setCellValue(noReports);
                    SX.setCellStyle(styleHeader);
                    shet1.addMergedRegion(new CellRangeAddress(counter, counter, 1, 3));

                    for (int j = 0; j < allReports.size(); j++) {
                        //         System.out.println("district name : "+prevDistrict+" no of reports : "+allReports.get(j).toString()+" for month : "+allMonths.get(j).toString());
                        int dataPos = 5 + j;
                        SX = rwTotal.createCell(dataPos);
                        SX.setCellValue(Integer.parseInt(allReports.get(j).toString()));
                        SX.setCellStyle(styleHeader);
                    }
                    for (int k = 0; k < arraySize; k++) {
                        allReports.set(k, 0);
                    }
                }
                counter++;
                HSSFRow rw1 = shet1.createRow(counter);
                HSSFCell S1 = rw1.createCell(0);
                S1.setCellValue(countyName);
                S1.setCellStyle(stborder);

                S1 = rw1.createCell(1);
                S1.setCellValue(districtName);
                S1.setCellStyle(stborder);

                S1 = rw1.createCell(2);
                S1.setCellValue(facilityName);
                S1.setCellStyle(stborder);

                S1 = rw1.createCell(3);
                S1.setCellValue(mflcode);
                S1.setCellStyle(stborder);

                S1 = rw1.createCell(4);
                S1.setCellValue(1);
                S1.setCellStyle(stborder);

                for (int j = 0; j < allMonths.size(); j++) {
                    int cellPos = j + 5;
                    S1 = rw1.createCell(cellPos);
                    // System.out.println("counter : "+counter+" datapos : "+cellPos+" status : "+status);
                    S1.setCellStyle(stborder);

                }
                int dataPos = 5 + monthPosition;
                S1 = rw1.getCell(dataPos);
                S1.setCellValue(status);

                if (!prevDistrict.equals(currentDistrict) && !prevDistrict.equals("")) {
                    int distStart = counter - districtCounter - 2;
                    int distEnd = counter - 2;
                    shet1.addMergedRegion(new CellRangeAddress(distStart, distEnd, 1, 1));
                    districtsMerged++;
                    districtCounter = 0;

                    for (int j = 0; j < arraySize; j++) {
                        allReports.set(j, 0);
                    }

                } else {
                    if (counter == 1) {
                    } else {
                        districtCounter++;
                    }
                }
                if (!prevCounty.equals(currentCounty) && !prevCounty.equals("")) {
                    int countyStart = counter - countyCounter - districtsMerged - 1;
                    int countyEnd = counter - 1;
                    shet1.addMergedRegion(new CellRangeAddress(countyStart, countyEnd, 0, 0));
                    countyCounter = 0;
                    districtsMerged = 0;
                } else {
                    if (counter == 1) {
                    } else {
                        countyCounter++;
                    }
                }
                prevCounty = currentCounty;
                prevDistrict = currentDistrict;
            } else {

                HSSFRow rw1 = shet1.getRow(counter);
                int dataPos = 5 + monthPosition;
                HSSFCell S1 = rw1.getCell(dataPos);
                S1.setCellValue(status);
                //    
            }

            if (status == 1) {
                int currentData = Integer.parseInt(allReports.get(monthPosition).toString()) + 1;
                allReports.set(monthPosition, currentData);
            }

            prevFacility = currentFacility;

        }
        //    MATCH THE LAST DISTRICTS
        counter++;
        noReports = districtCounter + 1;
        HSSFRow rwTotal = shet1.createRow(counter);
        HSSFCell SX = rwTotal.createCell(0);
        SX.setCellStyle(stborder);

        SX = rwTotal.createCell(1);
        SX.setCellValue(prevDistrict + " TOTALS : ");
        SX.setCellStyle(styleHeader);

        SX = rwTotal.createCell(2);
        SX.setCellStyle(styleHeader);

        SX = rwTotal.createCell(3);
        SX.setCellStyle(styleHeader);

        SX = rwTotal.createCell(4);
        SX.setCellValue(noReports);
        SX.setCellStyle(styleHeader);
        shet1.addMergedRegion(new CellRangeAddress(counter, counter, 1, 3));

        int distStart = counter - districtCounter - 1;
        int distEnd = counter - 1;
        //     System.out.println("MERGE BETWEEN : START : "+distStart+" END : "+distEnd);
        shet1.addMergedRegion(new CellRangeAddress(distStart, distEnd, 1, 1));
        districtCounter = 0;

        int countyStart = counter - countyCounter - 2;
        int countyEnd = counter;
        //        System.out.println("MERGE BETWEEN : START : "+distStart+" END : "+distEnd);
        shet1.addMergedRegion(new CellRangeAddress(countyStart, countyEnd, 0, 0));
        countyCounter = 0;

        for (int j = 0; j < allReports.size(); j++) {
            //         System.out.println("district name : "+prevDistrict+" no of reports : "+allReports.get(j).toString()+" for month : "+allMonths.get(j).toString());
            int dataPos = 5 + j;
            SX = rwTotal.createCell(dataPos);
            SX.setCellValue(Integer.parseInt(allReports.get(j).toString()));
            SX.setCellStyle(styleHeader);
        }

        if (conn.st != null) {
            conn.st.close();
        }
        if (conn.st1 != null) {
            conn.st1.close();
        }
        if (conn.st2 != null) {
            conn.st2.close();
        }

        if (conn.rs != null) {
            conn.rs.close();
        }
        if (conn.rs1 != null) {
            conn.rs1.close();
        }
        if (conn.rs2 != null) {
            conn.rs2.close();
        }
        if (conn.conn != null) {
            conn.conn.close();
        }

        createdOn = IG.CreatedOn();

        // write it as an excel attachment
        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition", "attachment; filename=HTC_Tracker_summary_for_PEPFAR_YEAR("
                + year + ")_" + createdOn.trim() + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } else {

        session.setAttribute("noTrackerReport",
                "<font color=\"red\"><b>SORRY:</b> No report was found for " + year + ".</red>");
        response.sendRedirect("reportsTracker.jsp");
    }

}

From source file:reports.kmmpexcel.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   www. j  ava 2s.c o  m*/
        response.setContentType("text/html;charset=UTF-8");
        session = request.getSession();

        dbConn conn = new dbConn();
        //get the existing data for the month, year and facility that is already on session

        String month = "";
        String year = "";
        String facil = "361";

        String form = "kmmp";

        String reportType = "";
        if (request.getParameter("reportType") != null) {
            reportType = request.getParameter("reportType");
        }
        String reportDuration = "";
        if (request.getParameter("reportDuration") != null) {
            reportDuration = request.getParameter("reportDuration");
        }

        //=====================================================================================================

        year = "2015";
        month = "5";
        String county = "";

        String header = "";

        String reporttype = "";

        if (request.getParameter("year") != null) {
            year = request.getParameter("year");
        }

        if (request.getParameter("facility") != null && reportType.equals("2")) {
            facil = request.getParameter("facility");

            String getfacil = "select SubPartnerNom,CentreSanteId as mflcode from subpartnera where SubPartnerID='"
                    + facil + "'";
            conn.rs = conn.st.executeQuery(getfacil);

            while (conn.rs.next()) {

                header += " FACILITY : " + conn.rs.getString(1).toUpperCase() + "     MFL CODE  :  "
                        + conn.rs.getString(2) + "  ";

            }

        }

        if (request.getParameter("county") != null && reportType.equals("2")) {
            county = request.getParameter("county");

            String getcounty = "select County from county where CountyID='" + county + "'";
            conn.rs = conn.st.executeQuery(getcounty);

            while (conn.rs.next()) {

                header += " COUNTY : " + conn.rs.getString(1).toUpperCase() + " ";

            }

        }

        if (request.getParameter("month") != null && reportDuration.equals("4")) {
            month = request.getParameter("month");

            String getmonth = "select name as monthname from month where id='" + month + "'";
            conn.rs = conn.st.executeQuery(getmonth);

            while (conn.rs.next()) {

                header += " MONTH : " + conn.rs.getString(1).toUpperCase() + " ";

            }

        }

        header += " YEAR : " + year + "";

        String facilitywhere = "";
        String yearwhere = "";
        String monthwhere = "";
        String countywhere = "";
        String duration = "";
        String semi_annual = "";
        String quarter = "";

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        int yearcopy = Integer.parseInt(year);

        //        reportType="2";
        //        year=2015;
        //        reportDuration="3";
        String yearmonth = "" + year;
        int prevYear = yearcopy - 1;
        int maxYearMonth = 0;
        int monthcopy = 0;
        //        GET REPORT DURATION============================================

        if (reportDuration.equals("1")) {
            yearmonth += "_AnnualReport";
            duration = " " + form + ".yearmonth BETWEEN " + prevYear + "10 AND " + year + "09";
        } else if (reportDuration.equals("2")) {
            semi_annual = request.getParameter("semi_annual");
            //        semi_annual="2";
            if (semi_annual.equals("1")) {
                yearmonth = prevYear + "_Oct_" + year + "_Mar";
                duration = " " + form + ".yearmonth BETWEEN " + prevYear + "10 AND " + year + "03";
            } else {
                yearmonth += "_Apr_Sep";
                duration = " " + form + ".yearmonth BETWEEN " + year + "04 AND " + year + "09";
            }
        }

        else if (reportDuration.equals("3")) {
            String startMonth, endMonth;
            quarter = request.getParameter("quarter");
            //       quarter="3";
            String getMonths = "SELECT months,name FROM quarter WHERE id='" + quarter + "'";
            conn.rs = conn.st.executeQuery(getMonths);
            if (conn.rs.next() == true) {

                String months[] = conn.rs.getString(1).split(",");
                startMonth = months[0];
                endMonth = months[2];
                if (quarter.equals("1")) {
                    duration = " " + form + ".yearmonth BETWEEN " + prevYear + "" + startMonth + " AND "
                            + prevYear + "" + endMonth;
                    yearmonth = prevYear + "_" + conn.rs.getString(2);
                } else {
                    yearmonth = year + "_" + conn.rs.getString(2);
                    duration = " " + form + ".yearmonth BETWEEN " + year + "" + startMonth + " AND " + year + ""
                            + endMonth;
                }
            }
        }

        else if (reportDuration.equals("4")) {
            monthcopy = Integer.parseInt(request.getParameter("month"));

            //     month=5;
            if (monthcopy >= 10) {
                yearmonth = prevYear + "_" + month;
                duration = " " + form + ".yearmonth=" + prevYear + "" + month;
            } else {
                duration = " " + form + ".yearmonth=" + year + "0" + month;
                yearmonth = year + "_(" + month + ")";
            }
        } else {
            duration = "";
        }

        //======================================================================   

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        String getexistingdata = "";

        if (!county.equals("")) {

            countywhere = " and countyid = '" + county + "'";

        }

        if (!facil.equals("") && reportType.equalsIgnoreCase("2")) {

            facilitywhere = " and kmmp.SubPartnerID = '" + facil + "'";

        }

        //String joinedwhwere=" where 1=1 "+yearwhere+" && "+duration;  

        String joinedwhwere = " where 1=1 " + facilitywhere + "  " + yearwhere + " && " + duration;

        //=====================================================================================================    

        //______________________________________________________________________________________
        //                       NOW CREATE THE WORKSHEETS          
        //______________________________________________________________________________________  

        HSSFWorkbook wb = new HSSFWorkbook();

        //______________________________________________________________________________________
        //______________________________________________________________________________________

        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        HSSFSheet shet = wb.createSheet(form);

        //create headers for that worksheet

        HSSFRow rw = shet.createRow(0);
        rw.setHeightInPoints(25);
        HSSFCell cl0 = rw.createCell(0);
        cl0.setCellValue("KMMP HEALTH FACILITY REPORTING FORM");
        cl0.setCellStyle(stylex);

        for (int a = 1; a < 4; a++) {
            HSSFCell clx = rw.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        HSSFRow rw1 = shet.createRow(1);
        rw1.setHeightInPoints(23);
        HSSFCell cl = rw1.createCell(0);
        cl.setCellValue(header);
        cl.setCellStyle(stylex);

        for (int a = 1; a < 4; a++) {
            HSSFCell clx = rw1.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        HSSFRow rw2 = shet.createRow(2);
        rw2.setHeightInPoints(23);
        HSSFCell cl3 = rw2.createCell(0);
        cl3.setCellValue("KMMP OUTPUT DATA");
        cl3.setCellStyle(stylex);

        for (int a = 1; a < 4; a++) {
            HSSFCell clx = rw2.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        shet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
        shet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));
        shet.addMergedRegion(new CellRangeAddress(2, 2, 0, 3));
        shet.addMergedRegion(new CellRangeAddress(3, 3, 1, 2));
        shet.addMergedRegion(new CellRangeAddress(4, 4, 1, 2));
        shet.addMergedRegion(new CellRangeAddress(5, 5, 1, 2));
        shet.addMergedRegion(new CellRangeAddress(5, 7, 0, 0));
        shet.addMergedRegion(new CellRangeAddress(6, 6, 1, 2));
        shet.addMergedRegion(new CellRangeAddress(7, 7, 1, 2));
        shet.addMergedRegion(new CellRangeAddress(8, 8, 1, 2));
        shet.addMergedRegion(new CellRangeAddress(9, 11, 0, 0));
        shet.addMergedRegion(new CellRangeAddress(9, 11, 1, 1));
        shet.addMergedRegion(new CellRangeAddress(12, 12, 1, 2));
        shet.addMergedRegion(new CellRangeAddress(13, 13, 1, 2));
        shet.setColumnWidth(0, 2000);
        shet.setColumnWidth(1, 17000);
        shet.setColumnWidth(2, 5000);

        getexistingdata = "select  sum(KMMP1) as KMMP1,   sum(KMMP2) as KMMP2,  sum(KMMP3a) as KMMP3a,   sum(KMMP3b) as KMMP3b,   avg(KMMP3c) as KMMP3c ,   sum(KMMP4) as KMMP4 ,   sum(KMMP5a) as KMMP5a,    sum(KMMP5b) as KMMP5b,    sum(KMMP5c) as KMMP5c,    sum(HV0205) as HV0205,    sum(HV0206) as HV0206 from kmmp join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on kmmp.SubPartnerID = subpartnera.SubPartnerID   "
                + joinedwhwere + "  ";

        System.out.println(getexistingdata);
        String formtype = "<b><font color='#4b8df8'>New Entry</font></b>";
        String KMMP1 = "";
        String KMMP2 = "";
        String KMMP3a = "";
        String KMMP3b = "";
        String KMMP3c = "";
        String KMMP4 = "";
        String KMMP5a = "";
        String KMMP5b = "";
        String KMMP5c = "";
        String HV0205 = "";
        String HV0206 = "";

        String distid = "";

        if (session.getAttribute("subcountyid") != null) {
            distid = session.getAttribute("subcountyid").toString();
        }

        int counter = 0;

        conn.rs = conn.st.executeQuery(getexistingdata);
        while (conn.rs.next()) {
            //now check if form was updated and if its one month after data entry
            //now load the column values here

            KMMP1 = conn.rs.getString("KMMP1");
            if (KMMP1 == null) {
                KMMP1 = "";
            }

            KMMP2 = conn.rs.getString("KMMP2");
            if (KMMP2 == null) {
                KMMP2 = "";
            }

            KMMP3a = conn.rs.getString("KMMP3a");
            if (KMMP3a == null) {
                KMMP3a = "";
            }

            KMMP3b = conn.rs.getString("KMMP3b");
            if (KMMP3b == null) {
                KMMP3b = "";
            }

            KMMP3c = conn.rs.getString("KMMP3c");
            if (KMMP3c == null) {
                KMMP3c = "";
            }

            KMMP4 = conn.rs.getString("KMMP4");
            if (KMMP4 == null) {
                KMMP4 = "";
            }

            KMMP5a = conn.rs.getString("KMMP5a");
            if (KMMP5a == null) {
                KMMP5a = "";
            }

            KMMP5b = conn.rs.getString("KMMP5b");
            if (KMMP5b == null) {
                KMMP5b = "";
            }

            KMMP5c = conn.rs.getString("KMMP5c");
            if (KMMP5c == null) {
                KMMP5c = "";
            }

            HV0205 = conn.rs.getString("HV0205");
            if (HV0205 == null) {
                HV0205 = "";
            }

            HV0206 = conn.rs.getString("HV0206");
            if (HV0206 == null) {
                HV0206 = "";
            }

        }

        String createdtable = "";

        if (1 == 1) {

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(3);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(0);
                cl4.setCellValue("1");
                cl4.setCellStyle(style2);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue("No of New HIV positive clients enrolled in KMMP Services (ANC and PN) ");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP1);
                cl43.setCellStyle(style2);
            }
            //================================================================================================  

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(4);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(0);
                cl4.setCellValue("2");
                cl4.setCellStyle(style2);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue("No of New HIV negative clients enrolled in KMMP Services (ANC Only) ");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP2);
                cl43.setCellStyle(style2);
            }
            //================================================================================================

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(5);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(0);
                cl4.setCellValue("3");
                cl4.setCellStyle(style2);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue("a) No. of HIV-positive pregnant women enrolled in KMMP Services");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP3a);
                cl43.setCellStyle(style2);
            }
            //================================================================================================

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(6);
                rw3.setHeightInPoints(23);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue(
                        " b) Total number of HIV-positive pregnant women in facility (New positive \n and Known Positive-MOH731)");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP3b);
                cl43.setCellStyle(style2);
            }
            //================================================================================================

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(7);
                rw3.setHeightInPoints(23);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue(" Percentage of new IV-positive pregnant women enrolled in KMMP Services");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP3c.substring(0, 2) + "%");
                cl43.setCellStyle(style2);
            }
            //================================================================================================

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(8);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(0);
                cl4.setCellValue("4");
                cl4.setCellStyle(style2);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue("No. of KMMP support group sessions held");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP4);
                cl43.setCellStyle(style2);
            }
            //================================================================================================

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(9);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(0);
                cl4.setCellValue("");
                cl4.setCellStyle(style2);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue("Defaulter tracing");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("New Defaulted Clients");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP5a);
                cl43.setCellStyle(style2);
            }
            //================================================================================================

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(10);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(1);
                cl4.setCellValue("");
                cl4.setCellStyle(style2);
                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("Clients Reached");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP5b);
                cl43.setCellStyle(style2);
            }
            //================================================================================================
            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(11);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(1);
                cl4.setCellValue("");
                cl4.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("Successfully resolved");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(KMMP5c);
                cl43.setCellStyle(style2);
            }

            //================================================================================================

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(12);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(0);
                cl4.setCellValue("");
                cl4.setCellStyle(style2);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue("MOH 731 HV02-05 Known positive status (at entry into ANC) ");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(HV0205);
                cl43.setCellStyle(style2);
            }
            //================================================================================================  

            if (1 == 1) {
                HSSFRow rw3 = shet.createRow(13);
                rw3.setHeightInPoints(23);
                HSSFCell cl4 = rw3.createCell(0);
                cl4.setCellValue("");
                cl4.setCellStyle(style2);

                HSSFCell cl41 = rw3.createCell(1);
                cl41.setCellValue("MOH 731 HV02-06 Antenatal");
                cl41.setCellStyle(style2);

                HSSFCell cl42 = rw3.createCell(2);
                cl42.setCellValue("");
                cl42.setCellStyle(style2);

                HSSFCell cl43 = rw3.createCell(3);
                cl43.setCellValue(HV0206);
                cl43.setCellStyle(style2);
            }

            //================================================================================================     
            createdtable += header
                    + "<br/><br/><br/><table class='mytable'   border=\"1\" style=\"font-family:cambria; border-color: #e5e5e5;margin-bottom: 3px; width:500px;\"><tr class='form-actions'><th colspan='3'><b style=\"text-align:center;\"> KMMP OUTPUT DATA</b></th><th>Total</th></tr><tr><td><b> 1 </b></td><td colspan='2'>No of New HIV positive clients enrolled in KMMP Services (ANC and PN) </td><td>"
                    + KMMP1 + "</td></tr>";

            createdtable += "<tr><td>Successfully Resolved</td><td>" + KMMP5c + "</td></tr>";

            createdtable += "<tr><td></td><td colspan='2'>MOH 731 HV02-05 Known positive status (at entry into ANC) :</td><td>"
                    + HV0205 + "</td></tr>";

            createdtable += "<tr><td></td><td colspan='2'>MOH 731 HV02-06 Antenatal:</td><td>" + HV0206
                    + "</td></tr></table> <div class='form-actions'></div>";

        }

        //System.out.println(createdtable);

        if (conn.conn != null) {
            conn.conn.close();
        }
        if (conn.rs != null) {
            conn.rs.close();
        }
        if (conn.rs1 != null) {
            conn.rs1.close();
        }
        if (conn.rs2 != null) {
            conn.rs2.close();
        }
        if (conn.st != null) {
            conn.st.close();
        }
        if (conn.st2 != null) {
            conn.st2.close();
        }

        //#############################################################################################################

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition",
                "attachment; filename=kmmp" + yearmonth + "_Generated_On_" + createdOn + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
        outStream.close();

        //#############################################################################################################

    } catch (SQLException ex) {
        Logger.getLogger(kmmppdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:reports.nutritionexcel.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   w  w w  . j  a v  a 2  s. c  om
        response.setContentType("text/html;charset=UTF-8");
        session = request.getSession();

        dbConn conn = new dbConn();
        //get the existing data for the month, year and facility that is already on session

        String month = "";
        String year = "";
        String facil = "";

        String form = "nutrition";

        //=====================================================================================================

        year = "2015";
        month = "5";
        String county = "";

        String header = "";

        String reportType = "";
        if (request.getParameter("reportType") != null) {
            reportType = request.getParameter("reportType");
        }
        String reportDuration = "";
        if (request.getParameter("reportDuration") != null) {
            reportDuration = request.getParameter("reportDuration");
        }
        if (request.getParameter("year") != null) {
            year = request.getParameter("year");
        }

        if (request.getParameter("facility") != null && reportType.equals("2")) {
            facil = request.getParameter("facility");

            String getfacil = "select SubPartnerNom,CentreSanteId as mflcode from subpartnera where SubPartnerID='"
                    + facil + "'";
            conn.rs = conn.st.executeQuery(getfacil);

            while (conn.rs.next()) {

                header += " FACILITY : " + conn.rs.getString(1).toUpperCase() + "    MFL CODE  :  "
                        + conn.rs.getString(2) + "  ";

            }

        }

        if (request.getParameter("county") != null && reportType.equals("2")) {
            county = request.getParameter("county");

            String getcounty = "select County from county where CountyID='" + county + "'";
            conn.rs = conn.st.executeQuery(getcounty);

            while (conn.rs.next()) {

                header += " COUNTY : " + conn.rs.getString(1).toUpperCase() + " ";

            }

        }

        if (request.getParameter("month") != null && reportDuration.equals("4")) {
            month = request.getParameter("month");

            String getmonth = "select name as monthname from month where id='" + month + "'";
            conn.rs = conn.st.executeQuery(getmonth);

            while (conn.rs.next()) {

                header += " MONTH : " + conn.rs.getString(1).toUpperCase() + " ";

            }

        }

        header += " YEAR : " + year + "";

        String facilitywhere = "";
        String yearwhere = "";
        String monthwhere = "";
        String countywhere = "";
        String duration = "";
        String semi_annual = "";
        String quarter = "";

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        int yearcopy = Integer.parseInt(year);

        //        reportType="2";
        //        year=2015;
        //        reportDuration="3";
        String yearmonth = "" + year;
        int prevYear = yearcopy - 1;
        int maxYearMonth = 0;
        int monthcopy = 0;
        //        GET REPORT DURATION============================================

        if (reportDuration.equals("1")) {
            yearmonth += "_AnnualReport";
            duration = " " + form + ".yearmonth BETWEEN " + prevYear + "10 AND " + year + "09";
        } else if (reportDuration.equals("2")) {
            semi_annual = request.getParameter("semi_annual");
            //        semi_annual="2";
            if (semi_annual.equals("1")) {
                yearmonth = prevYear + "_Oct_" + year + "_Mar";
                duration = " " + form + ".yearmonth BETWEEN " + prevYear + "10 AND " + year + "03";
            } else {
                yearmonth += "_Apr_Sep";
                duration = " " + form + ".yearmonth BETWEEN " + year + "04 AND " + year + "09";
            }
        }

        else if (reportDuration.equals("3")) {
            String startMonth, endMonth;
            quarter = request.getParameter("quarter");
            //       quarter="3";
            String getMonths = "SELECT months,name FROM quarter WHERE id='" + quarter + "'";
            conn.rs = conn.st.executeQuery(getMonths);
            if (conn.rs.next() == true) {

                String months[] = conn.rs.getString(1).split(",");
                startMonth = months[0];
                endMonth = months[2];
                if (quarter.equals("1")) {
                    duration = " " + form + ".yearmonth BETWEEN " + prevYear + "" + startMonth + " AND "
                            + prevYear + "" + endMonth;
                    yearmonth = prevYear + "_" + conn.rs.getString(2);
                } else {
                    yearmonth = year + "_" + conn.rs.getString(2);
                    duration = " " + form + ".yearmonth BETWEEN " + year + "" + startMonth + " AND " + year + ""
                            + endMonth;
                }
            }
        }

        else if (reportDuration.equals("4")) {
            monthcopy = Integer.parseInt(request.getParameter("month"));

            //     month=5;
            if (monthcopy >= 10) {
                yearmonth = prevYear + "_" + month;
                duration = " " + form + ".yearmonth=" + prevYear + "" + month;
            } else {
                duration = " " + form + ".yearmonth=" + year + "0" + month;
                yearmonth = year + "_(" + month + ")";
            }
        } else {
            duration = "";
        }

        //======================================================================   
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        String getexistingdata = "";

        if (!county.equals("")) {

            countywhere = " and countyid = '" + county + "'";

        }

        if (!facil.equals("") && reportType.equalsIgnoreCase("2")) {

            facilitywhere = " and " + form + ".SubPartnerID = '" + facil + "'";

        }

        //String joinedwhwere=" where 1=1 "+yearwhere+" && "+duration;  

        String joinedwhwere = " where 1=1 " + facilitywhere + "  " + yearwhere + " && " + duration;

        //=====================================================================================================    

        //=====================================================================================================    

        //=====================================================================================================    

        //______________________________________________________________________________________
        //                       NOW CREATE THE WORKSHEETS          
        //______________________________________________________________________________________  

        HSSFWorkbook wb = new HSSFWorkbook();

        //______________________________________________________________________________________
        //______________________________________________________________________________________

        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        stylex.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        fontx.setColor((short) 0000);
        fontx.setBoldweight((short) 07);
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        HSSFSheet shet = wb.createSheet(form);

        //create headers for that worksheet

        HSSFRow rw = shet.createRow(0);
        rw.setHeightInPoints(25);
        HSSFCell cl0 = rw.createCell(0);
        cl0.setCellValue("3.1.9: Nutrition");
        cl0.setCellStyle(stylex);

        for (int a = 1; a <= 6; a++) {
            HSSFCell clx = rw.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        HSSFRow rw1 = shet.createRow(1);
        rw1.setHeightInPoints(23);
        HSSFCell cl = rw1.createCell(0);
        cl.setCellValue(header);
        cl.setCellStyle(stylex);

        for (int a = 1; a <= 6; a++) {
            HSSFCell clx = rw1.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        HSSFRow rw2 = shet.createRow(2);
        rw2.setHeightInPoints(23);
        HSSFCell cl3 = rw2.createCell(0);
        cl3.setCellValue("3.1.9.2 Population Based Nutrition Service Delivery");
        cl3.setCellStyle(stylex);
        HSSFCell cl3a = rw2.createCell(1);
        cl3a.setCellValue("");
        cl3a.setCellStyle(stylex);
        HSSFCell cl31 = rw2.createCell(2);
        cl31.setCellValue(
                "Number of people trained in child health care and nutrition through USG-supported health area programs");
        cl31.setCellStyle(style2);

        for (int a = 3; a <= 5; a++) {
            HSSFCell clx = rw2.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(style2);
        }

        shet.addMergedRegion(new CellRangeAddress(2, 11, 0, 1));
        shet.addMergedRegion(new CellRangeAddress(2, 2, 2, 5));
        shet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
        shet.addMergedRegion(new CellRangeAddress(1, 1, 0, 6));
        shet.addMergedRegion(new CellRangeAddress(12, 20, 0, 0));

        shet.setColumnWidth(0, 3000);
        shet.setColumnWidth(1, 3000);
        shet.setColumnWidth(2, 16000);
        shet.setColumnWidth(3, 6900);
        shet.setColumnWidth(4, 3000);
        shet.setColumnWidth(5, 3000);

        getexistingdata = "select  sum(MCHCCNtrTM) as MCHCCNtrTM,    MCHCCNtrTMC,    sum(MCHCCNtrTF) as MCHCCNtrTF,    MCHCCNtrTFC,   sum(MCHCCNtrTT) as MCHCCNtrTT,    MCHCCNtrTTC,    sum(MCHNtrnCHWTrain) as MCHNtrnCHWTrain,   sum(MCHNutChRch) as MCHNutChRch,   sum(MCHNtrnWasted) as MCHNtrnWasted,   sum(MCHNtrnUnderweight) as MCHNtrnUnderweight,   sum(MCHChild5D) as MCHChild5D,   sum(MCHNtrnHealthFacility) as MCHNtrnHealthFacility,   sum(MCHVaccVitA) as MCHVaccVitA,   sum(MCHNtrnFoodOVC) as MCHNtrnFoodOVC,   sum(MCHNtrnFoodPLHIV) as MCHNtrnFoodPLHIV,   sum(MCHNtrnFood) as MCHNtrnFood,   sum(C51DCM) as C51DCM,   sum(C51DCF) as C51DCF,   sum(C51DC) as C51DC,    sum(C51DAM) as C51DAM,   sum(C51DAF) as C51DAF,   sum(C51DA) as C51DA,    sum(C51DP) as C51DP,    sum(C51DMT) as C51DMT,    sum(C51DFT) as C51DFT,    sum(C51DT) as C51DT  from "
                + form
                + " join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                + form + ".SubPartnerID = subpartnera.SubPartnerID   " + joinedwhwere + "  ";

        //System.out.println(getexistingdata);

        String MCHCCNtrTM = "";
        String MCHCCNtrTF = "";
        String MCHCCNtrTT = "";

        String MCHCCNtrTMC = "0";
        String MCHCCNtrTFC = "0";
        String MCHCCNtrTTC = "0";

        String MCHCCNtrTMCH = "0";
        String MCHCCNtrTFCH = "0";
        String MCHCCNtrTTCH = "0";

        String MCHNtrnCHWTrain = "";
        String MCHNutChRch = "";
        String MCHNtrnWasted = "";
        String MCHNtrnUnderweight = "";
        String MCHChild5D = "";
        String MCHNtrnHealthFacility = "";
        String MCHVaccVitA = "";
        String MCHNtrnFoodOVC = "";
        String MCHNtrnFoodPLHIV = "";
        String MCHNtrnFood = "";
        String C51DCM = "";
        String C51DCF = "";
        String C51DC = "";
        String C51DAM = "";
        String C51DAF = "";
        String C51DA = "";
        String C51DP = "";
        String C51DMT = "";
        String C51DFT = "";
        String C51DT = "";

        String distid = "";

        if (session.getAttribute("subcountyid") != null) {
            distid = session.getAttribute("subcountyid").toString();
        }

        int counter = 0;

        conn.rs = conn.st.executeQuery(getexistingdata);
        while (conn.rs.next()) {
            //now check if form was updated and if its one month after data entry
            //now load the column values here

            MCHCCNtrTM = conn.rs.getString("MCHCCNtrTM");
            if (MCHCCNtrTM == null) {
                MCHCCNtrTM = "";
            }

            MCHCCNtrTF = conn.rs.getString("MCHCCNtrTF");
            if (MCHCCNtrTF == null) {
                MCHCCNtrTF = "";
            }

            MCHCCNtrTT = conn.rs.getString("MCHCCNtrTT");
            if (MCHCCNtrTT == null) {
                MCHCCNtrTT = "";
            }

            MCHCCNtrTMC = conn.rs.getString("MCHCCNtrTMC");
            if (MCHCCNtrTMC == null) {
                MCHCCNtrTMC = "0";
            }

            MCHCCNtrTFC = conn.rs.getString("MCHCCNtrTFC");
            if (MCHCCNtrTFC == null) {
                MCHCCNtrTFC = "0";
            }

            MCHCCNtrTTC = conn.rs.getString("MCHCCNtrTTC");
            if (MCHCCNtrTTC == null) {
                MCHCCNtrTTC = "0";
            }

            MCHNtrnCHWTrain = conn.rs.getString("MCHNtrnCHWTrain");
            if (MCHNtrnCHWTrain == null) {
                MCHNtrnCHWTrain = "";
            }

            MCHNutChRch = conn.rs.getString("MCHNutChRch");
            if (MCHNutChRch == null) {
                MCHNutChRch = "";
            }

            MCHNtrnWasted = conn.rs.getString("MCHNtrnWasted");
            if (MCHNtrnWasted == null) {
                MCHNtrnWasted = "";
            }

            MCHNtrnUnderweight = conn.rs.getString("MCHNtrnUnderweight");
            if (MCHNtrnUnderweight == null) {
                MCHNtrnUnderweight = "";
            }

            MCHChild5D = conn.rs.getString("MCHChild5D");
            if (MCHChild5D == null) {
                MCHChild5D = "";
            }

            MCHNtrnHealthFacility = conn.rs.getString("MCHNtrnHealthFacility");
            if (MCHNtrnHealthFacility == null) {
                MCHNtrnHealthFacility = "";
            }

            MCHVaccVitA = conn.rs.getString("MCHVaccVitA");
            if (MCHVaccVitA == null) {
                MCHVaccVitA = "";
            }

            MCHNtrnFoodOVC = conn.rs.getString("MCHNtrnFoodOVC");
            if (MCHNtrnFoodOVC == null) {
                MCHNtrnFoodOVC = "";
            }

            MCHNtrnFoodPLHIV = conn.rs.getString("MCHNtrnFoodPLHIV");
            if (MCHNtrnFoodPLHIV == null) {
                MCHNtrnFoodPLHIV = "";
            }

            MCHNtrnFood = conn.rs.getString("MCHNtrnFood");
            if (MCHNtrnFood == null) {
                MCHNtrnFood = "";
            }

            C51DCM = conn.rs.getString("C51DCM");
            if (C51DCM == null) {
                C51DCM = "";
            }

            C51DCF = conn.rs.getString("C51DCF");
            if (C51DCF == null) {
                C51DCF = "";
            }

            C51DC = conn.rs.getString("C51DC");
            if (C51DC == null) {
                C51DC = "";
            }

            C51DAM = conn.rs.getString("C51DAM");
            if (C51DAM == null) {
                C51DAM = "";
            }

            C51DAF = conn.rs.getString("C51DAF");
            if (C51DAF == null) {
                C51DAF = "";
            }

            C51DA = conn.rs.getString("C51DA");
            if (C51DA == null) {
                C51DA = "";
            }

            C51DP = conn.rs.getString("C51DP");
            if (C51DP == null) {
                C51DP = "";
            }

            C51DMT = conn.rs.getString("C51DMT");
            if (C51DMT == null) {
                C51DMT = "";
            }

            C51DFT = conn.rs.getString("C51DFT");
            if (C51DFT == null) {
                C51DFT = "";
            }

            C51DT = conn.rs.getString("C51DT");
            if (C51DT == null) {
                C51DT = "";
            }

        }

        String createdtable = "";

        if (1 == 1) {

            int r = 3;

            HSSFCell cl3d = rw2.createCell(6);
            cl3d.setCellValue(MCHCCNtrTTC);
            cl3d.setCellStyle(style2);

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("Number of Men");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHCCNtrTM);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }

            //==================================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("Number of Women");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHCCNtrTF);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Total Number of people trained in child health care and nutrition through USG-supported health area programs");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHCCNtrTT);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }

            //============================================================================================   

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("Number of Community health workers trained in child health and/or nutrition");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHNtrnCHWTrain);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }

            //===========================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("Number of children reached by USG-supported nutrition programs");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHNutChRch);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }

            //===========================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Total number of children under five who are wasted (with weight for height Z score < - 2)");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHNtrnWasted);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Total number of children under five who are underweight (with weight for age Z score < - 2) (see Indicator");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHNtrnUnderweight);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }
            //===========================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("Total number of children under five years");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHChild5D);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }
            //===========================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Number of health facilities with established capacity to manage acute under-nutrition");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHNtrnHealthFacility);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));
                }
                r++;
            }
            //===========================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("HIV and Nutrition");
                clx0.setCellStyle(stylex);

                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("");
                clx1a.setCellStyle(stylex);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Number of children under 5 years of age who received Vitamin A from USG-supported programs");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHVaccVitA);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    //shet.addMergedRegion(new CellRangeAddress(2,11,0,0));
                }
                r++;
            }
            //===========================================================================================================

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(stylex);
                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("C2.3.D:");
                clx1a.setCellStyle(stylex);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Number of HIV  positive clinically malnourished clients who received therapeutic and/or supplementary food < 18");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHNtrnFoodOVC);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    shet.addMergedRegion(new CellRangeAddress(r, r + 2, 1, 1));
                }
                r++;
            }
            //===========================================================================================================    

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(stylex);
                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("");
                clx1a.setCellStyle(stylex);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Number of HIV  positive clinically malnourished clients who received therapeutic and/or supplementary food 18+ (PLHIV)");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHNtrnFoodPLHIV);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    // shet.addMergedRegion(new CellRangeAddress(r,r+3,1,1));
                }
                r++;
            }

            //=========================================================================================================== 

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(stylex);
                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("");
                clx1a.setCellStyle(stylex);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Number of HIV  positive clinically malnourished clients who received therapeutic and/or supplementary food - Total");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue(MCHNtrnFood);
                clx1.setCellStyle(style2);

                for (int a = 3; a <= 5; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    // shet.addMergedRegion(new CellRangeAddress(r,r+3,1,1));
                }
                r++;
            }
            //===========================================================================================================      
            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(stylex);
                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("");
                clx1a.setCellStyle(stylex);
                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("");
                clx.setCellStyle(style2);
                HSSFCell clx3 = rwx.createCell(3);
                clx3.setCellValue("");
                clx3.setCellStyle(style2);
                HSSFCell clx1 = rwx.createCell(6);
                clx1.setCellValue("");
                clx1.setCellStyle(style2);

                String haeade[] = { "Male", "Female", "Total" };

                for (int a = 4; a <= 6; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue(haeade[a - 4]);
                    clx2.setCellStyle(style2);
                    //shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    // shet.addMergedRegion(new CellRangeAddress(r,r+3,1,1));
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 2, 3));
                r++;
            }
            //=========================================================================================================== 
            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(stylex);
                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("C5.1.D:");
                clx1a.setCellStyle(stylex);

                HSSFCell clx1b = rwx.createCell(3);
                clx1b.setCellValue("< 18");
                clx1b.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue(
                        "Number of eligible clients who received food and / or other nutrition Services");
                clx.setCellStyle(style2);

                String haeade[] = { C51DCM, C51DCF, C51DC };

                for (int a = 0; a < haeade.length; a++) {
                    HSSFCell clx2 = rwx.createCell(a + 4);
                    clx2.setCellValue(haeade[a]);
                    clx2.setCellStyle(style2);
                    //shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    // shet.addMergedRegion(new CellRangeAddress(r,r+3,1,1));
                }
                //shet.addMergedRegion(new CellRangeAddress(r,r,2,3));       
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 1, 1));
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 2, 2));

                r++;
            }
            //===========================================================================================================    

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(stylex);
                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("");
                clx1a.setCellStyle(stylex);

                HSSFCell clx1b = rwx.createCell(3);
                clx1b.setCellValue(">=18");
                clx1b.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("");
                clx.setCellStyle(style2);

                String haeade[] = { C51DAM, C51DAF, C51DA };

                for (int a = 0; a < haeade.length; a++) {
                    HSSFCell clx2 = rwx.createCell(a + 4);
                    clx2.setCellValue(haeade[a]);
                    clx2.setCellStyle(style2);
                    //shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    // shet.addMergedRegion(new CellRangeAddress(r,r+3,1,1));
                }
                //shet.addMergedRegion(new CellRangeAddress(r,r,2,3));       

                r++;
            }
            //===========================================================================================================    

            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(stylex);
                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("");
                clx1a.setCellStyle(stylex);

                HSSFCell clx1b = rwx.createCell(3);
                clx1b.setCellValue("Pregnant/Lactating (PMTCT 1.5)");
                clx1b.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("");
                clx.setCellStyle(style2);

                String haeade[] = { "", "", C51DP };

                for (int a = 0; a < haeade.length; a++) {
                    HSSFCell clx2 = rwx.createCell(a + 4);
                    clx2.setCellValue(haeade[a]);
                    clx2.setCellStyle(style2);
                    //shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    // shet.addMergedRegion(new CellRangeAddress(r,r+3,1,1));
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 4, 5));

                r++;
            }
            //===========================================================================================================    
            if (1 == 1) {

                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(stylex);
                HSSFCell clx1a = rwx.createCell(1);
                clx1a.setCellValue("");
                clx1a.setCellStyle(stylex);

                HSSFCell clx1b = rwx.createCell(3);
                clx1b.setCellValue("Total");
                clx1b.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(2);
                clx.setCellValue("");
                clx.setCellStyle(style2);

                String haeade[] = { C51DMT, C51DFT, C51DT };

                for (int a = 0; a < haeade.length; a++) {
                    HSSFCell clx2 = rwx.createCell(a + 4);
                    clx2.setCellValue(haeade[a]);
                    clx2.setCellStyle(style2);
                    //shet.addMergedRegion(new CellRangeAddress(r, r, 2, 5));

                    // shet.addMergedRegion(new CellRangeAddress(r,r+3,1,1));
                }
                //shet.addMergedRegion(new CellRangeAddress(r,r,2,3));       

                r++;
            }
            //===========================================================================================================    

            createdtable += header
                    + "<br/><table   border='1' style='border-color: #e5e5e5;margin-bottom: 3px;font-size:11;'><tr class='form-actions'>"
                    + "<th rowspan='10' colspan='2'><b style='text-align:center;'>3.1.9.2 <br/> population-based Nutrition Service Delivery</b></th>"
                    + "<td colspan='4'><b>Number of People trained in child health care and nutrition through USG-supported health area programs</b></td><td><b>"
                    + MCHCCNtrTTC + "</b></td></tr>";
            createdtable += "<tr><td colspan='4' style='text-align:left;'>No of Men </td><td>" + MCHCCNtrTM
                    + "</td></tr>";
            createdtable += "<tr><td colspan='4' style='text-align:left;'>No of Women </td><td>" + MCHCCNtrTF
                    + "</td></tr>";
            createdtable += "<tr><td colspan='4'><b>Total Number of people trained in child health care and nutrition through USG-supported health area programs</b></td><td>"
                    + MCHCCNtrTT + "</td></tr>";
            createdtable += "<tr><td colspan='4'><b>Number of Community health workers trained in child health and/or nutrition</b></td><td>"
                    + MCHNtrnCHWTrain + "</td></tr>";
            createdtable += "<tr><td colspan='4'><b>Number of children reached by USG-supported nutrition programs</b></td><td>"
                    + MCHNutChRch + "</td></tr>";
            createdtable += "<tr><td colspan='4'>Total number of children under five who are wasted (with weight for height Z score < - 2)</td><td>"
                    + MCHNtrnWasted + "</td></tr>";
            createdtable += "<tr><td colspan='4'>Total number of children under five who are underweight (with weight for age Z score < - 2) (SEE Indicator </td><td>"
                    + MCHNtrnUnderweight + "</td></tr>";
            createdtable += "<tr><td colspan='4'>Total number of children under five years</td><td>"
                    + MCHChild5D + "</td></tr>";
            createdtable += "<tr><td colspan='4'>Number of health facilities with established capacity to manage acute under-nutrition</td><td>"
                    + MCHNtrnHealthFacility + "</td></tr>";

            createdtable += "<tr><td colspan='1' rowspan='9'>HIV and Nutrition</td><td></td> <td colspan='4'> <b> Number of children under 5 years of age who received Vitamin A from USG-supported programs </b> </td><td>"
                    + MCHVaccVitA + "</td></tr>";
            createdtable += "<tr><td rowspan='3' colspan='1'> <b> C2.3.D </b> </td> <td colspan='4'>Number of HIV  positive clinically malnourished clients who received therapeutic and/or supplementary food < 18 </td><td>"
                    + MCHNtrnFoodOVC + "</td></tr>";
            createdtable += "<tr><td colspan='4'>Number of HIV  positive clinically malnourished clients who received therapeutic and/or supplementary food 18+ (PLHIV)</td><td>"
                    + MCHNtrnFoodPLHIV + "</td></tr>";
            createdtable += "<tr><td colspan='4'>Number of HIV  positive clinically malnourished clients who received therapeutic and/or supplementary food -<b> Total</b></td><td>"
                    + MCHNtrnFood + "</td></tr>";

            createdtable += "<tr> <td></td><td></td><td></td><td><b>Male</b></td><td><b>Female</b></td><td><b>Total</b></td></tr>";
            createdtable += "<tr><td rowspan='4' colspan='1'> <b>C5.1.D </b> </td> <td colspan='1' rowspan='4'>Number of eligible clients who received food and / or other nutrition Services</td><td> <b> less Than 18 </b>  </td> <td>"
                    + C51DCM + "</td><td>" + C51DCF + "</td><td>" + C51DC + "</td></tr>";
            createdtable += "<tr><td> <b> >=18 </b> </td> <td>" + C51DAM + "</td><td>" + C51DAF + "</td><td>"
                    + C51DA + "</td></tr>";
            createdtable += "<tr><td colspan='3'> <b> Pregnant/Lactating (PMTCT 1.5)</b> </td><td>" + C51DP
                    + "</td></tr>";
            createdtable += "<tr><td> <b> Total </b>  </td> <td> " + C51DMT + " </td> <td> " + C51DFT
                    + " </td> <td> " + C51DT + " </td></tr></table>";

        }

        System.out.println(createdtable);

        if (conn.conn != null) {
            conn.conn.close();
        }
        if (conn.rs != null) {
            conn.rs.close();
        }
        if (conn.rs1 != null) {
            conn.rs1.close();
        }
        if (conn.rs2 != null) {
            conn.rs2.close();
        }
        if (conn.st != null) {
            conn.st.close();
        }
        if (conn.st2 != null) {
            conn.st2.close();
        }

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition",
                "attachment; filename=" + form + yearmonth + "_Generated_On_" + createdOn + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
        outStream.close();

    } catch (SQLException ex) {
        Logger.getLogger(Vmmcpdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:reports.reportsTracker731.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {

    dbConn conn = new dbConn();
    session = request.getSession();//from  w  ww  . j av  a 2  s .  c  om

    year = Integer.parseInt(request.getParameter("year"));
    //        year=2015;
    prevYear = year - 1;
    IdGenerator IG = new IdGenerator();
    allMonths.clear();
    allReports.clear();
    duration = "WHERE (moh731.yearmonth BETWEEN " + prevYear + "" + 10 + " AND " + year
            + "09) AND (subpartnera.PMTCT=1 OR subpartnera.ART=1 OR subpartnera.PEP=1 OR subpartnera.HTC=1)";

    currentMonth = IG.CurrentMonth();

    monthsData = "";
    //            ^^^^^^^^^^^^^CREATE STATIC AND WRITE STATIC DATA TO THE EXCELL^^^^^^^^^^^^
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet shet1 = wb.createSheet("MOH 731 REPORTS TRACKER");

    HSSFFont font = wb.createFont();
    font.setFontHeightInPoints((short) 18);
    font.setFontName("Arial Black");
    font.setColor((short) 0000);
    CellStyle style = wb.createCellStyle();
    style.setFont(font);
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    HSSFFont font2 = wb.createFont();
    font2.setFontName("Arial Black");
    font2.setColor((short) 0000);
    CellStyle style2 = wb.createCellStyle();
    style2.setFont(font2);

    HSSFCellStyle stborder = wb.createCellStyle();
    stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    stborder.setWrapText(true);

    HSSFCellStyle stylex = wb.createCellStyle();
    stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    HSSFFont fontx = wb.createFont();
    fontx.setColor(HSSFColor.DARK_BLUE.index);
    stylex.setFont(fontx);
    stylex.setWrapText(true);

    HSSFCellStyle styleHeader = wb.createCellStyle();
    styleHeader.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    styleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);
    styleHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    HSSFFont fontHeader = wb.createFont();
    fontHeader.setColor(HSSFColor.DARK_BLUE.index);
    styleHeader.setFont(fontHeader);
    styleHeader.setWrapText(true);

    for (int i = 0; i <= 2; i++) {
        shet1.setColumnWidth(i, 8000);
    }
    HSSFRow rw1S1 = shet1.createRow(0);
    HSSFCell S1cell = rw1S1.createCell(0);
    S1cell.setCellValue("COUNTY NAME");
    S1cell.setCellStyle(stylex);

    HSSFCell S1cellX = rw1S1.createCell(1);
    S1cellX.setCellValue("SUB COUNTY");
    S1cellX.setCellStyle(stylex);

    S1cellX = rw1S1.createCell(2);
    S1cellX.setCellValue("HEALTH FACILITY");
    S1cellX.setCellStyle(stylex);

    S1cellX = rw1S1.createCell(3);
    S1cellX.setCellValue("MFL CODE");
    S1cellX.setCellStyle(stylex);

    S1cellX = rw1S1.createCell(4);
    S1cellX.setCellValue("EXPECTED REPORTS");
    S1cellX.setCellStyle(stylex);

    counterHeader = 5;
    String getMaxandMin = "SELECT DISTINCT(month.name),month.id FROM moh731 JOIN month ON moh731.Mois=month.id JOIN subpartnera ON moh731.SubPartnerID=subpartnera.SubPartnerID "
            + duration + " " + " ORDER BY  moh731.yearmonth";
    conn.rs = conn.st.executeQuery(getMaxandMin);
    while (conn.rs.next()) {
        monthName = conn.rs.getString(1);
        monthid = conn.rs.getInt(2);
        if (monthid <= 9) {
            currentYear = year;
        } else {
            currentYear = prevYear;
        }
        System.out.println(" Months are : " + monthName);
        allMonths.add(monthName);
        allReports.add(0);
        S1cellX = rw1S1.createCell(counterHeader);
        S1cellX.setCellValue(monthName);
        S1cellX.setCellStyle(stylex);
        counterHeader++;
    }
    prevFacility = currentFacility = "";
    currentDistrict = prevDistrict = "";
    currentCounty = prevCounty = "";
    counter = districtCounter = countyCounter = districtsMerged = 0;
    arraySize = allReports.size();

    if (allMonths.size() > 0) {
        String checkReports = "SELECT county.County,district.DistrictNom,subpartnera.SubPartnerNom,"
                + "subpartnera.CentreSanteId,COUNT(moh731.SubPartnerID),month.name,subpartnera.SubPartnerID "
                + "FROM subpartnera " + "LEFT JOIN moh731 ON moh731.SubPartnerID=subpartnera.SubPartnerID "
                + "LEFT JOIN district ON subpartnera.DistrictID=district.DistrictID "
                + "LEFT JOIN county ON county.CountyID=district.CountyID "
                + "LEFT JOIN month ON moh731.Mois=month.id " + " " + duration + " "
                + " GROUP BY subpartnera.SubPartnerNom,moh731.Annee,moh731.Mois "
                + "ORDER BY county.County,district.DistrictNom,subpartnera.SubPartnerNom,moh731.Mois";
        System.out.println(checkReports);
        conn.rs = conn.st.executeQuery(checkReports);
        while (conn.rs.next()) {
            countyName = conn.rs.getString(1);
            districtName = conn.rs.getString(2);
            facilityName = conn.rs.getString(3);
            mflcode = conn.rs.getString(4);
            status = conn.rs.getInt(5);
            selectedMonth = conn.rs.getString(6);
            currentFacility = conn.rs.getString(7);
            currentDistrict = districtName;
            currentCounty = countyName;
            //     CHECK WHERE TO PLACE THE NUMBER; 

            monthPosition = allMonths.indexOf(selectedMonth);

            if (!prevFacility.equals(currentFacility)) {

                if (!prevDistrict.equals(currentDistrict) && !prevDistrict.equals("")) {
                    counter++;
                    noReports = districtCounter + 1;
                    HSSFRow rwTotal = shet1.createRow(counter);
                    HSSFCell SX = rwTotal.createCell(0);
                    SX.setCellStyle(stborder);

                    SX = rwTotal.createCell(1);
                    SX.setCellValue(prevDistrict + " TOTALS : ");
                    SX.setCellStyle(styleHeader);

                    SX = rwTotal.createCell(2);
                    SX.setCellStyle(styleHeader);

                    SX = rwTotal.createCell(3);
                    SX.setCellStyle(styleHeader);

                    SX = rwTotal.createCell(4);
                    SX.setCellValue(noReports);
                    SX.setCellStyle(styleHeader);
                    shet1.addMergedRegion(new CellRangeAddress(counter, counter, 1, 3));

                    for (int j = 0; j < allReports.size(); j++) {
                        //         System.out.println("district name : "+prevDistrict+" no of reports : "+allReports.get(j).toString()+" for month : "+allMonths.get(j).toString());
                        int dataPos = 5 + j;
                        SX = rwTotal.createCell(dataPos);
                        SX.setCellValue(Integer.parseInt(allReports.get(j).toString()));
                        SX.setCellStyle(styleHeader);
                    }
                    for (int k = 0; k < arraySize; k++) {
                        allReports.set(k, 0);
                    }
                }
                counter++;
                HSSFRow rw1 = shet1.createRow(counter);
                HSSFCell S1 = rw1.createCell(0);
                S1.setCellValue(countyName);
                S1.setCellStyle(stborder);

                S1 = rw1.createCell(1);
                S1.setCellValue(districtName);
                S1.setCellStyle(stborder);

                S1 = rw1.createCell(2);
                S1.setCellValue(facilityName);
                S1.setCellStyle(stborder);

                S1 = rw1.createCell(3);
                S1.setCellValue(mflcode);
                S1.setCellStyle(stborder);

                S1 = rw1.createCell(4);
                S1.setCellValue(1);
                S1.setCellStyle(stborder);

                for (int j = 0; j < allMonths.size(); j++) {
                    int cellPos = j + 5;
                    S1 = rw1.createCell(cellPos);
                    // System.out.println("counter : "+counter+" datapos : "+cellPos+" status : "+status);
                    S1.setCellStyle(stborder);

                }
                int dataPos = 5 + monthPosition;
                S1 = rw1.getCell(dataPos);
                S1.setCellValue(status);

                if (!prevDistrict.equals(currentDistrict) && !prevDistrict.equals("")) {
                    int distStart = counter - districtCounter - 2;
                    int distEnd = counter - 2;
                    shet1.addMergedRegion(new CellRangeAddress(distStart, distEnd, 1, 1));
                    districtsMerged++;
                    districtCounter = 0;

                    for (int j = 0; j < arraySize; j++) {
                        allReports.set(j, 0);
                    }

                } else {
                    if (counter == 1) {
                    } else {
                        districtCounter++;
                    }
                }
                if (!prevCounty.equals(currentCounty) && !prevCounty.equals("")) {
                    int countyStart = counter - countyCounter - districtsMerged - 1;
                    int countyEnd = counter - 1;
                    shet1.addMergedRegion(new CellRangeAddress(countyStart, countyEnd, 0, 0));
                    countyCounter = 0;
                    districtsMerged = 0;
                } else {
                    if (counter == 1) {
                    } else {
                        countyCounter++;
                    }
                }
                prevCounty = currentCounty;
                prevDistrict = currentDistrict;
            } else {

                HSSFRow rw1 = shet1.getRow(counter);
                int dataPos = 5 + monthPosition;
                HSSFCell S1 = rw1.getCell(dataPos);
                S1.setCellValue(status);
                //    
            }

            if (status == 1) {
                int currentData = Integer.parseInt(allReports.get(monthPosition).toString()) + 1;
                allReports.set(monthPosition, currentData);
            }

            prevFacility = currentFacility;

        }
        //    MATCH THE LAST DISTRICTS
        counter++;
        noReports = districtCounter + 1;
        HSSFRow rwTotal = shet1.createRow(counter);
        HSSFCell SX = rwTotal.createCell(0);
        SX.setCellStyle(stborder);

        SX = rwTotal.createCell(1);
        SX.setCellValue(prevDistrict + " TOTALS : ");
        SX.setCellStyle(styleHeader);

        SX = rwTotal.createCell(2);
        SX.setCellStyle(styleHeader);

        SX = rwTotal.createCell(3);
        SX.setCellStyle(styleHeader);

        SX = rwTotal.createCell(4);
        SX.setCellValue(noReports);
        SX.setCellStyle(styleHeader);
        shet1.addMergedRegion(new CellRangeAddress(counter, counter, 1, 3));

        int distStart = counter - districtCounter - 1;
        int distEnd = counter - 1;
        //     System.out.println("MERGE BETWEEN : START : "+distStart+" END : "+distEnd);
        shet1.addMergedRegion(new CellRangeAddress(distStart, distEnd, 1, 1));
        districtCounter = 0;

        int countyStart = counter - countyCounter - 2;
        int countyEnd = counter;
        //        System.out.println("MERGE BETWEEN : START : "+distStart+" END : "+distEnd);
        shet1.addMergedRegion(new CellRangeAddress(countyStart, countyEnd, 0, 0));
        countyCounter = 0;

        for (int j = 0; j < allReports.size(); j++) {
            //         System.out.println("district name : "+prevDistrict+" no of reports : "+allReports.get(j).toString()+" for month : "+allMonths.get(j).toString());
            int dataPos = 5 + j;
            SX = rwTotal.createCell(dataPos);
            SX.setCellValue(Integer.parseInt(allReports.get(j).toString()));
            SX.setCellStyle(styleHeader);
        }

        if (conn.st != null) {
            conn.st.close();
        }
        if (conn.st1 != null) {
            conn.st1.close();
        }
        if (conn.st2 != null) {
            conn.st2.close();
        }

        if (conn.rs != null) {
            conn.rs.close();
        }
        if (conn.rs1 != null) {
            conn.rs1.close();
        }
        if (conn.rs2 != null) {
            conn.rs2.close();
        }
        if (conn.conn != null) {
            conn.conn.close();
        }

        createdOn = IG.CreatedOn();

        // write it as an excel attachment
        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition", "attachment; filename=Reporting_summary_for_PEPFAR_YEAR("
                + year + ")_" + createdOn.trim() + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } else {

        session.setAttribute("noTrackerReport",
                "<font color=\"red\"><b>SORRY:</b> No report was found for " + year + ".</red>");
        response.sendRedirect("reportsTracker.jsp");
    }

}

From source file:reports.staticReportExcel731.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {

    dbConn conn = new dbConn();
    session = request.getSession();//  w  w w .  ja  v  a  2  s.  c  o  m

    //--------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------
    //added later to accomodate the years
    String subpartnerid = "SubPartnerID";
    String subpartnera = "subpartnera";

    int monthint = 0;
    int yearint = 0;

    reportType = request.getParameter("reportType");
    year = Integer.parseInt(request.getParameter("year"));
    reportDuration = request.getParameter("reportDuration");
    yearint = year;
    //        reportType="2";
    //        year=2015;
    //        reportDuration="3";

    prevYear = year - 1;
    maxYearMonth = 0;

    //        GET REPORT DURATION============================================
    startPMTCT = startART = startPEP = startHTC = noPMTCT = noART = noPEP = noHTC = 0;
    if (reportDuration.equals("1")) {

        //_________________________________annualy_____________________________________

        //solve subpartner table and facil_id first            
        if (yearint <= 2014) {
            subpartnerid = "SP_ID";
            subpartnera = "subpartnera2014";
        } else if (yearint > 2015) {
            subpartnerid = "SubPartnerID";
            subpartnera = "subpartnera";
        } else if (yearint == 2015) {
            //this should be skipped since it picks both facil tables. 
            //It has been disabled at the interface position
            subpartnerid = "SubPartnerID";
            subpartnera = "subpartnera";
        }

        duration = " moh731.yearmonth BETWEEN " + prevYear + "10 AND " + year + "09";
    } else if (reportDuration.equals("2")) {
        //_________________________________SemiAnnualy_________________________________

        //oct-mar
        //          if(quarter.equals("1")||quarter.equals("2")){
        //      if(yearint<=2014){
        //       subpartnerid="SP_ID";
        //       subpartnera="subpartnera2014";
        //       }
        //       else if(yearint>2015) {
        //        subpartnerid="SubPartnerID";
        //        subpartnera="subpartnera";
        //       }
        //      else if(yearint==2015){
        //         //for oct-mar, use old database list
        //    subpartnerid="SP_ID";
        //       subpartnera="subpartnera2014";  
        //         
        //      }
        //            
        //          }
        //          else if(quarter.equals("3")||quarter.equals("4")){
        //          //apr-sep
        //          
        //               //apr-sep
        //           
        //              if(yearint<=2014){
        //       subpartnerid="SP_ID";
        //       subpartnera="subpartnera2014";
        //       }
        //       else if(yearint>2015) {
        //        subpartnerid="SubPartnerID";
        //        subpartnera="subpartnera";
        //       }
        //      else if(yearint==2015){
        //        subpartnerid="SubPartnerID";
        //        subpartnera="subpartnera";      
        //         
        //      }
        //              
        //          }

        semi_annual = request.getParameter("semi_annual");
        //        semi_annual="2";
        if (semi_annual.equals("1")) {

            //oct-mar            
            if (yearint <= 2014) {
                subpartnerid = "SP_ID";
                subpartnera = "subpartnera2014";
            } else if (yearint > 2015) {
                subpartnerid = "SubPartnerID";
                subpartnera = "subpartnera";
            } else if (yearint == 2015) {
                //for oct-mar, use old database list
                subpartnerid = "SP_ID";
                subpartnera = "subpartnera2014";

            }

            duration = " moh731.yearmonth BETWEEN " + prevYear + "10 AND " + year + "03";
        } else {

            //apr-sep

            if (yearint <= 2014) {
                subpartnerid = "SP_ID";
                subpartnera = "subpartnera2014";
            } else if (yearint > 2015) {
                subpartnerid = "SubPartnerID";
                subpartnera = "subpartnera";
            } else if (yearint == 2015) {
                subpartnerid = "SubPartnerID";
                subpartnera = "subpartnera";

            }

            duration = " moh731.yearmonth BETWEEN " + year + "04 AND " + year + "09";
        }
    }

    else if (reportDuration.equals("3")) {
        //quarterly

        String startMonth, endMonth;

        //_________________________________Quarterly__________________________________

        quarter = request.getParameter("quarter");
        //specify subparter table and facil id first

        //oct-mar
        if (quarter.equals("1") || quarter.equals("2")) {
            if (yearint <= 2014) {
                subpartnerid = "SP_ID";
                subpartnera = "subpartnera2014";
            } else if (yearint > 2015) {
                subpartnerid = "SubPartnerID";
                subpartnera = "subpartnera";
            } else if (yearint == 2015) {
                //for oct-mar, use old database list
                subpartnerid = "SP_ID";
                subpartnera = "subpartnera2014";

            }

        } else if (quarter.equals("3") || quarter.equals("4")) {
            //apr-sep

            //apr-sep

            if (yearint <= 2014) {
                subpartnerid = "SP_ID";
                subpartnera = "subpartnera2014";
            } else if (yearint > 2015) {
                subpartnerid = "SubPartnerID";
                subpartnera = "subpartnera";
            } else if (yearint == 2015) {
                subpartnerid = "SubPartnerID";
                subpartnera = "subpartnera";

            }

        }

        //       quarter="3";
        String getMonths = "SELECT months FROM quarter WHERE id='" + quarter + "'";
        conn.rs = conn.st.executeQuery(getMonths);
        if (conn.rs.next() == true) {
            String months[] = conn.rs.getString(1).split(",");
            startMonth = months[0];
            endMonth = months[2];
            if (quarter.equals("1")) {
                duration = " moh731.yearmonth BETWEEN " + prevYear + "" + startMonth + " AND " + prevYear + ""
                        + endMonth;
            } else {
                duration = " moh731.yearmonth BETWEEN " + year + "" + startMonth + " AND " + year + ""
                        + endMonth;
            }
        }
    }

    else if (reportDuration.equals("4")) {

        //_____________________________monthly________________________________

        //__________________________monthly reports_________________________

        //deal with subpartnertable and facilid first

        monthint = month;

        if (yearint == 2015) {

            if (monthint == 10 || monthint == 11 || monthint == 12 || monthint == 1 || monthint == 2
                    || monthint == 3) {
                //here use a different subpartner id
                subpartnerid = "SP_ID";
                subpartnera = "subpartnera2014";
            } else {

                subpartnerid = "SubPartnerID";
                subpartnera = "subpartnera";

            }

        } else if (yearint <= 2014) {
            subpartnerid = "SP_ID";
            subpartnera = "subpartnera2014";
        } else if (yearint > 2015) {
            subpartnerid = "SubPartnerID";
            subpartnera = "subpartnera";
        }
        //---------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------

        month = Integer.parseInt(request.getParameter("month"));
        //     month=5;
        if (month >= 10) {
            duration = " moh731.yearmonth=" + prevYear + "" + month;
        } else {
            duration = " moh731.yearmonth=" + year + "0" + month;
        }
    } else {
        duration = "";
    }

    //     GET FACILITIES TO OUTPUT.................................
    mflcode = countyName = districtName = facilityName = "";

    if (reportType.equals("1")) {
        facility = "";

        facilityName = "ALL APHIA PLUS SUPPORTED HEALTH FACILITIES";
        districtName = "ALL";
        countyName = "ALL COUNTIES";
        mflcode = "NONE";
    }

    else {
        facilityId = request.getParameter("facility");

        String spid = "";

        //  facilityId="403";
        facility = "moh731.SubPartnerID='" + facilityId + "' &&";

        String getName = "SELECT subpartnera.SubPartnerNom,district.DistrictNom,county.County,subpartnera.CentreSanteId   , SP_ID FROM subpartnera "
                + "JOIN district ON subpartnera.DistrictID=district.DistrictID JOIN county ON "
                + "district.CountyID=county.CountyID WHERE subpartnera.SubPartnerID='" + facilityId + "'";
        conn.rs = conn.st.executeQuery(getName);

        if (conn.rs.next() == true) {
            facilityName = conn.rs.getString(1);
            districtName = conn.rs.getString(2);
            countyName = conn.rs.getString(3);
            mflcode = conn.rs.getString(4);

            spid = conn.rs.getString(5);

        }

        if (subpartnerid.equalsIgnoreCase("SP_ID")) {

            facility = "moh731.SubPartnerID='" + spid + "' &&";

        }

    }

    header += "</table>";

    String getMaxYearMonth = "SELECT MAX(yearmonth) FROM moh731 WHERE " + facility + " " + duration;
    conn.rs = conn.st.executeQuery(getMaxYearMonth);
    if (conn.rs.next() == true) {
        maxYearMonth = conn.rs.getInt(1);
    }
    System.out.println("max year month : " + maxYearMonth);

    //            ^^^^^^^^^^^^^CREATE STATIC AND WRITE STATIC DATA TO THE EXCELL^^^^^^^^^^^^
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet shet4 = wb.createSheet("HTC");
    HSSFSheet shet1 = wb.createSheet("PMTCT");
    HSSFSheet shet2 = wb.createSheet("Care and Treatment");
    HSSFSheet shet3 = wb.createSheet("PEP");

    HSSFFont font = wb.createFont();
    font.setFontHeightInPoints((short) 18);
    font.setFontName("Cambria");
    font.setColor((short) 0000);
    CellStyle style = wb.createCellStyle();
    style.setFont(font);
    style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
    HSSFFont font2 = wb.createFont();
    font2.setFontName("Arial Black");
    font2.setColor((short) 0000);
    CellStyle style2 = wb.createCellStyle();
    style2.setFont(font2);

    HSSFCellStyle stborder = wb.createCellStyle();
    stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stborder.setAlignment(HSSFCellStyle.ALIGN_LEFT);
    stborder.setWrapText(true);

    HSSFCellStyle stylex = wb.createCellStyle();
    stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stylex.setAlignment(HSSFCellStyle.ALIGN_LEFT);

    HSSFFont fontx = wb.createFont();
    fontx.setColor(HSSFColor.DARK_BLUE.index);
    stylex.setFont(fontx);
    stylex.setWrapText(true);

    HSSFCellStyle styleHeader = wb.createCellStyle();
    styleHeader.setFillForegroundColor(HSSFColor.LIME.index);
    styleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);
    styleHeader.setAlignment(HSSFCellStyle.ALIGN_LEFT);

    HSSFFont fontHeader = wb.createFont();
    fontHeader.setColor(HSSFColor.DARK_BLUE.index);
    styleHeader.setFont(fontHeader);
    styleHeader.setWrapText(true);

    for (int i = 0; i <= 1; i++) {
        shet1.setColumnWidth(i, 14000);
    }

    for (int i = 0; i <= 1; i++) {
        shet2.setColumnWidth(i, 14000);
    }

    for (int i = 0; i <= 1; i++) {
        shet3.setColumnWidth(i, 14000);
    }
    for (int i = 0; i <= 1; i++) {
        shet4.setColumnWidth(i, 14000);
    }

    shet1.setColumnWidth(2, 4000);
    shet2.setColumnWidth(2, 4000);
    shet3.setColumnWidth(2, 4000);
    shet4.setColumnWidth(2, 4000);

    String headers = "COUNTY,SUB COUNTY,FACILITY NAME,MFL CODE";

    String arrayHeader[] = headers.split(",");
    int headerno = 0;
    int valueNo = 0;
    int arrayCounter = 0;

    //   XSSFRow rw0S1=shet1.createRow(0);
    HSSFRow rw1S1 = shet1.createRow(0);

    //    XSSFRow rw0S2=shet2.createRow(0);
    HSSFRow rw1S2 = shet2.createRow(0);

    //    XSSFRow rw0S3=shet3.createRow(0);
    HSSFRow rw1S3 = shet3.createRow(0);

    HSSFRow rw1S4 = shet4.createRow(0);

    String getMonth = "SELECT name FROM month WHERE id='" + month + "'";
    conn.rs = conn.st.executeQuery(getMonth);
    if (conn.rs.next() == true) {
        monthName = conn.rs.getString(1);
    }

    counterPMTCT = counterART = counterPEP = 3;

    //   START OUTPUTTING THE RESULTS=================================================   

    System.out.println("facility : " + facility + "   duration : " + duration);

    prevSection = currentSection = "";
    secCounter = 0;

    String checker = "SELECT "
            + "SUM(HV0101),SUM(HV0102),SUM(HV0103),SUM(HV0105),SUM(HV0106),SUM(HV0107),SUM(HV0108),SUM(HV0109),SUM(HV0110),SUM(HV0111),SUM(HV0112),SUM(HV0113),SUM(HV0114),"
            + "SUM(HV0115),SUM(HV0116),"
            + "SUM(HV0201),SUM(HV0202),SUM(HV0203),SUM(HV0204),SUM(HV0205),SUM(HV0206),SUM(HV0207),SUM(HV0208),SUM(HV0209),SUM(HV0210),SUM(HV0211),SUM(HV0212),SUM(HV0213),"
            + "SUM(HV0214),SUM(HV0215),SUM(HV0216),SUM(HV0217),SUM(HV0218),SUM(HV0219),SUM(HV0220),SUM(HV0221),SUM(HV0224),SUM(HV0225),SUM(HV0226),SUM(HV0227),SUM(HV0228),SUM(HV0229),"
            + "SUM(HV0230),SUM(HV0231),SUM(HV0232),SUM(HV0233),SUM(HV0234),SUM(HV0235),SUM(HV0236),SUM(HV0237),SUM(HV0238),SUM(HV0239),SUM(HV0240),SUM(HV0241),SUM(HV0242),"
            + "SUM(HV0243),SUM(HV0244),"
            + "SUM(HV0301),SUM(HV0302),SUM(HV0303),SUM(HV0304),SUM(HV0305),SUM(HV0306),SUM(HV0307),SUM(HV0308),SUM(HV0309),SUM(HV0310),SUM(HV0311),SUM(HV0312),SUM(HV0313),SUM(HV0314),"
            + "SUM(HV0315),SUM(HV0316),SUM(HV0317),SUM(HV0318),SUM(HV0319),SUM(HV0320),SUM(HV0321),SUM(HV0322),SUM(HV0323),SUM(HV0324),SUM(HV0325),SUM(HV0326),SUM(HV0327),SUM(HV0328),"
            + "SUM(HV0329),SUM(HV0330),SUM(HV0331),SUM(HV0332),SUM(HV0333),SUM(HV0334),SUM(HV0335),SUM(HV0336),SUM(HV0337),SUM(HV0338),SUM(HV0339),SUM(HV0340),SUM(HV0341),"
            + "SUM(HV0342),SUM(HV0343),SUM(HV0344),SUM(HV0345),SUM(HV0346),SUM(HV0347),SUM(HV0348),SUM(HV0349),SUM(HV0350),SUM(HV0351),SUM(HV0352),SUM(HV0353),"
            + "SUM(HV0354),SUM(HV0355),SUM(HV0904),SUM(HV0905),SUM(HV0370),SUM(HV0371),SUM(HV0372),SUM(HV0373),"
            + "SUM(HV0401),SUM(HV0402),SUM(HV0403),SUM(HV0406),SUM(HV0407),SUM(HV0408),SUM(HV0409),SUM(HV0410),SUM(HV0411),SUM(HV0412),SUM(HV0413),SUM(HV0414),SUM(HV0415),"
            + "SUM(HV0501),SUM(HV0502),SUM(HV0503),SUM(HV0504),SUM(HV0505),SUM(HV0506),SUM(HV0507),SUM(HV0508),SUM(HV0509),SUM(HV0510),SUM(HV0511),SUM(HV0512),SUM(HV0513),SUM(HV0514),"
            + "SUM(HV0101),SUM(HV0102),SUM(HV0103),SUM(HV0105),SUM(HV0106),SUM(HV0107),SUM(HV0108),SUM(HV0109),SUM(HV0110),SUM(HV0111),SUM(HV0112),SUM(HV0113),SUM(HV0114),SUM(HV0115),SUM(HV0116),"
            + //added later
            "SUM(HV0601),SUM(HV0602),SUM(HV0605)," + subpartnera + ".PMTCT, " + subpartnera + ".ART,"
            + subpartnera + ".PEP, " + subpartnera + ".HTC " + "FROM moh731 JOIN " + subpartnera
            + " ON moh731.SubPartnerID=" + subpartnera + "." + subpartnerid + " WHERE " + facility + " "
            + duration;

    System.out.println("@@@  " + checker);
    conn.rs = conn.st.executeQuery(checker);
    if (conn.rs.next() == true) {

        isPMTCT = conn.rs.getInt(subpartnera + ".PMTCT");
        isART = conn.rs.getInt(subpartnera + ".ART");
        isPEP = conn.rs.getInt(subpartnera + ".PEP");
        isHTC = conn.rs.getInt(subpartnera + ".HTC");

        String headerValues = countyName + "," + districtName + "," + facilityName + "," + mflcode;
        String arrayValues[] = headerValues.split(",");
        String headerValue = "";
        pos = 0;
        //   CREATE HEADERS
        for (String headername : arrayHeader) {
            headerValue = arrayValues[arrayCounter];

            HSSFRow rw1S10 = shet1.createRow(pos);
            HSSFRow rw1S20 = shet2.createRow(pos);
            HSSFRow rw1S30 = shet3.createRow(pos);
            HSSFRow rw1S40 = shet4.createRow(pos);

            HSSFCell S1cell = rw1S10.createCell(0);
            S1cell.setCellValue(headername);
            S1cell.setCellStyle(stylex);

            HSSFCell S1cellX = rw1S10.createCell(1);
            S1cellX.setCellValue(headerValue);
            S1cellX.setCellStyle(stylex);

            S1cellX = rw1S10.createCell(2);
            S1cellX.setCellValue("");
            S1cellX.setCellStyle(stylex);

            S1cellX = rw1S10.createCell(3);
            S1cellX.setCellValue("");
            S1cellX.setCellStyle(stylex);

            HSSFCell S2cell = rw1S20.createCell(0);
            S2cell.setCellValue(headername);
            S2cell.setCellStyle(stylex);

            HSSFCell S2cellX = rw1S20.createCell(1);
            S2cellX.setCellValue(headerValue);
            S2cellX.setCellStyle(stylex);

            S2cellX = rw1S20.createCell(2);
            S2cellX.setCellValue("");
            S2cellX.setCellStyle(stylex);

            S2cellX = rw1S20.createCell(3);
            S2cellX.setCellValue("");
            S2cellX.setCellStyle(stylex);

            HSSFCell S3cell = rw1S30.createCell(0);
            S3cell.setCellValue(headername);
            S3cell.setCellStyle(stylex);

            HSSFCell S3cellX = rw1S30.createCell(1);
            S3cellX.setCellValue(headerValue);
            S3cellX.setCellStyle(stylex);

            S3cellX = rw1S30.createCell(2);
            S3cellX.setCellValue("");
            S3cellX.setCellStyle(stylex);

            S3cellX = rw1S30.createCell(3);
            S3cellX.setCellValue("");
            S3cellX.setCellStyle(stylex);

            //_______________________________

            HSSFCell S4cell = rw1S40.createCell(0);
            S4cell.setCellValue(headername);
            S4cell.setCellStyle(stylex);

            HSSFCell S4cellX = rw1S40.createCell(1);
            S4cellX.setCellValue(headerValue);
            S4cellX.setCellStyle(stylex);

            S4cellX = rw1S40.createCell(2);
            S4cellX.setCellValue("");
            S4cellX.setCellStyle(stylex);

            S4cellX = rw1S40.createCell(3);
            S4cellX.setCellValue("");
            S4cellX.setCellStyle(stylex);

            arrayCounter++;
            pos++;
        }

        //     pos+=1;
        //  OUTPUT ELEMENT HEADING

        HSSFRow rw1S10 = shet1.createRow(pos);
        HSSFRow rw1S20 = shet2.createRow(pos);
        HSSFRow rw1S30 = shet3.createRow(pos);
        HSSFRow rw1S40 = shet4.createRow(pos);

        rw1S10.setHeightInPoints(25);
        rw1S20.setHeightInPoints(25);
        rw1S30.setHeightInPoints(25);
        rw1S40.setHeightInPoints(25);

        HSSFCell S1cell = rw1S10.createCell(0);
        S1cell.setCellValue("SUB SECTION");
        S1cell.setCellStyle(styleHeader);

        HSSFCell S1cellX = rw1S10.createCell(1);
        S1cellX.setCellValue("ELEMENT TITLE");
        S1cellX.setCellStyle(styleHeader);

        HSSFCell S1cellX2 = rw1S10.createCell(2);
        S1cellX2.setCellValue("LABEL");
        S1cellX2.setCellStyle(styleHeader);

        S1cellX2 = rw1S10.createCell(3);
        S1cellX2.setCellValue("VALUE");
        S1cellX2.setCellStyle(styleHeader);

        HSSFCell S2cell = rw1S20.createCell(0);
        S2cell.setCellValue("SUB SECTION");
        S2cell.setCellStyle(styleHeader);

        HSSFCell S2cellX = rw1S20.createCell(1);
        S2cellX.setCellValue("ELEMENT TITLE");
        S2cellX.setCellStyle(styleHeader);

        HSSFCell S2cellX2 = rw1S20.createCell(2);
        S2cellX2.setCellValue("LABEL");
        S2cellX2.setCellStyle(styleHeader);

        S2cellX2 = rw1S20.createCell(3);
        S2cellX2.setCellValue("VALUE");
        S2cellX2.setCellStyle(styleHeader);

        HSSFCell S3cell = rw1S30.createCell(0);
        S3cell.setCellValue("SUB SECTION");
        S3cell.setCellStyle(styleHeader);

        HSSFCell S3cellX = rw1S30.createCell(1);
        S3cellX.setCellValue("ELEMENT TITLE");
        S3cellX.setCellStyle(styleHeader);

        HSSFCell S3cellX2 = rw1S30.createCell(2);
        S3cellX2.setCellValue("LABEL");
        S3cellX2.setCellStyle(styleHeader);

        S3cellX2 = rw1S30.createCell(3);
        S3cellX2.setCellValue("VALUE");
        S3cellX2.setCellStyle(styleHeader);

        //--------------------htc
        HSSFCell S4cell = rw1S40.createCell(0);
        S4cell.setCellValue("SUB SECTION");
        S4cell.setCellStyle(styleHeader);

        HSSFCell S4cellX = rw1S40.createCell(1);
        S4cellX.setCellValue("ELEMENT TITLE");
        S4cellX.setCellStyle(styleHeader);

        HSSFCell S4cellX2 = rw1S40.createCell(2);
        S4cellX2.setCellValue("LABEL");
        S4cellX2.setCellStyle(styleHeader);

        S4cellX2 = rw1S40.createCell(3);
        S4cellX2.setCellValue("VALUE");
        S4cellX2.setCellStyle(styleHeader);

        elementCounter = 1;
        valueCounter = 1;
        specialElement = 0;
        String getCummulatives = "SELECT "
                //              + "SUM(HV0301),SUM(HV0302),"
                + "SUM(HV0303),SUM(HV0304),SUM(HV0305),SUM(HV0306),SUM(HV0307),"
                + "SUM(HV0314),SUM(HV0315),SUM(HV0316),SUM(HV0317),SUM(HV0318),SUM(HV0319),"
                + "SUM(HV0328),SUM(HV0329),SUM(HV0330),SUM(HV0331),SUM(HV0332),SUM(HV0333),SUM(HV0334),SUM(HV0335),"
                + "SUM(HV0336),SUM(HV0337),SUM(HV0338),SUM(HV0339),SUM(HV0340),SUM(HV0341),SUM(HV0342),SUM(HV0343),SUM(HV0344), "
                + "SUM(HV0350),SUM(HV0351),SUM(HV0352),SUM(HV0353),SUM(HV0354),SUM(HV0355) "
                + "FROM moh731 join subpartnera on moh731.subpartnerid=subpartnera.subpartnerid WHERE "
                + facility + " art=1 && yearmonth=" + maxYearMonth;
        conn.rs2 = conn.st2.executeQuery(getCummulatives);
        if (conn.rs2.next() == true) {
            System.out.println("entered to get cumulatives : " + maxYearMonth);

            int j = 5;
            int i = 5;
            int k = 5;
            int l = 5;
            String getElements = "SELECT subsection,shortlabel,label FROM pivottable WHERE form='moh731' ORDER BY tableid";
            conn.rs1 = conn.st1.executeQuery(getElements);
            while (conn.rs1.next()) {
                //     subsection,shortlabel,label;  
                subsection = conn.rs1.getString(1);
                shortlabel = conn.rs1.getString(2);
                label = conn.rs1.getString(3);

                elementCounter++;
                valueCounter = elementCounter + 4;
                //pmtct
                if (elementCounter >= 17 && elementCounter <= 58) {
                    if (isPMTCT == 1 && j <= 47) {
                        int valuePos = j + 15 - 4;
                        HSSFRow rw1S11 = shet1.createRow(j);
                        HSSFCell S1cell1 = rw1S11.createCell(0);
                        S1cell1.setCellValue(subsection);
                        S1cell1.setCellStyle(stborder);

                        HSSFCell S1cellX1 = rw1S11.createCell(1);
                        S1cellX1.setCellValue(shortlabel);
                        S1cellX1.setCellStyle(stborder);

                        HSSFCell S1cellX21 = rw1S11.createCell(2);
                        S1cellX21.setCellValue(label);
                        S1cellX21.setCellStyle(stborder);

                        S1cellX21 = rw1S11.createCell(3);
                        S1cellX21.setCellValue(conn.rs.getInt(valuePos));
                        S1cellX21.setCellStyle(stborder);

                        currentSection = subsection;

                        if (prevSection.equals(currentSection) && !prevSection.equals("")) {
                            secCounter++;
                            //    System.out.println("THey are equal  :"+prevSection+" current sec:   "+currentSection);
                        } else if (j == 5) {
                            prevSection = currentSection = subsection;
                            //secCounter++;         
                            //     System.out.println("entered j=5 :"+j+"  :"+prevSection+" current sec:  "+currentSection);
                        }

                        else if (!prevSection.equals(currentSection)) {
                            int startMerger = j - secCounter - 1;
                            int endMerger = j - 1;
                            shet1.addMergedRegion(new CellRangeAddress(startMerger, endMerger, 0, 0));
                            secCounter = 0;
                            //    System.out.println("merged cells from :"+startMerger+" to :"+endMerger);

                        }

                        else {
                            System.out.println("cant think anymore");
                        }
                        prevSection = currentSection;

                        j++;
                        //          System.out.println("j values : "+j);
                        if (j == 47) {
                            System.out.println("entered end here j " + j);
                            int startMerger = j - secCounter - 1;
                            int endMerger = j - 1;
                            shet1.addMergedRegion(new CellRangeAddress(startMerger, endMerger, 0, 0));
                            secCounter = 0;
                            prevSection = currentSection = "";
                        }
                    }

                }
                //art
                if (elementCounter >= 59 && elementCounter <= 119) {
                    if (isART == 1 && i <= 66) {
                        int valuePos = i + 57 - 4;
                        HSSFRow rw1S11 = shet2.createRow(i);
                        HSSFCell S1cell1 = rw1S11.createCell(0);
                        S1cell1.setCellValue(subsection);
                        S1cell1.setCellStyle(stborder);

                        HSSFCell S1cellX1 = rw1S11.createCell(1);
                        S1cellX1.setCellValue(shortlabel);
                        S1cellX1.setCellStyle(stborder);

                        HSSFCell S1cellX21 = rw1S11.createCell(2);
                        S1cellX21.setCellValue(label);
                        S1cellX21.setCellStyle(stborder);

                        if (elementCounter >= 61 && elementCounter <= 65) {
                            specialElement++;
                            //        System.out.println("entered on cumus for ctx>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            //        System.out.println("Value is >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+conn.rs2.getInt(specialElement));
                            S1cellX21 = rw1S11.createCell(3);
                            S1cellX21.setCellValue(conn.rs2.getInt(specialElement));
                            //    S1cellX21.setCellValue("");
                            S1cellX21.setCellStyle(stborder);

                        }

                        else if (elementCounter >= 72 && elementCounter <= 77) {
                            specialElement++;
                            S1cellX21 = rw1S11.createCell(3);
                            S1cellX21.setCellValue(conn.rs2.getInt(specialElement));
                            S1cellX21.setCellStyle(stborder);

                        }

                        else if (elementCounter >= 86 && elementCounter <= 91) {
                            specialElement++;
                            S1cellX21 = rw1S11.createCell(3);
                            S1cellX21.setCellValue(conn.rs2.getInt(specialElement));
                            S1cellX21.setCellStyle(stborder);

                        }

                        else if (elementCounter >= 92 && elementCounter <= 102) {
                            specialElement++;
                            S1cellX21 = rw1S11.createCell(3);
                            S1cellX21.setCellValue(conn.rs2.getInt(specialElement));
                            S1cellX21.setCellStyle(stborder);
                        } else if (elementCounter >= 108 && elementCounter <= 113) {
                            specialElement++;
                            S1cellX21 = rw1S11.createCell(3);
                            S1cellX21.setCellValue(conn.rs2.getInt(specialElement));
                            S1cellX21.setCellStyle(stborder);
                        } else {
                            S1cellX21 = rw1S11.createCell(3);
                            S1cellX21.setCellValue(conn.rs.getInt(valuePos));
                            S1cellX21.setCellStyle(stborder);
                        }

                        currentSection = subsection;

                        if (prevSection.equals(currentSection) && !prevSection.equals("")) {
                            secCounter++;
                            //    System.out.println("THey are equal  :"+prevSection+" current sec:   "+currentSection);
                        } else if (i == 5) {
                            prevSection = currentSection = subsection;
                            //secCounter++;         
                            //    System.out.println("entered j=5 :"+i+"  :"+prevSection+" current sec:  "+currentSection);
                        }

                        else if (!prevSection.equals(currentSection)) {
                            int startMerger = i - secCounter - 1;
                            int endMerger = i - 1;
                            shet2.addMergedRegion(new CellRangeAddress(startMerger, endMerger, 0, 0));
                            secCounter = 0;
                            //    System.out.println("merged cells from :"+startMerger+" to :"+endMerger);

                        }

                        else {
                            //         System.out.println("cant think anymore");
                        }
                        prevSection = currentSection;

                        i++;

                        if (i == 66) {
                            //       System.out.println("entered end here i "+i);
                            int startMerger = i - secCounter - 1;
                            int endMerger = i - 1;
                            shet2.addMergedRegion(new CellRangeAddress(startMerger, endMerger, 0, 0));
                            secCounter = 0;
                            prevSection = currentSection = "";
                        }

                    }
                }
                //PEP
                if (elementCounter >= 133 && elementCounter <= 146) {
                    if (isPEP == 1 && k <= 18) {
                        int valuePos = k + 131 - 4;
                        System.out.println("k values : " + k);
                        HSSFRow rw1S11 = shet3.createRow(k);
                        HSSFCell S1cell1 = rw1S11.createCell(0);
                        S1cell1.setCellValue(subsection);
                        S1cell1.setCellStyle(stborder);

                        HSSFCell S1cellX1 = rw1S11.createCell(1);
                        S1cellX1.setCellValue(shortlabel);
                        S1cellX1.setCellStyle(stborder);

                        HSSFCell S1cellX21 = rw1S11.createCell(2);
                        S1cellX21.setCellValue(label);
                        S1cellX21.setCellStyle(stborder);

                        S1cellX21 = rw1S11.createCell(3);
                        S1cellX21.setCellValue(conn.rs.getInt(valuePos));
                        S1cellX21.setCellStyle(stborder);

                        currentSection = subsection;

                        if (prevSection.equals(currentSection) && !prevSection.equals("")) {
                            secCounter++;
                        } else if (k == 5) {
                            prevSection = currentSection = subsection;
                        }

                        else if (!prevSection.equals(currentSection)) {
                            int startMerger = k - secCounter - 1;
                            int endMerger = k - 1;
                            if (startMerger == endMerger) {
                            } else {
                                shet3.addMergedRegion(new CellRangeAddress(startMerger, endMerger, 0, 0));
                            }
                            secCounter = 0;
                            System.out.println("merged cells from :" + startMerger + " to :" + endMerger);

                        }

                        else {
                            System.out.println("cant think anymore");
                        }
                        prevSection = currentSection;

                        k++;

                        if (k == 18) {
                            int startMerger = k - secCounter - 1;
                            int endMerger = k;
                            shet3.addMergedRegion(new CellRangeAddress(startMerger, endMerger, 0, 0));
                            secCounter = 0;
                            prevSection = currentSection = "";
                        }

                    }

                }

                //==========================HTC===============================  

                if (elementCounter <= 16) {
                    if (isHTC == 1 && l <= 19) {
                        int valuePos = l - 4;
                        System.out.println("l values : " + l);
                        HSSFRow rw1S11 = shet4.createRow(l);
                        HSSFCell S1cell1 = rw1S11.createCell(0);
                        S1cell1.setCellValue(subsection);
                        S1cell1.setCellStyle(stborder);

                        HSSFCell S1cellX1 = rw1S11.createCell(1);
                        S1cellX1.setCellValue(shortlabel);
                        S1cellX1.setCellStyle(stborder);

                        HSSFCell S1cellX21 = rw1S11.createCell(2);
                        S1cellX21.setCellValue(label);
                        S1cellX21.setCellStyle(stborder);

                        S1cellX21 = rw1S11.createCell(3);
                        S1cellX21.setCellValue(conn.rs.getInt(valuePos));
                        S1cellX21.setCellStyle(stborder);

                        currentSection = subsection;

                        if (prevSection.equals(currentSection) && !prevSection.equals("")) {
                            secCounter++;
                        } else if (l == 5) {
                            prevSection = currentSection = subsection;
                        }

                        else if (!prevSection.equals(currentSection)) {
                            int startMerger = l - secCounter - 1;
                            int endMerger = l - 1;
                            if (startMerger == endMerger) {
                            } else {
                                shet4.addMergedRegion(new CellRangeAddress(startMerger, endMerger, 0, 0));
                            }
                            secCounter = 0;
                            System.out.println("merged cells from :" + startMerger + " to :" + endMerger);

                        }

                        else {
                            System.out.println("cant think anymore");
                        }
                        prevSection = currentSection;

                        l++;

                        if (l == 19) {
                            int startMerger = l - secCounter - 1;
                            int endMerger = l;
                            shet4.addMergedRegion(new CellRangeAddress(startMerger, endMerger, 0, 0));
                            secCounter = 0;
                            prevSection = currentSection = "";
                        }

                    }

                }

            }
        }
        System.out.println("Data already exist loading............................");

        counter++;
    }

    System.out.println("Validity checker : " + isValidated);

    if (conn.st != null) {
        conn.st.close();
    }
    if (conn.st1 != null) {
        conn.st1.close();
    }
    if (conn.st2 != null) {
        conn.st2.close();
    }

    if (conn.rs != null) {
        conn.rs.close();
    }
    if (conn.rs1 != null) {
        conn.rs1.close();
    }
    if (conn.rs2 != null) {
        conn.rs2.close();
    }
    if (conn.conn != null) {
        conn.conn.close();
    }

    IdGenerator IG = new IdGenerator();
    createdOn = IG.CreatedOn();

    // write it as an excel attachment
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
    wb.write(outByteStream);
    byte[] outArray = outByteStream.toByteArray();
    response.setContentType("application/ms-excel");
    response.setContentLength(outArray.length);
    response.setHeader("Expires:", "0"); // eliminates browser caching
    response.setHeader("Content-Disposition",
            "attachment; filename=MOH731_STATIC_REPORT_CREATED_" + createdOn.trim() + ".xls");
    OutputStream outStream = response.getOutputStream();
    outStream.write(outArray);
    outStream.flush();

}

From source file:reports.verificationreports.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    session = request.getSession();/*ww w  .  j  a  v a  2s  . c  o m*/
    dbConn conn = new dbConn();
    allFacilities.clear();
    year = Integer.parseInt(request.getParameter("year"));
    reportDuration = request.getParameter("reportDuration");

    String headerART[] = "County,Sub County,Health Facility,MFL Code,Type of support,Numerator,<1,1-4Y,5-14Y,15-19Y,20+Y,<1,1-4Y,5-14Y,15-19Y,20+Y,Numerator,<1,1-4Y,5-9Y,10-14Y,15-19Y,20-24Y,25-49Y,50+Y,<1,1-4Y,5-9Y,10-14Y,15-19Y,20-24Y,25-49Y,50+Y"
            .split(",");
    String headerCARE[] = "County,Sub County,Health Facility,MFL Code,Type of support,Numerator,<1,1-4Y,5-9Y,10-14Y,15-19Y,20-24Y,25-49Y,50+Y,<1,1-4Y,5-9Y,10-14Y,15-19Y,20-24Y,25-49Y,50+Y,NUMERATOR,<1,1-4Y,5-9Y,10-14Y,15-19Y,20-24Y,25-49Y,50+Y,<1,1-4Y,5-9Y,10-14Y,15-19Y,20-24Y,25-49Y,50+Y"
            .split(",");
    String headerPMTCT[] = "County,Sub County,Health Facility,MFL Code,Type of support,Numerator,Denominator,HIV-infected:Linked to ART,HIV-infected: Not linked to ART,HIV-infected : Unknown link,HIV-uninfected:Not beastfeeding,HIV-uninfected: Still breastfeeeding,HIV-uninfected:Breastfeeding unknown,Other outcomes: In care but not test done, Other outcomes:Lost to follow up,Other outcomes : Died,Other outcomes:Transferred out,Numerator,Denominator,Life-long ART:New,Life-long ART: Already on treatment at the beginning of the current pregnancy,Maternal Triple-Drug ARV,Maternal AZT,Single-dose nevirapine(with or without tail),Numerator,Infants who received a virologic test within 2 months of birth, Infants who received their first virologic HIV test between 2 and 12 months of age,Infants with a postive virologic test results within 2 months of birth, Infants with a postive virologic test resultsbetween 2 and 12 months of age,Numerator,Known postive at entry,New postives,Denominator,Numerator "
            .split(",");

    //        year=2015;
    //        reportDuration="4";
    String facilityIds1 = "";

    period = "";
    prevYear = year - 1;
    maxYearMonth = 0;
    facilityIds = "(";
    facilityIds1 = "(";
    artpos = carepos = pmtctpos = 0;
    //        GET REPORT DURATION============================================

    if (reportDuration.equals("1")) {
        duration = " moh731.yearmonth BETWEEN " + prevYear + "10 AND " + year + "09";
        period = "DATIM ANNUAL DATA REPORT FOR PEPFAR YEAR : " + year;
    } else if (reportDuration.equals("2")) {
        semi_annual = request.getParameter("semi_annual");
        //        semi_annual="2";
        if (semi_annual.equals("1")) {
            duration = " moh731.yearmonth BETWEEN " + prevYear + "10 AND " + year + "03";

            period = "DATIM SEMI - ANNUAL DATA REPORT FOR : OCT " + prevYear + " to MARCH " + year;
        } else {
            duration = " moh731.yearmonth BETWEEN " + year + "04 AND " + year + "09";
            period = "DATIM SEMI - ANNUAL DATA REPORT FOR : APRIL " + year + " to SEPT " + year;
        }
    }

    else if (reportDuration.equals("3")) {
        String startMonth, endMonth;
        quarter = request.getParameter("quarter");
        //       quarter="3";
        String getMonths = "SELECT months,name FROM quarter WHERE id='" + quarter + "'";
        conn.rs = conn.st.executeQuery(getMonths);
        if (conn.rs.next() == true) {
            String months[] = conn.rs.getString(1).split(",");
            startMonth = months[0];
            endMonth = months[2];
            if (quarter.equals("1")) {
                duration = " moh731.yearmonth BETWEEN " + prevYear + "" + startMonth + " AND " + prevYear + ""
                        + endMonth;
                period = "DATIM QUARTERLY DATA REPORT FOR : "
                        + conn.rs.getString(2).replace("-", " " + prevYear + " TO ") + " " + prevYear + "";
            } else {
                duration = " moh731.yearmonth BETWEEN " + year + "" + startMonth + " AND " + year + ""
                        + endMonth;
                period = "DATIM QUARTERLY DATA REPORT FOR : "
                        + conn.rs.getString(2).replace("-", " " + year + " TO ") + " " + year + "";
            }
        }
    }

    else if (reportDuration.equals("4")) {
        month = Integer.parseInt(request.getParameter("month"));
        //            month=5;
        String getMonthName = "SELECT name FROM month WHERE id='" + month + "'";
        conn.rs = conn.st.executeQuery(getMonthName);
        if (conn.rs.next() == true) {
            if (month >= 10) {
                duration = " moh731.yearmonth=" + prevYear + "" + month;
                period = "DATIM MONTHLY DATA REPORT FOR : " + conn.rs.getString(1) + "(" + prevYear + ")";
            } else {
                duration = " moh731.yearmonth=" + year + "0" + month;
                period = "DATIM MONTHLY DATA REPORT FOR : " + conn.rs.getString(1) + "(" + year + ")";
            }
        }
    } else {
        duration = "";
    }

    if (request.getParameter("subcounty") != null && !request.getParameter("subcounty").equals("")) {
        String subcounty = request.getParameter("subcounty");
        String getDist = "SELECT subpartnera.SubPartnerID FROM subpartnera "
                + "JOIN district ON subpartnera.DistrictID=district.DistrictID " + "WHERE district.DistrictID='"
                + subcounty + "'";
        conn.rs = conn.st.executeQuery(getDist);
        while (conn.rs.next()) {
            allFacilities.add(conn.rs.getString(1));
            facilityIds += " moh731.SubPartnerID='" + conn.rs.getString(1) + "' || ";
            facilityIds1 += " moh711.SubPartnerID='" + conn.rs.getString(1) + "' || ";
        }
        facilityIds = facilityIds.substring(0, facilityIds.length() - 3);
        facilityIds += ") && ";
        facilityIds1 = facilityIds1.substring(0, facilityIds1.length() - 3);
        facilityIds1 += ") && ";
    } else {
        if (request.getParameter("county") != null && !request.getParameter("county").equals("")) {
            String county = request.getParameter("county");
            String getCounty = "SELECT subpartnera.SubPartnerID FROM subpartnera "
                    + "JOIN district ON subpartnera.DistrictID=district.DistrictID "
                    + "JOIN county ON district.CountyID=county.CountyID WHERE county.CountyID='" + county + "'";
            conn.rs = conn.st.executeQuery(getCounty);
            while (conn.rs.next()) {
                allFacilities.add(conn.rs.getString(1));
                facilityIds += " moh731.SubPartnerID='" + conn.rs.getString(1) + "' || ";
                facilityIds1 += " moh711.SubPartnerID='" + conn.rs.getString(1) + "' || ";
            }
            facilityIds = facilityIds.substring(0, facilityIds.length() - 3);
            facilityIds += ") && ";
            facilityIds1 = facilityIds1.substring(0, facilityIds1.length() - 3);
            facilityIds1 += ") && ";
        }

        else {
            facilityIds = "";
            facilityIds1 = "";
        }

    }
    System.out.println("period is : " + period);

    //     GET FACILITIES TO OUTPUT.................................
    mflcode = countyName = districtName = facilityName = "";

    //  facilityId=request.getParameter("facility");
    //  facilityIds="403";

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet shet1 = wb.createSheet("ART");
    HSSFSheet shet2 = wb.createSheet("CARE");
    HSSFSheet shet3 = wb.createSheet("HTC ");
    HSSFSheet shetPMTCT = wb.createSheet("PMTCT");
    HSSFFont font = wb.createFont();
    font.setFontHeightInPoints((short) 18);
    font.setFontName("Arial Black");
    font.setColor((short) 0000);
    CellStyle style = wb.createCellStyle();
    style.setFont(font);
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    HSSFFont font2 = wb.createFont();
    font2.setFontName("Arial Black");
    font2.setColor((short) 0000);
    CellStyle style2 = wb.createCellStyle();
    style2.setFont(font2);

    HSSFCellStyle stborder = wb.createCellStyle();
    stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    stborder.setWrapText(true);

    // for the red color
    HSSFCellStyle redstyle = wb.createCellStyle();
    redstyle.setFillForegroundColor(HSSFColor.RED.index);
    redstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    redstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
    redstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    redstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    redstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
    redstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    redstyle.setWrapText(true);

    //    HSSFCellStyle stylex = wb.createCellStyle();
    //stylex.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
    //stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    //   stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
    //    stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    //    stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    //    stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
    //    stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    //    
    //HSSFFont fontx = wb.createFont();
    //fontx.setColor(HSSFColor.DARK_BLUE.index);
    //stylex.setFont(fontx);
    //stylex.setWrapText(true);

    //   HSSFCellStyle stylemainHeader = wb.createCellStyle();
    //stylemainHeader.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
    //stylemainHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    //   stylemainHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);
    //    stylemainHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    //    stylemainHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    //    stylemainHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);
    //    stylemainHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    //    stylemainHeader.setWrapText(true);

    HSSFCellStyle styleHeader = wb.createCellStyle();
    styleHeader.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    styleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    styleHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);
    styleHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    styleHeader.setWrapText(true);

    HSSFCellStyle styleminiHeader = wb.createCellStyle();
    styleminiHeader.setFillForegroundColor(HSSFColor.ORCHID.index);
    styleminiHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleminiHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);
    styleminiHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    styleminiHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    styleminiHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);
    styleminiHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    styleminiHeader.setWrapText(true);

    HSSFFont fontHeader = wb.createFont();
    fontHeader.setColor(HSSFColor.DARK_BLUE.index);
    styleHeader.setFont(fontHeader);
    styleHeader.setWrapText(true);

    for (int i = 3; i <= headerPMTCT.length; i++) {
        shetPMTCT.setColumnWidth(i, 4000);
    }
    for (int i = 0; i <= 1; i++) {
        shetPMTCT.setColumnWidth(i, 5000);
    }
    shetPMTCT.setColumnWidth(2, 8000);

    for (int i = 5; i <= 16; i++) {
        shetPMTCT.setColumnWidth(i, 4000);
    }

    for (int i = 3; i <= 33; i++) {
        shet1.setColumnWidth(i, 2000);
    }
    for (int i = 0; i <= 1; i++) {
        shet1.setColumnWidth(i, 5000);
    }
    shet1.setColumnWidth(2, 8000);

    for (int i = 3; i <= 33; i++) {
        shet2.setColumnWidth(i, 2000);
    }

    // for sheet3
    for (int i = 3; i <= 42; i++) {
        shet3.setColumnWidth(i, 2000);
    }
    for (int i = 0; i <= 1; i++) {
        shet2.setColumnWidth(i, 5000);
    }
    for (int i = 0; i <= 1; i++) {
        shet3.setColumnWidth(i, 5000);
    }
    shet2.setColumnWidth(2, 8000);

    shet1.setColumnWidth(5, 3500);
    shet1.setColumnWidth(16, 3500);

    shet2.setColumnWidth(5, 3500);
    shet2.setColumnWidth(22, 3500);

    shet3.setColumnWidth(7, 3500);
    shet3.setColumnWidth(25, 3500);

    //  ART AND CARE HEADERS============================================================================================

    HSSFRow rw00shet1 = shet1.createRow(1);
    rw00shet1.setHeightInPoints(30);

    HSSFRow rw00shet2 = shet2.createRow(1);
    rw00shet2.setHeightInPoints(30);

    HSSFCell c011;

    for (int j = 0; j < headerART.length; j++) {
        c011 = rw00shet1.createCell(j);
        c011.setCellStyle(styleHeader);
    }

    for (int j = 0; j < headerCARE.length; j++) {
        c011 = rw00shet2.createCell(j);
        c011.setCellStyle(styleHeader);
    }

    c011 = rw00shet1.getCell(0);
    c011.setCellValue(period);

    c011 = rw00shet1.getCell(5);
    c011.setCellValue("CURRENT ON ART");

    c011 = rw00shet1.getCell(16);
    c011.setCellValue("NEW ON ART");
    shet1.addMergedRegion(new CellRangeAddress(1, 1, 5, 15));
    shet1.addMergedRegion(new CellRangeAddress(1, 1, 16, 32));

    c011 = rw00shet2.getCell(0);
    c011.setCellValue(period);

    c011 = rw00shet2.getCell(5);
    c011.setCellValue("CURRENTLY ON CARE");

    c011 = rw00shet2.getCell(22);
    c011.setCellValue("NEW ON CARE");
    shet2.addMergedRegion(new CellRangeAddress(1, 1, 5, 21));
    shet2.addMergedRegion(new CellRangeAddress(1, 1, 22, 38));

    HSSFRow rw0shet1 = shet1.createRow(2);
    rw0shet1.setHeightInPoints(30);

    HSSFRow rw0shet2 = shet2.createRow(2);
    rw0shet2.setHeightInPoints(30);

    HSSFCell c001;

    for (int j = 0; j < headerART.length; j++) {
        c001 = rw0shet1.createCell(j);
        c001.setCellStyle(styleHeader);
    }

    for (int j = 0; j < headerCARE.length; j++) {
        c001 = rw0shet2.createCell(j);
        c001.setCellStyle(styleHeader);
    }

    c001 = rw0shet1.getCell(5);
    c001.setCellValue("NUMERATOR");

    c001 = rw0shet1.getCell(16);
    c001.setCellValue("NUMERATOR");

    c001 = rw0shet1.getCell(6);
    c001.setCellValue("FEMALE");

    c001 = rw0shet1.getCell(11);
    c001.setCellValue("MALE");

    c001 = rw0shet1.getCell(17);
    c001.setCellValue("FEMALE");

    c001 = rw0shet1.getCell(25);
    c001.setCellValue("MALE");

    shet1.addMergedRegion(new CellRangeAddress(2, 2, 6, 10));
    shet1.addMergedRegion(new CellRangeAddress(2, 2, 11, 15));
    shet1.addMergedRegion(new CellRangeAddress(2, 2, 17, 24));
    shet1.addMergedRegion(new CellRangeAddress(2, 2, 25, 32));

    c001 = rw0shet2.getCell(5);
    c001.setCellValue("NUMERATOR");

    c001 = rw0shet2.getCell(22);
    c001.setCellValue("NUMERATOR");

    c001 = rw0shet2.getCell(6);
    c001.setCellValue("FEMALE");

    c001 = rw0shet2.getCell(14);
    c001.setCellValue("MALE");

    c001 = rw0shet2.getCell(23);
    c001.setCellValue("FEMALE");

    c001 = rw0shet2.getCell(31);
    c001.setCellValue("MALE");

    shet2.addMergedRegion(new CellRangeAddress(2, 2, 6, 13));
    shet2.addMergedRegion(new CellRangeAddress(2, 2, 14, 21));
    shet2.addMergedRegion(new CellRangeAddress(2, 2, 23, 30));
    shet2.addMergedRegion(new CellRangeAddress(2, 2, 31, 38));

    //ROW 3 FOR PAEDS STARTS HERE  
    HSSFRow rw1shet1 = shet1.createRow(3);
    rw1shet1.setHeightInPoints(30);

    HSSFRow rw1shet2 = shet2.createRow(3);
    rw1shet2.setHeightInPoints(30);

    HSSFCell c01;

    for (int j = 0; j < headerART.length; j++) {
        c01 = rw1shet1.createCell(j);
        c01.setCellStyle(styleHeader);
    }

    for (int j = 0; j < headerCARE.length; j++) {
        c01 = rw1shet2.createCell(j);
        c01.setCellStyle(styleHeader);
    }
    c01 = rw1shet1.getCell(6);
    c01.setCellValue("Paeds <15yrs");

    c01 = rw1shet1.getCell(9);
    c01.setCellValue("Adults 15+ Yr");

    c01 = rw1shet1.getCell(11);
    c01.setCellValue("Paeds <15yrs");

    c01 = rw1shet1.getCell(14);
    c01.setCellValue("Adults 15+ Yr");

    c01 = rw1shet1.getCell(17);
    c01.setCellValue("Paeds <15yrs");

    c01 = rw1shet1.getCell(21);
    c01.setCellValue("Adults 15+ Yr");

    c01 = rw1shet1.getCell(25);
    c01.setCellValue("Paeds <15yrs");

    c01 = rw1shet1.getCell(29);
    c01.setCellValue("Adults 15+ Yr");

    shet1.addMergedRegion(new CellRangeAddress(3, 3, 6, 8));
    shet1.addMergedRegion(new CellRangeAddress(3, 3, 9, 10));
    shet1.addMergedRegion(new CellRangeAddress(3, 3, 11, 13));
    shet1.addMergedRegion(new CellRangeAddress(3, 3, 14, 15));
    shet1.addMergedRegion(new CellRangeAddress(3, 3, 17, 20));
    shet1.addMergedRegion(new CellRangeAddress(3, 3, 21, 24));
    shet1.addMergedRegion(new CellRangeAddress(3, 3, 25, 28));
    shet1.addMergedRegion(new CellRangeAddress(3, 3, 29, 32));

    c01 = rw1shet2.getCell(6);
    c01.setCellValue("Paeds <15yrs");

    c01 = rw1shet2.getCell(10);
    c01.setCellValue("Adults 15+ Yr");

    c01 = rw1shet2.getCell(14);
    c01.setCellValue("Paeds <15yrs");

    c01 = rw1shet2.getCell(18);
    c01.setCellValue("Adults 15+ Yr");

    c01 = rw1shet2.getCell(23);
    c01.setCellValue("Paeds <15yrs");

    c01 = rw1shet2.getCell(27);
    c01.setCellValue("Adults 15+ Yr");

    c01 = rw1shet2.getCell(31);
    c01.setCellValue("Paeds <15yrs");

    c01 = rw1shet2.getCell(35);
    c01.setCellValue("Adults 15+ Yr");

    shet2.addMergedRegion(new CellRangeAddress(3, 3, 6, 9));
    shet2.addMergedRegion(new CellRangeAddress(3, 3, 10, 13));
    shet2.addMergedRegion(new CellRangeAddress(3, 3, 14, 17));
    shet2.addMergedRegion(new CellRangeAddress(3, 3, 18, 21));
    shet2.addMergedRegion(new CellRangeAddress(3, 3, 23, 26));
    shet2.addMergedRegion(new CellRangeAddress(3, 3, 27, 30));
    shet2.addMergedRegion(new CellRangeAddress(3, 3, 31, 34));
    shet2.addMergedRegion(new CellRangeAddress(3, 3, 35, 38));

    shet1.addMergedRegion(new CellRangeAddress(1, 3, 0, 4));
    shet2.addMergedRegion(new CellRangeAddress(1, 3, 0, 4));

    HSSFRow rw2shet1 = shet1.createRow(4);
    rw2shet1.setHeightInPoints(30);

    HSSFRow rw2shet2 = shet2.createRow(4);
    rw2shet2.setHeightInPoints(30);

    HSSFCell c11;
    for (int headerpos = 0; headerpos < headerART.length; headerpos++) {
        String headerInfor = headerART[headerpos];
        c11 = rw2shet1.createCell(headerpos);
        c11.setCellValue(headerInfor);
        c11.setCellStyle(styleHeader);
    }
    System.out.println("art header length : " + headerART.length);

    for (int headerpos = 0; headerpos < headerCARE.length; headerpos++) {
        String headerInfor = headerCARE[headerpos];
        c11 = rw2shet2.createCell(headerpos);
        c11.setCellValue(headerInfor);
        c11.setCellStyle(styleHeader);
    }

    shet1.addMergedRegion(new CellRangeAddress(2, 4, 5, 5));
    shet2.addMergedRegion(new CellRangeAddress(2, 4, 5, 5));
    shet1.addMergedRegion(new CellRangeAddress(2, 4, 16, 16));
    shet2.addMergedRegion(new CellRangeAddress(2, 4, 22, 22));

    //    PMTCT HEADER=====================================================================================

    HSSFRow rw0shetPMTCT = shetPMTCT.createRow(1);
    rw0shetPMTCT.setHeightInPoints(30);

    for (int j = 0; j < headerPMTCT.length; j++) {
        c001 = rw0shetPMTCT.createCell(j);
        c001.setCellStyle(styleHeader);
    }
    c001 = rw0shetPMTCT.getCell(0);
    c001.setCellValue(period);

    c001 = rw0shetPMTCT.getCell(5);
    c001.setCellValue("PMTCT_FO");

    c001 = rw0shetPMTCT.getCell(17);
    c001.setCellValue("PMTCT_ARV");

    c001 = rw0shetPMTCT.getCell(24);
    c001.setCellValue("PMTCT_EID");

    c001 = rw0shetPMTCT.getCell(29);
    c001.setCellValue("PMTCT_STAT (Numerator)");

    c001 = rw0shetPMTCT.getCell(32);
    c001.setCellValue("PMTCT_STAT (Denominator)");

    c001 = rw0shetPMTCT.getCell(33);
    c001.setCellValue("PMTCT_CTX");

    shetPMTCT.addMergedRegion(new CellRangeAddress(1, 1, 0, 4));
    shetPMTCT.addMergedRegion(new CellRangeAddress(1, 1, 5, 16));
    shetPMTCT.addMergedRegion(new CellRangeAddress(1, 1, 17, 23));
    shetPMTCT.addMergedRegion(new CellRangeAddress(1, 1, 24, 28));
    shetPMTCT.addMergedRegion(new CellRangeAddress(1, 1, 29, 31));
    //  shetPMTCT.addMergedRegion(new CellRangeAddress(2,2,25,32)); 

    HSSFRow rw2shetPMTCT = shetPMTCT.createRow(2);
    rw2shetPMTCT.setHeightInPoints(50);

    for (int headerpos = 0; headerpos < headerPMTCT.length; headerpos++) {
        String headerInfor = headerPMTCT[headerpos];
        c11 = rw2shetPMTCT.createCell(headerpos);
        c11.setCellValue(headerInfor);
        c11.setCellStyle(styleHeader);
    }
    System.out.println("art header length : " + headerPMTCT.length);

    artpos = 4;
    pmtctpos = 3;
    totalNewART = totalCurrentART = totalNewCARE = totalCurrentCARE = 0;

    //    String getData="SELECT subpartnera.SubPartnerNom,district.DistrictNom,county.County,"
    //            + "subpartnera.CentreSanteId,ART_Support,PMTCT_Support,"
    //            + "SUM(HV0308),SUM(HV0309),SUM(HV0310),SUM(HV0311),SUM(HV0312),"
    //    + "SUM(HV0320),SUM(HV0321),SUM(HV0322),SUM(HV0323),SUM(HV0324),"
    //            + "subpartnera.SubPartnerID FROM moh731 JOIN subpartnera "
    //            + "ON moh731.SubPartnerID=subpartnera.SubPartnerID "
    //            + "JOIN district ON subpartnera.DistrictID=district.DistrictID JOIN county ON "
    //          + "district.CountyID=county.CountyID"
    //            + " WHERE "
    //    + " "+facilityIds+" "+duration+" && (subpartnera.PMTCT=1 || ART=1) "
    //            + "GROUP BY moh731.SubPartnerID " ;

    String getData = "SELECT subpartnera.SubPartnerNom,district.DistrictNom,county.County,"
            + "subpartnera.CentreSanteId,ART_Support,PMTCT_Support,"
            + "SUM(HV0308),SUM(HV0309),SUM(HV0310),SUM(HV0311),SUM(HV0312),"
            + "SUM(HV0320),SUM(HV0321),SUM(HV0322),SUM(HV0323),SUM(HV0324)," + "subpartnera.SubPartnerID,"
            + "SUM(HV0205),SUM(HV0209),SUM(HV0210),SUM(HV0216),SUM(HV0217),"
            + "SUM(HV0224),SUM(HV0225),SUM(HV0227),SUM(HV0229),SUM(HV0230),SUM(HV0231),SUM(HV0232),"
            + "SUM(HV0301),SUM(HV0206),SUM(HV0207),SUM(HV0208) " + " FROM moh731 JOIN subpartnera "
            + "ON moh731.SubPartnerID=subpartnera.SubPartnerID "
            + "JOIN district ON subpartnera.DistrictID=district.DistrictID JOIN county ON "
            + "district.CountyID=county.CountyID" + " WHERE " + " " + facilityIds + " " + duration
            + " && (subpartnera.PMTCT=1 || ART=1) " + "GROUP BY moh731.SubPartnerID ";

    System.out.println("new : " + getData);
    conn.rs = conn.st.executeQuery(getData);
    while (conn.rs.next()) {
        HV0308 = HV0309 = HV0310 = HV0311 = HV0312 = HV0320 = HV0321 = HV0322 = HV0323 = HV0324 = 0;
        HV0314 = HV0315 = HV0316 = HV0317 = HV0318 = HV0334 = HV0335 = HV0336 = HV0337 = HV0338 = 0;
        currentART1M = currentART1_4M = currentART5_14M = currentART15_19M = currentART20M = 0;
        currentART1F = currentART1_4F = currentART5_14F = currentART15_19F = currentART20F = 0;
        newART1M = newART1_4M = newART5_9M = newART10_14M = newART15_19M = newART20_24M = newART25_49M = newART50M = 0;
        newART1F = newART1_4F = newART5_9F = newART10_14F = newART15_19F = newART20_24F = newART25_49F = newART50F = 0;
        newCARE1M = newCARE1_4M = newCARE5_9M = newCARE10_14M = newCARE15_19M = newCARE20_24M = newCARE25_49M = newCARE50M = 0;
        newCARE1F = newCARE1_4F = newCARE5_9F = newCARE10_14F = newCARE15_19F = newCARE20_24F = newCARE25_49F = newCARE50F = 0;
        currentCARE1M = currentCARE1_4M = currentCARE5_9M = currentCARE10_14M = currentCARE15_19M = currentCARE20_24M = currentCARE25_49M = currentCARE50M = 0;
        currentCARE1F = currentCARE1_4F = currentCARE5_9F = currentCARE10_14F = currentCARE15_19F = currentCARE20_24F = currentCARE25_49F = currentCARE50F = 0;

        PMTCT_FO_I_N = PMTCT_FO_I_D = PMTCT_FO_I_LINKED = PMTCT_FO_I_NOT_LINKED = PMTCT_FO_I_UNKNOWN = PMTCT_FO_U_NOT_BREASTFEEDING = PMTCT_FO_U_STILL_BREASTFEEDING = PMTCT_FO_U_BREASTFEEDING_UNKNOWN = PMTCT_FO_OTHER_INCARE = PMTCT_FO_OTHER_NOFOLLOWUP = PMTCT_FO_DIED = PMTCT_FO_TRANSFERRED = 0.0;
        PMTCT_ARV_N = PMTCT_ARV_D = PMTCT_ARV_LIFELONGART_NEW = PMTCT_ARV_LIFELONGART_EXISTING = PMTCT_ARV_MATERNAL_TRIPLEDRUG_ARV = PMTCT_ARV_MATERNAL_AZT = PMTCT_ARV_SINGLEDOSE = 0.0;
        PMTCT_EID_N = PMTCT_EID_VIRO_2MONTHS = PMTCT_EID_VIRO_2_12MONTHS = PMTCT_EID_P_VIRO_2MONTHS = PMTCT_EID_P_VIRO_2_12MONTHS = 0.0;
        PMTCT_STATN_N = PMTCT_STATN_KNOWNPOSTIVE = PMTCTN_STAT_NEWPOSTIVE = 0.0;
        PMTCT_STATD_D = PMTCT_STATD_LESS15 = PMTCT_STATD_15_19 = PMTCT_STATD_20_24 = PMTCT_STATD_25 = 0.0;
        PMTCT_CTX = 0.0;
        facilityName = conn.rs.getString(1);
        districtName = conn.rs.getString(2);
        countyName = conn.rs.getString(3);
        mflcode = conn.rs.getString(4);
        ARTSupport = conn.rs.getString(5);
        //      CARESuport=conn.rs.getString(6);
        PMTCTSupport = conn.rs.getString(6);
        HV0308 = conn.rs.getInt(7);
        HV0309 = conn.rs.getInt(8);
        HV0310 = conn.rs.getInt(9);
        HV0311 = conn.rs.getInt(10);
        HV0312 = conn.rs.getInt(11);
        HV0320 = conn.rs.getInt(12);
        HV0321 = conn.rs.getInt(13);
        HV0322 = conn.rs.getInt(14);
        HV0323 = conn.rs.getInt(15);
        HV0324 = conn.rs.getInt(16);
        facilityId = conn.rs.getString(17);

        HV0205 = conn.rs.getInt(18);
        HV0209 = conn.rs.getInt(19);
        HV0210 = conn.rs.getInt(20);
        HV0216 = conn.rs.getInt(21);
        HV0217 = conn.rs.getInt(22);
        HV0224 = conn.rs.getInt(23);
        HV0225 = conn.rs.getInt(24);
        HV0227 = conn.rs.getInt(25);
        HV0229 = conn.rs.getInt(26);
        HV0230 = conn.rs.getInt(27);
        HV0231 = conn.rs.getInt(28);
        HV0232 = conn.rs.getInt(29);
        //        HV0301=conn.rs.getInt(30);
        HV0206 = conn.rs.getInt(31);
        HV0207 = conn.rs.getInt(32);
        HV0208 = conn.rs.getInt(33);

        String getMaxYearMonth = "SELECT MAX(yearmonth) FROM moh731 WHERE moh731.SubPartnerID='" + facilityId
                + "' && " + duration;
        conn.rs2 = conn.st2.executeQuery(getMaxYearMonth);
        if (conn.rs2.next() == true) {
            maxYearMonth = conn.rs2.getInt(1);
        }

        String getCurrent = "SELECT HV0314,HV0315,HV0316,HV0317,HV0318,"
                + "HV0334,HV0335,HV0336,HV0337,HV0338,HV0301 FROM moh731 WHERE " + "moh731.SubPartnerID='"
                + facilityId + "' && yearmonth='" + maxYearMonth + "'";
        System.out.println("current : " + getCurrent);
        conn.rs1 = conn.st1.executeQuery(getCurrent);
        if (conn.rs1.next() == true) {
            HV0314 = conn.rs1.getInt(1);
            HV0315 = conn.rs1.getInt(2);
            HV0316 = conn.rs1.getInt(3);
            HV0317 = conn.rs1.getInt(4);
            HV0318 = conn.rs1.getInt(5);
            HV0334 = conn.rs1.getInt(6);
            HV0335 = conn.rs1.getInt(7);
            HV0336 = conn.rs1.getInt(8);
            HV0337 = conn.rs1.getInt(9);
            HV0338 = conn.rs1.getInt(10);
            HV0301 = conn.rs1.getInt(11);
        }

        if (ARTSupport != null) {
            double splitData;
            int adderPos = 0;
            //    VALUES FOR CURRENT ON ART
            currentART1M = (float) Math.round((0.03 * HV0335));
            currentART1_4M = (float) Math.round((0.32 * HV0335));
            currentART5_14M = (float) Math.round((0.65 * HV0335));

            splitData = currentART1M + currentART1_4M + currentART5_14M;
            adderPos = 0;

            while (splitData < HV0335) {
                if (adderPos < 2) {
                    currentART5_14M += 1;
                } else {
                    currentART1_4M += 1;
                }
                splitData++;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
                if (splitData == HV0335) {
                }
            }

            splitData = currentART1M + currentART1_4M + currentART5_14M;
            adderPos = 0;

            while (splitData > HV0335) {
                if (adderPos < 2) {
                    currentART5_14M -= 1;
                } else {
                    currentART1_4M -= 1;
                }
                splitData--;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
                if (splitData == HV0335) {
                }
            }

            currentART15_19M = (float) Math.round((0.02 * HV0337));
            currentART20M = (float) Math.round((0.98 * HV0337));

            splitData = currentART20M + currentART15_19M;
            while (splitData < HV0337) {
                currentART20M += 1;
                splitData++;
            }

            splitData = currentART20M + currentART15_19M;
            while (splitData > HV0337) {
                currentART20M -= 1;
                splitData--;
            }

            currentART1F = (float) Math.round((0.03 * HV0336));//NEED CLARIFICATION
            currentART1_4F = (float) Math.round((0.32 * HV0336));
            currentART5_14F = (float) Math.round((0.65 * HV0336));

            splitData = currentART5_14F + currentART1_4F + currentART1F;
            adderPos = 0;

            while (splitData < HV0336) {
                if (adderPos < 2) {
                    currentART5_14F += 1;
                } else {
                    currentART1_4F += 1;
                }
                splitData++;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }

            splitData = currentART5_14F + currentART1_4F + currentART1F;
            adderPos = 0;
            while (splitData > HV0336) {
                if (adderPos < 2) {
                    currentART5_14F -= 1;
                } else {
                    currentART1_4F -= 1;
                }
                splitData--;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }

            currentART15_19F = (float) Math.round((0.02 * HV0338));
            currentART20F = (float) Math.round((0.98 * HV0338));

            splitData = currentART20F + currentART15_19F;
            while (splitData < HV0338) {
                currentART20F += 1;
                splitData++;
            }

            splitData = currentART20F + currentART15_19F;
            while (splitData > HV0338) {
                currentART20F -= 1;
                splitData--;
            }

            totalCurrentART = HV0338 + HV0336 + HV0337 + HV0335;
            //    VALUES

            newART1M = (float) Math.round((0.034 * HV0321));
            newART1_4M = (float) Math.round((0.214 * HV0321));
            newART5_9M = (float) Math.round((0.37 * HV0321));
            newART10_14M = (float) Math.round((0.382 * HV0321));

            splitData = newART10_14M + newART5_9M + newART1_4M + newART1M;
            adderPos = 0;
            while (splitData < HV0321) {
                if (adderPos == 0) {
                    newART10_14M += 1;
                } else if (adderPos == 1) {
                    newART5_9M += 1;
                } else {
                    newART1_4M += 1;
                }

                splitData++;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }

            splitData = newART10_14M + newART5_9M + newART1_4M + newART1M;
            adderPos = 0;
            while (splitData > HV0321) {
                if (adderPos == 0) {
                    newART10_14M -= 1;
                } else if (adderPos == 1) {
                    newART5_9M -= 1;
                } else {
                    newART1_4M -= 1;
                }

                splitData--;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }

            newART15_19M = (float) Math.round((0.008 * HV0323));
            newART20_24M = (float) Math.round((0.008 * HV0323));
            newART25_49M = (float) Math.round((0.775 * HV0323));
            newART50M = (float) Math.round((0.209 * HV0323));

            splitData = newART25_49M + newART50M + newART20_24M + newART15_19M;
            System.out.println("split data : " + splitData + " all data " + HV0323);
            adderPos = 0;
            while (splitData < HV0323) {
                if (adderPos < 3) {
                    newART25_49M += 1;
                } else {
                    newART50M += 1;
                }
                splitData++;
                adderPos++;
                if (adderPos > 3) {
                    adderPos = 0;
                }
            }
            splitData = newART25_49M + newART50M + newART20_24M + newART15_19M;
            //   System.out.println("split data : "+splitData+" all data"+HV0323);     
            adderPos = 0;
            while (splitData > HV0323) {
                if (adderPos < 3) {
                    newART25_49M -= 1;
                } else {
                    newART50M -= 1;
                }
                splitData--;
                adderPos++;
                if (adderPos > 3) {
                    adderPos = 0;
                }
            }
            newART1F = (float) Math.round((0.034 * HV0322));
            newART1_4F = (float) Math.round((0.214 * HV0322));
            newART5_9F = (float) Math.round((0.37 * HV0322));
            newART10_14F = (float) Math.round((0.382 * HV0322));

            splitData = newART10_14F + newART5_9F + newART1_4F + newART1F;
            adderPos = 0;
            while (splitData < HV0322) {
                if (adderPos == 0) {
                    newART10_14F += 1;
                } else if (adderPos == 1) {
                    newART5_9F += 1;
                } else {
                    newART1_4F += 1;
                }

                splitData++;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }

            splitData = newART10_14F + newART5_9F + newART1_4F + newART1F;
            adderPos = 0;
            while (splitData > HV0322) {
                if (adderPos == 0) {
                    newART10_14F -= 1;
                } else if (adderPos == 1) {
                    newART5_9F -= 1;
                } else {
                    newART1_4F -= 1;
                }

                splitData--;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }

            newART15_19F = (float) Math.round((0.008 * HV0324));
            newART20_24F = (float) Math.round((0.008 * HV0324));
            newART25_49F = (float) Math.round((0.775 * HV0324));
            newART50F = (float) Math.round((0.209 * HV0324));

            splitData = newART25_49F + newART50F + newART20_24F + newART15_19F;
            adderPos = 0;
            while (splitData < HV0324) {
                if (adderPos < 3) {
                    newART25_49F += 1;
                } else {
                    newART50F += 1;
                }
                splitData++;
                adderPos++;
                if (adderPos > 3) {
                    adderPos = 0;
                }
            }
            splitData = newART25_49F + newART50F + newART20_24F + newART15_19F;
            adderPos = 0;
            while (splitData > HV0324) {
                if (adderPos < 3) {
                    newART25_49F -= 1;
                } else {
                    newART50F -= 1;
                }
                splitData--;
                adderPos++;
                if (adderPos > 3) {
                    adderPos = 0;
                }
            }

            totalNewART = HV0324 + HV0322 + HV0323 + HV0321;
            System.out.println();
            //    VALUES

            newCARE1M = (float) Math.round((0.18 * HV0309));
            newCARE1_4M = (float) Math.round((0.34 * HV0309));
            newCARE5_9M = (float) Math.round((0.28 * HV0309));
            newCARE10_14M = (float) Math.round((0.20 * HV0309));

            splitData = newCARE10_14M + newCARE5_9M + newCARE1_4M + newCARE1M;
            adderPos = 0;
            while (splitData < HV0309) {
                if (adderPos == 0) {
                    newCARE1_4M += 1;
                } else if (adderPos == 1) {
                    newCARE5_9M += 1;
                } else if (adderPos == 2) {
                    newCARE10_14M += 1;
                } else if (adderPos == 3) {
                    newCARE1M += 1;
                }

                splitData++;
                adderPos++;
                if (adderPos > 3) {
                    adderPos = 0;
                }
            }
            splitData = newCARE10_14M + newCARE5_9M + newCARE1_4M + newCARE1M;
            adderPos = 0;
            while (splitData > HV0309) {
                if (adderPos == 0) {
                    newCARE1_4M -= 1;
                } else if (adderPos == 1) {
                    newCARE5_9M -= 1;
                } else if (adderPos == 2) {
                    newCARE10_14M -= 1;
                } else if (adderPos == 3) {
                    newCARE1M -= 1;
                }

                splitData--;
                adderPos++;
                if (adderPos > 3) {
                    adderPos = 0;
                }
            }

            newCARE15_19M = (float) Math.round((0.02 * HV0311));
            newCARE20_24M = (float) Math.round((0.09 * HV0311));
            newCARE25_49M = (float) Math.round((0.80 * HV0311));
            newCARE50M = (float) Math.round((0.09 * HV0311));

            splitData = newCARE50M + newCARE25_49M + newCARE20_24M + newCARE15_19M;
            while (splitData < HV0311) {
                newCARE25_49M += 1;
                splitData++;
            }

            splitData = newCARE50M + newCARE25_49M + newCARE20_24M + newCARE15_19M;
            while (splitData > HV0311) {
                newCARE25_49M -= 1;
                splitData--;
            }
            newCARE1F = (float) Math.round((0.18 * HV0310));
            newCARE1_4F = (float) Math.round((0.34 * HV0310));
            newCARE5_9F = (float) Math.round((0.28 * HV0310));
            newCARE10_14F = (float) Math.round((0.20 * HV0310));

            splitData = newCARE10_14F + newCARE5_9F + newCARE1_4F + newCARE1F;
            adderPos = 0;
            while (splitData < HV0310) {
                if (adderPos == 0) {
                    newCARE1_4F += 1;
                } else if (adderPos == 1) {
                    newCARE5_9F += 1;
                } else if (adderPos == 2) {
                    newCARE10_14F += 1;
                } else if (adderPos == 3) {
                    newCARE1F += 1;
                }

                splitData++;
                adderPos++;
                if (adderPos > 3) {
                    adderPos = 0;
                }
            }

            splitData = newCARE10_14F + newCARE5_9F + newCARE1_4F + newCARE1F;
            adderPos = 0;
            while (splitData > HV0310) {
                if (adderPos == 0) {
                    newCARE1_4F -= 1;
                } else if (adderPos == 1) {
                    newCARE5_9F -= 1;
                } else if (adderPos == 2) {
                    newCARE10_14F -= 1;
                } else if (adderPos == 3) {
                    newCARE1F -= 1;
                }

                splitData--;
                adderPos++;
                if (adderPos > 3) {
                    adderPos = 0;
                }
            }

            newCARE15_19F = (float) Math.round((0.02 * HV0312));
            newCARE20_24F = (float) Math.round((0.09 * HV0312));
            newCARE25_49F = (float) Math.round((0.80 * HV0312));
            newCARE50F = (float) Math.round((0.09 * HV0312));

            splitData = newCARE50F + newCARE25_49F + newCARE20_24F + newCARE15_19F;
            while (splitData < HV0312) {
                newCARE25_49F += 1;
                splitData++;
            }
            splitData = newCARE50F + newCARE25_49F + newCARE20_24F + newCARE15_19F;
            while (splitData > HV0312) {
                newCARE25_49F -= 1;
                splitData--;
            }
            totalNewCARE = HV0312 + HV0310 + HV0311 + HV0309;
            //    VALUES

            currentCARE1M = (float) Math.round((0.03 * HV0315));
            currentCARE1_4M = (float) Math.round((0.22 * HV0315));
            currentCARE5_9M = (float) Math.round((0.37 * HV0315));
            currentCARE10_14M = (float) Math.round((0.38 * HV0315));

            splitData = currentCARE10_14M + currentCARE5_9M + currentCARE1_4M + currentCARE1M;
            adderPos = 0;
            while (splitData < HV0315) {
                if (adderPos == 0) {
                    currentCARE10_14M += 1;
                } else if (adderPos == 1) {
                    currentCARE5_9M += 1;
                } else if (adderPos == 2) {
                    currentCARE1_4M += 1;
                }

                splitData++;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }
            splitData = currentCARE10_14M + currentCARE5_9M + currentCARE1_4M + currentCARE1M;
            adderPos = 0;
            while (splitData > HV0315) {
                if (adderPos == 0) {
                    currentCARE10_14M -= 1;
                } else if (adderPos == 1) {
                    currentCARE5_9M -= 1;
                } else if (adderPos == 2) {
                    currentCARE1_4M -= 1;
                }

                splitData--;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }
            currentCARE15_19M = (float) Math.round((0.02 * HV0317));
            currentCARE20_24M = (float) Math.round((0.09 * HV0317));
            currentCARE25_49M = (float) Math.round((0.80 * HV0317));
            currentCARE50M = (float) Math.round((0.09 * HV0317));

            splitData = currentCARE50M + currentCARE25_49M + currentCARE20_24M + currentCARE15_19M;
            while (splitData < HV0317) {
                currentCARE25_49M += 1;
                splitData++;
            }
            splitData = currentCARE50M + currentCARE25_49M + currentCARE20_24M + currentCARE15_19M;
            while (splitData > HV0317) {
                currentCARE25_49M -= 1;
                splitData--;
            }
            currentCARE1F = (float) Math.round((0.03 * HV0316));
            currentCARE1_4F = (float) Math.round((0.22 * HV0316));
            currentCARE5_9F = (float) Math.round((0.37 * HV0316));
            currentCARE10_14F = (float) Math.round((0.38 * HV0316));

            splitData = currentCARE10_14F + currentCARE5_9F + currentCARE1_4F + currentCARE1F;
            adderPos = 0;
            while (splitData < HV0316) {
                if (adderPos == 0) {
                    currentCARE10_14F += 1;
                } else if (adderPos == 1) {
                    currentCARE5_9F += 1;
                } else if (adderPos == 2) {
                    currentCARE1_4F += 1;
                }

                splitData++;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }
            splitData = currentCARE10_14F + currentCARE5_9F + currentCARE1_4F + currentCARE1F;
            adderPos = 0;
            while (splitData > HV0316) {
                if (adderPos == 0) {
                    currentCARE10_14F -= 1;
                } else if (adderPos == 1) {
                    currentCARE5_9F -= 1;
                } else if (adderPos == 2) {
                    currentCARE1_4F -= 1;
                }

                splitData--;
                adderPos++;
                if (adderPos > 2) {
                    adderPos = 0;
                }
            }
            currentCARE15_19F = (float) Math.round((0.02 * HV0318));
            currentCARE20_24F = (float) Math.round((0.09 * HV0318));
            currentCARE25_49F = (float) Math.round((0.80 * HV0318));
            currentCARE50F = (float) Math.round((0.09 * HV0318));

            splitData = currentCARE50F + currentCARE25_49F + currentCARE20_24F + currentCARE15_19F;
            while (splitData < HV0318) {
                currentCARE25_49F += 1;
                splitData++;
            }
            splitData = currentCARE50F + currentCARE25_49F + currentCARE20_24F + currentCARE15_19F;
            while (splitData > HV0318) {
                currentCARE25_49F -= 1;
                splitData--;
            }
            totalCurrentCARE = HV0318 + HV0316 + HV0317 + HV0315;

            String dataART[] = (countyName + "," + districtName + "," + facilityName + "," + mflcode + ","
                    + ARTSupport + "," + totalCurrentART + "," + "" + currentART1F + "," + currentART1_4F + ","
                    + currentART5_14F + "," + currentART15_19F + "," + "" + currentART20F + "," + currentART1M
                    + "," + currentART1_4M + "," + currentART5_14M + "," + "" + currentART15_19M + ","
                    + currentART20M + "," + totalNewART + "," + "" + newART1F + "," + newART1_4F + ","
                    + newART5_9F + "," + newART10_14F + "," + newART15_19F + "," + newART20_24F + "," + ""
                    + newART25_49F + "," + newART50F + "," + newART1M + "," + newART1_4M + "," + newART5_9M
                    + "," + newART10_14M + "," + "" + newART15_19M + "," + newART20_24M + "," + newART25_49M
                    + "," + newART50M).split(",");

            String dataCARE[] = (countyName + "," + districtName + "," + facilityName + "," + mflcode + ","
                    + ARTSupport + "," + totalCurrentCARE + "," + "" + currentCARE1F + "," + currentCARE1_4F
                    + "," + currentCARE5_9F + "," + currentCARE10_14F + "," + currentCARE15_19F + "," + ""
                    + currentCARE20_24F + "," + currentCARE25_49F + "," + currentCARE50F + "," + currentCARE1M
                    + "," + currentCARE1_4M + "," + "" + currentCARE5_9M + "," + currentCARE10_14M + ","
                    + currentCARE15_19M + "," + currentCARE20_24M + "," + "" + currentCARE25_49M + ","
                    + currentCARE50M + "," + totalNewCARE + "," + "" + newCARE1F + "," + newCARE1_4F + ","
                    + newCARE5_9F + "," + newCARE10_14F + "," + newCARE15_19F + "," + newCARE20_24F + "," + ""
                    + newCARE25_49F + "," + newCARE50F + "," + newCARE1M + "," + newCARE1_4M + "," + newCARE5_9M
                    + "," + newCARE10_14M + "," + "" + newCARE15_19M + "," + newCARE20_24M + "," + newCARE25_49M
                    + "," + newCARE50M).split(",");

            artpos++;

            HSSFRow rw3shet1 = shet1.createRow(artpos);
            rw3shet1.setHeightInPoints(25);
            for (int positionART = 0; positionART < dataART.length; positionART++) {
                String value = dataART[positionART];
                c11 = rw3shet1.createCell(positionART);
                if (positionART > 4) {
                    c11.setCellValue(Double.parseDouble(value));
                } else {
                    c11.setCellValue(value);
                }
                c11.setCellStyle(stborder);
                if (positionART == 5 || positionART == 16) {
                    c11.setCellStyle(styleHeader);
                }
            }
            // System.out.println("art data length : "+dataART.length);

            HSSFRow rw3Shet2 = shet2.createRow(artpos);
            rw3Shet2.setHeightInPoints(25);
            for (int positionCARE = 0; positionCARE < dataCARE.length; positionCARE++) {
                String value = dataCARE[positionCARE];
                c11 = rw3Shet2.createCell(positionCARE);
                if (positionCARE > 4) {
                    c11.setCellValue(Double.parseDouble(value));
                } else {
                    c11.setCellValue(value);
                }
                c11.setCellStyle(stborder);
                if (positionCARE == 5 || positionCARE == 22) {
                    c11.setCellStyle(styleHeader);
                }

            }
        }

        //  OUTPUT PMTCT DATA HERE +===========================================================================================    
        if (PMTCTSupport != null) {
            numerator = denominator = 0;
            String pmtct_fo_id = year + "_" + quarter + "_" + facilityId;
            String getPMTCTFO = "SELECT numerator,denominator FROM pmtct_fo WHERE id='" + pmtct_fo_id + "' ";
            conn.rs1 = conn.st1.executeQuery(getPMTCTFO);
            if (conn.rs1.next() == true) {
                numerator = conn.rs1.getInt(1);
                denominator = conn.rs1.getInt(2);
            }
            if (!reportDuration.equals("3")) {
                numerator = denominator = 0;
            }

            //        PMTCT_FO===================================================================================================
            PMTCT_FO_I_N = (double) numerator;
            PMTCT_FO_I_D = (double) denominator;
            PMTCT_FO_I_LINKED = (double) Math.round((0.05 * numerator));
            PMTCT_FO_I_NOT_LINKED = 0.0;
            PMTCT_FO_I_UNKNOWN = 0.0;
            PMTCT_FO_U_NOT_BREASTFEEDING = (double) Math.round((0.83 * numerator));
            PMTCT_FO_U_STILL_BREASTFEEDING = 0.0;
            PMTCT_FO_U_BREASTFEEDING_UNKNOWN = 0.0;
            PMTCT_FO_OTHER_INCARE = 0.0;
            PMTCT_FO_OTHER_NOFOLLOWUP = (double) Math.round((0.08 * numerator));
            PMTCT_FO_DIED = (double) Math.round((0.02 * numerator));
            PMTCT_FO_TRANSFERRED = (double) Math.round((0.02 * numerator));

            double normalizer = PMTCT_FO_I_LINKED + PMTCT_FO_I_NOT_LINKED + PMTCT_FO_I_UNKNOWN
                    + PMTCT_FO_U_NOT_BREASTFEEDING + PMTCT_FO_U_STILL_BREASTFEEDING
                    + PMTCT_FO_U_BREASTFEEDING_UNKNOWN + PMTCT_FO_OTHER_INCARE + PMTCT_FO_OTHER_NOFOLLOWUP
                    + PMTCT_FO_DIED + PMTCT_FO_TRANSFERRED;
            int pmtctnum = 0;
            while (numerator > normalizer) {
                PMTCT_FO_U_NOT_BREASTFEEDING++;
                normalizer++;
            }

            while (numerator < normalizer) {
                PMTCT_FO_U_NOT_BREASTFEEDING--;
                normalizer--;
            }
            //        PMTCT_ARV===================================================================================================

            PMTCT_ARV_N = (double) HV0217;
            PMTCT_ARV_D = (double) HV0209;
            PMTCT_ARV_LIFELONGART_NEW = (double) Math.round((0.75 * HV0217));
            PMTCT_ARV_LIFELONGART_EXISTING = (double) Math.round((0.25 * HV0217));

            normalizer = PMTCT_ARV_LIFELONGART_NEW + PMTCT_ARV_LIFELONGART_EXISTING;
            pmtctnum = 0;
            while (HV0217 > normalizer) {
                if (pmtctnum < 3) {
                    PMTCT_ARV_LIFELONGART_NEW++;
                } else {
                    PMTCT_ARV_LIFELONGART_EXISTING++;
                }
                if (pmtctnum == 3) {
                    pmtctnum = 0;
                }
                normalizer++;
                pmtctnum++;
            }

            normalizer = PMTCT_ARV_LIFELONGART_NEW + PMTCT_ARV_LIFELONGART_EXISTING;
            pmtctnum = 0;
            while (normalizer > HV0217) {
                if (pmtctnum < 3) {
                    PMTCT_ARV_LIFELONGART_NEW--;
                } else {
                    PMTCT_ARV_LIFELONGART_EXISTING--;
                }
                if (pmtctnum == 3) {
                    pmtctnum = 0;
                }
                normalizer--;
                pmtctnum++;

            }

            PMTCT_ARV_MATERNAL_TRIPLEDRUG_ARV = 0.0;
            PMTCT_ARV_MATERNAL_AZT = 0.0;
            PMTCT_ARV_SINGLEDOSE = 0.0;

            //      PMTCT_EID===================================================================================================
            PMTCT_EID_N = (double) (HV0224 + HV0225 + HV0227);
            PMTCT_EID_VIRO_2MONTHS = (double) (HV0224);
            PMTCT_EID_VIRO_2_12MONTHS = (double) (HV0225 + HV0227);
            PMTCT_EID_P_VIRO_2MONTHS = (double) (HV0229);
            PMTCT_EID_P_VIRO_2_12MONTHS = (double) (HV0230 + HV0231);

            //  PMTCT_STAT NUMERATOR======================================================================================================

            PMTCT_STATN_N = (double) HV0210;
            PMTCT_STATN_KNOWNPOSTIVE = (double) HV0205;
            PMTCTN_STAT_NEWPOSTIVE = (double) (HV0206 + HV0207 + HV0208);
            PMTCT_STATD_D = (double) Math.round((1.03 * HV0210));

            // PMTCT_CTX=====================================================================================================

            PMTCT_CTX = (double) HV0301; //Mo clarification whether to um or take most recent
            if (PMTCTSupport != null) {
                if (!reportDuration.equals("3")) {
                    numerator = denominator = 0;

                    String dataPMTCT[] = (countyName + "," + districtName + "," + facilityName + "," + mflcode
                            + "," + PMTCTSupport + ",," + ",,,,,,,,,,," + "" + PMTCT_ARV_N + "," + PMTCT_ARV_D
                            + "," + PMTCT_ARV_LIFELONGART_NEW + "," + PMTCT_ARV_LIFELONGART_EXISTING + ","
                            + PMTCT_ARV_MATERNAL_TRIPLEDRUG_ARV + "," + PMTCT_ARV_MATERNAL_AZT + "," + ""
                            + PMTCT_ARV_SINGLEDOSE + "," + PMTCT_EID_N + "," + PMTCT_EID_VIRO_2MONTHS + ","
                            + PMTCT_EID_VIRO_2_12MONTHS + "," + PMTCT_EID_P_VIRO_2MONTHS + ","
                            + PMTCT_EID_P_VIRO_2_12MONTHS + "," + "" + PMTCT_STATN_N + ","
                            + PMTCT_STATN_KNOWNPOSTIVE + "," + PMTCTN_STAT_NEWPOSTIVE + "," + "" + PMTCT_STATD_D
                            + "," + PMTCT_CTX).split(",");
                    HSSFRow rw3shetPMTCT = shetPMTCT.createRow(pmtctpos);
                    rw3shetPMTCT.setHeightInPoints(25);
                    for (int positionPMTCT = 0; positionPMTCT < dataPMTCT.length; positionPMTCT++) {
                        String value = dataPMTCT[positionPMTCT];
                        c11 = rw3shetPMTCT.createCell(positionPMTCT);
                        if (positionPMTCT > 16 && positionPMTCT < (dataPMTCT.length)) {
                            c11.setCellValue(Double.parseDouble(value));
                        } else {
                            c11.setCellValue(value);
                        }
                        c11.setCellStyle(stborder);
                        if (positionPMTCT == 17 || positionPMTCT == 18 || positionPMTCT == 24
                                || positionPMTCT == 29 || positionPMTCT == 32 || positionPMTCT == 33) {
                            c11.setCellStyle(styleHeader);
                        }
                    }
                    pmtctpos++;
                } else {
                    //        HAVE FORMULAS HERE AND THE OUTPUT FOR PMTCT   
                    String dataPMTCT[] = (countyName + "," + districtName + "," + facilityName + "," + mflcode
                            + "," + PMTCTSupport + "," + PMTCT_FO_I_N + "," + "" + PMTCT_FO_I_D + ","
                            + PMTCT_FO_I_LINKED + "," + PMTCT_FO_I_NOT_LINKED + "," + PMTCT_FO_I_UNKNOWN + ","
                            + "" + PMTCT_FO_U_NOT_BREASTFEEDING + "," + PMTCT_FO_U_STILL_BREASTFEEDING + ","
                            + PMTCT_FO_U_BREASTFEEDING_UNKNOWN + "," + PMTCT_FO_OTHER_INCARE + ","
                            + PMTCT_FO_OTHER_NOFOLLOWUP + "," + PMTCT_FO_DIED + "," + PMTCT_FO_TRANSFERRED + ","
                            + "" + PMTCT_ARV_N + "," + PMTCT_ARV_D + "," + PMTCT_ARV_LIFELONGART_NEW + ","
                            + PMTCT_ARV_LIFELONGART_EXISTING + "," + PMTCT_ARV_MATERNAL_TRIPLEDRUG_ARV + ","
                            + PMTCT_ARV_MATERNAL_AZT + "," + "" + PMTCT_ARV_SINGLEDOSE + "," + PMTCT_EID_N + ","
                            + PMTCT_EID_VIRO_2MONTHS + "," + PMTCT_EID_VIRO_2_12MONTHS + ","
                            + PMTCT_EID_P_VIRO_2MONTHS + "," + PMTCT_EID_P_VIRO_2_12MONTHS + "," + ""
                            + PMTCT_STATN_N + "," + PMTCT_STATN_KNOWNPOSTIVE + "," + PMTCTN_STAT_NEWPOSTIVE
                            + "," + "" + PMTCT_STATD_D + ",").split(",");

                    HSSFRow rw3shetPMTCT = shetPMTCT.createRow(pmtctpos);
                    rw3shetPMTCT.setHeightInPoints(25);
                    for (int positionPMTCT = 0; positionPMTCT < dataPMTCT.length; positionPMTCT++) {
                        String value = dataPMTCT[positionPMTCT];
                        c11 = rw3shetPMTCT.createCell(positionPMTCT);
                        if (positionPMTCT > 4 && positionPMTCT < (dataPMTCT.length)) {
                            c11.setCellValue(Double.parseDouble(value));
                        } else {
                            c11.setCellValue(value);
                        }
                        c11.setCellStyle(stborder);
                        if (positionPMTCT == 5 || positionPMTCT == 6 || positionPMTCT == 17
                                || positionPMTCT == 18 || positionPMTCT == 24 || positionPMTCT == 29
                                || positionPMTCT == 32 || positionPMTCT == 33) {
                            c11.setCellStyle(styleHeader);
                        }
                    }
                    pmtctpos++;

                }
            }
        }
    }

    // 711 REPORT
    // MALES

    int TestedAdultMale = 0, TestedAdultFemale = 0;
    int TestedChildMale = 0, TestedChildFemale = 0;
    int HIV_AdultMale = 0, HIV_AdultFemale = 0;
    int HIV_ChildMale = 0, HIV_ChildFemale = 0;

    double FemaleAdultTested;
    double FemaleTestedChild;
    double AdultFemaleHIV;
    double ChildFemaleHIV;

    double MaleAdultTested;
    double MaleTestedChild;
    double AdultMaleHIV;
    double ChildMaleHIV;

    double FemaleAdultTested1 = 0;
    double FemaleAdultTested4 = 0;
    double FemaleAdultTested9 = 0;
    double FemaleAdultTested14 = 0;
    double FemaleAdultTested19 = 0;
    double FemaleAdultTested24 = 0;
    double FemaleAdultTested49 = 0;
    double FemaleAdultTested50 = 0;

    double FemaleTestedChild1 = 0;
    double FemaleTestedChild4 = 0;
    double FemaleTestedChild9 = 0;
    double FemaleTestedChild14 = 0;
    double FemaleTestedChild19 = 0;
    double FemaleTestedChild24 = 0;
    double FemaleTestedChild49 = 0;
    double FemaleTestedChild50 = 0;

    double AdultFemaleHIV19Neg = 0;
    double AdultFemaleHIV24Neg = 0;
    double AdultFemaleHIV49Neg = 0;
    double AdultFemaleHIV50Neg = 0;

    double AdultFemaleHIV19 = 0;
    double AdultFemaleHIV24 = 0;
    double AdultFemaleHIV49 = 0;
    double AdultFemaleHIV50 = 0;

    double ChildFemaleHIV1 = 0;
    double ChildFemaleHIV4 = 0;
    double ChildFemaleHIV9 = 0;
    double ChildFemaleHIV14 = 0;

    double ChildFemaleHIV1Neg = 0;
    double ChildFemaleHIV4Neg = 0;
    double ChildFemaleHIV9Neg = 0;
    double ChildFemaleHIV14Neg = 0;

    // MALES
    double MaleAdultTested19Neg = 0;
    double MaleAdultTested21Neg = 0;
    double MaleAdultTested49Neg = 0;
    double MaleAdultTested50Neg = 0;

    double MaleAdultTested19 = 0;
    double MaleAdultTested24 = 0;
    double MaleAdultTested49 = 0;
    double MaleAdultTested50 = 0;

    double MaleTestedChild1 = 0;
    double MaleTestedChild4 = 0;
    double MaleTestedChild9 = 0;
    double MaleTestedChild14 = 0;

    double MaleTestedChild1Neg = 0;
    double MaleTestedChild4Neg = 0;
    double MaleTestedChild9Neg = 0;
    double MaleTestedChild14Neg = 0;

    double AdultMaleHIV19Neg = 0;
    double AdultMaleHIV24Neg = 0;
    double AdultMaleHIV49Neg = 0;
    double AdultMaleHIV50Neg = 0;

    double AdultMaleHIV19 = 0;
    double AdultMaleHIV24 = 0;
    double AdultMaleHIV49 = 0;
    double AdultMaleHIV50 = 0;

    double ChildMaleHIV1 = 0;
    double ChildMaleHIV4 = 0;
    double ChildMaleHIV9 = 0;
    double ChildMaleHIV14 = 0;

    double ChildMaleHIV1Neg = 0;
    double ChildMaleHIV4Neg = 0;
    double ChildMaleHIV9Neg = 0;
    double ChildMaleHIV14Neg = 0;

    double splitData = 0;
    int adderPos = 0;
    double childSplitData = 0;

    year = Integer.parseInt(request.getParameter("year"));
    reportDuration = request.getParameter("reportDuration");

    //        year=2015;
    //        reportDuration="4";
    String period1 = "";
    String duration1 = "";
    prevYear = year - 1;
    maxYearMonth = 0;

    //        GET REPORT DURATION============================================

    if (reportDuration.equals("1")) {
        duration1 = " moh711.yearmonth BETWEEN " + prevYear + "10 AND " + year + "09";
        period1 = "DATIM ANNUAL DATA REPORT FOR PEPFAR YEAR : " + year;
    } else if (reportDuration.equals("2")) {
        semi_annual = request.getParameter("semi_annual");
        //        semi_annual="2";
        if (semi_annual.equals("1")) {
            duration1 = " moh711.yearmonth BETWEEN " + prevYear + "10 AND " + year + "03";

            period1 = "DATIM SEMI - ANNUAL DATA REPORT FOR PERIOD : OCT " + prevYear + " to MARCH " + year;
        } else {
            duration1 = " moh711.yearmonth BETWEEN " + year + "04 AND " + year + "09";
            period1 = "DATIM SEMI - ANNUAL DATA REPORT FOR PERIOD : APRIL " + year + " to SEPT " + year;
        }
    }

    else if (reportDuration.equals("3")) {
        String startMonth, endMonth;
        quarter = request.getParameter("quarter");
        //       quarter="3";
        String getMonths = "SELECT months,name FROM quarter WHERE id='" + quarter + "'";
        conn.rs = conn.st.executeQuery(getMonths);
        if (conn.rs.next() == true) {
            String months[] = conn.rs.getString(1).split(",");
            startMonth = months[0];
            endMonth = months[2];
            if (quarter.equals("1")) {
                duration1 = " moh711.yearmonth BETWEEN " + prevYear + "" + startMonth + " AND " + prevYear + ""
                        + endMonth;
                period1 = "DATIM QUARTERLY DATA REPORT FOR PERIOD : "
                        + conn.rs.getString(2).replace("-", " " + prevYear + " TO ") + " " + prevYear + "";
            } else {
                duration1 = " moh711.yearmonth BETWEEN " + year + "" + startMonth + " AND " + year + ""
                        + endMonth;
                period1 = "DATIM QUARTERLY DATA REPORT FOR PERIOD : "
                        + conn.rs.getString(2).replace("-", " " + year + " TO ") + " " + year + "";
            }
        }
    }

    else if (reportDuration.equals("4")) {
        month = Integer.parseInt(request.getParameter("month"));
        //            month=5;
        String getMonthName = "SELECT name FROM month WHERE id='" + month + "'";
        conn.rs = conn.st.executeQuery(getMonthName);
        if (conn.rs.next() == true) {
            if (month >= 10) {
                duration1 = " moh711.yearmonth=" + prevYear + "" + month;
                period1 = "DATIM MONTHLY DATA REPORT FOR : " + conn.rs.getString(1) + "(" + prevYear + ")";
            } else {
                duration1 = " moh711.yearmonth=" + year + "0" + month;
                period1 = "DATIM MONTHLY DATA REPORT FOR : " + conn.rs.getString(1) + "(" + year + ")";
            }
        }
    } else {
        duration1 = "";
    }

    FemaleAdultTested = 0;
    FemaleTestedChild = 0;
    AdultFemaleHIV = 0;
    ChildFemaleHIV = 0;
    double TotalTested = 0;
    double TotalPositiveFemale = 0;
    double TotalPositiveMale = 0;
    double TotalNegativeFemale = 0;
    double TotalNegativeMale = 0;

    // MALES
    MaleAdultTested = 0;
    MaleTestedChild = 0;
    AdultMaleHIV = 0;
    ChildMaleHIV = 0;
    double TotalPositive = 0;
    double TotalNegative = 0;

    String county = "";
    String district = "";
    String facilityname = "";

    HSSFCellStyle stylex = wb.createCellStyle();
    stylex.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
    stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    HSSFFont fontx = wb.createFont();
    fontx.setColor(HSSFColor.DARK_BLUE.index);
    stylex.setFont(fontx);
    stylex.setWrapText(true);

    HSSFCellStyle stylemainHeader = wb.createCellStyle();
    stylemainHeader.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    stylemainHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    stylemainHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);
    stylemainHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    stylemainHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    stylemainHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);
    stylemainHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    stylemainHeader.setWrapText(true);

    shet3.setColumnWidth(0, 4000);
    shet3.setColumnWidth(1, 5000);
    shet3.setColumnWidth(2, 7000);
    shet3.setColumnWidth(6, 5000);
    //    for (int i=1;i<=42;i++){
    //   shet3.setColumnWidth(i, 2000);     
    //    }
    HSSFRow rw0 = shet3.createRow(0);
    rw0.setHeightInPoints(30);
    HSSFCell c1, c2, c3, c4, c5, c6, c7, c8;
    c1 = rw0.createCell(0);

    c1.setCellValue(period);
    c1.setCellStyle(stylemainHeader);
    for (int j = 1; j <= 43; j++) {
        c1 = rw0.createCell(j);
        c1.setCellStyle(stylemainHeader);
    }
    shet3.addMergedRegion(new CellRangeAddress(0, 0, 0, 17));
    HSSFCell c12, c13, c14, c15, c16, c17, c18, c19, c20, c110, c111, c112, c113, c114, c115, c116, c117, c118,
            c219;
    HSSFCell c119, c120, c121, c122, c123, c124, c125, c126, c127, c128, c129, c130, c131, c132, c133, c134,
            c135, c136, c137;
    HSSFCell c211, c212, c213, c214, c215, c216, c217;
    rw0 = shet3.createRow(2);
    rw0.setHeightInPoints(30);

    c211 = rw0.createCell(0);
    c212 = rw0.createCell(1);
    c213 = rw0.createCell(2);
    c214 = rw0.createCell(3);
    c215 = rw0.createCell(4);
    c216 = rw0.createCell(5);
    c217 = rw0.createCell(6);

    c211.setCellValue("COUNTY");
    c212.setCellValue("SUB-COUNTY");
    c213.setCellValue("FACILITY");
    c214.setCellValue("MFL-CODE");
    c215.setCellValue("TYPE OF SUPPORT");

    c11 = rw0.createCell(7);

    c12 = rw0.createCell(8);
    c13 = rw0.createCell(9);
    c14 = rw0.createCell(10);
    c15 = rw0.createCell(11);
    c16 = rw0.createCell(12);
    c17 = rw0.createCell(13);
    c18 = rw0.createCell(14);
    c19 = rw0.createCell(15);
    c110 = rw0.createCell(16);
    c111 = rw0.createCell(17);
    c112 = rw0.createCell(18);
    c113 = rw0.createCell(19);
    c114 = rw0.createCell(20);
    c115 = rw0.createCell(21);
    c116 = rw0.createCell(22);
    c117 = rw0.createCell(23);
    c118 = rw0.createCell(24);

    c119 = rw0.createCell(25);
    c120 = rw0.createCell(26);
    c121 = rw0.createCell(27);
    c122 = rw0.createCell(28);
    c123 = rw0.createCell(29);
    c124 = rw0.createCell(30);
    c125 = rw0.createCell(31);
    c126 = rw0.createCell(32);
    c127 = rw0.createCell(33);
    c128 = rw0.createCell(34);
    c129 = rw0.createCell(35);
    c130 = rw0.createCell(36);
    c131 = rw0.createCell(37);
    c132 = rw0.createCell(38);
    c133 = rw0.createCell(39);
    c134 = rw0.createCell(40);
    c135 = rw0.createCell(41);
    c136 = rw0.createCell(42);
    c137 = rw0.createCell(43);

    c216.setCellValue("Total HIV+");

    c217.setCellValue("Total HIV+ (F)");
    c11.setCellValue("POSITIVE");

    c12.setCellValue("FEMALE");
    c216.setCellStyle(stylemainHeader);
    c217.setCellStyle(stylemainHeader);
    c11.setCellStyle(stylemainHeader);
    c12.setCellStyle(stylemainHeader);
    c13.setCellValue("");
    c14.setCellValue("");
    c15.setCellValue("");
    c16.setCellValue("");
    c17.setCellValue("");
    c18.setCellValue("");
    c19.setCellValue("");

    c110.setCellValue("");

    c111.setCellValue("MALE");
    c111.setCellStyle(stylemainHeader);
    c112.setCellValue("");
    c113.setCellValue("");
    c114.setCellValue("");
    c115.setCellValue("");
    c116.setCellValue("");
    c117.setCellValue("");
    c118.setCellValue("");

    //      
    //       rw0=shet3.createRow(2);
    //        rw0.setHeightInPoints(20);

    c119.setCellValue("NEGATIVE");
    c120.setCellValue("FEMALE");
    c119.setCellStyle(stylemainHeader);
    c120.setCellStyle(stylemainHeader);
    c121.setCellValue("");
    c122.setCellValue("");
    c123.setCellValue("");
    c124.setCellValue("");
    c125.setCellValue("");
    c126.setCellValue("");
    c127.setCellValue("");

    c128.setCellValue("");

    c129.setCellValue("MALE");
    c129.setCellStyle(stylemainHeader);
    c130.setCellValue("");
    c131.setCellValue("");
    c132.setCellValue("");
    c133.setCellValue("");
    c134.setCellValue("");
    c135.setCellValue("");
    c136.setCellValue("");
    c137.setCellValue("");
    for (int i = 0; i <= 22; i++) {
        c11 = rw0.getCell(i);
        c11.setCellStyle(stylemainHeader);
    }

    for (int i = 23; i <= 43; i++) {
        c11 = rw0.getCell(i);
        c11.setCellStyle(stylemainHeader);
    }

    shet3.addMergedRegion(new CellRangeAddress(2, 2, 8, 15));
    shet3.addMergedRegion(new CellRangeAddress(2, 2, 17, 24));

    shet3.addMergedRegion(new CellRangeAddress(2, 2, 26, 33));
    shet3.addMergedRegion(new CellRangeAddress(2, 2, 35, 42));

    rw0 = shet3.createRow(3);
    rw0.setHeightInPoints(30);
    c211 = rw0.createCell(0);
    c212 = rw0.createCell(1);
    c213 = rw0.createCell(2);
    c214 = rw0.createCell(3);
    c215 = rw0.createCell(4);
    c216 = rw0.createCell(5);
    c217 = rw0.createCell(6);

    // other data
    c11 = rw0.createCell(7);
    c12 = rw0.createCell(8);
    c13 = rw0.createCell(9);
    c14 = rw0.createCell(10);
    c15 = rw0.createCell(11);
    c16 = rw0.createCell(12);
    c17 = rw0.createCell(13);
    c18 = rw0.createCell(14);
    c19 = rw0.createCell(15);
    c110 = rw0.createCell(16);
    c111 = rw0.createCell(17);
    c112 = rw0.createCell(18);
    c113 = rw0.createCell(19);
    c114 = rw0.createCell(20);
    c115 = rw0.createCell(21);
    c116 = rw0.createCell(22);
    c117 = rw0.createCell(23);
    c118 = rw0.createCell(24);

    c11.setCellValue("Num");
    c216.setCellValue("TOTAL HIV+");
    c217.setCellValue("TOTAL +VE (F)");
    c12.setCellValue("Paeds <15Yr");
    c13.setCellValue("");
    c14.setCellValue("");
    c15.setCellValue("");
    c16.setCellValue("Adults 15+Yr");
    c17.setCellValue("");
    c18.setCellValue("");
    c19.setCellValue("");

    c110.setCellValue("TOTAL +VE MALE");

    c111.setCellValue("Paeds <15Yr");
    c112.setCellValue("");
    c113.setCellValue("");
    c114.setCellValue("");
    c115.setCellValue("Adults 15+Yr");
    c116.setCellValue("");
    c117.setCellValue("");
    c118.setCellValue("");

    c11 = rw0.createCell(25);
    c12 = rw0.createCell(26);
    c13 = rw0.createCell(27);
    c14 = rw0.createCell(28);
    c15 = rw0.createCell(29);
    c16 = rw0.createCell(30);
    c17 = rw0.createCell(31);
    c18 = rw0.createCell(32);
    c19 = rw0.createCell(33);
    c110 = rw0.createCell(34);
    c111 = rw0.createCell(35);
    c112 = rw0.createCell(36);
    c113 = rw0.createCell(37);
    c114 = rw0.createCell(38);
    c115 = rw0.createCell(39);
    c116 = rw0.createCell(40);
    c117 = rw0.createCell(41);
    c118 = rw0.createCell(42);
    c119 = rw0.createCell(43);

    c11.setCellValue("TOTAL -VE(F)");
    c12.setCellValue("Paeds <15Yr");
    c13.setCellValue("");
    c14.setCellValue("");
    c15.setCellValue("");
    c16.setCellValue("Adults 15+Yr");
    c17.setCellValue("");
    c18.setCellValue("");
    c19.setCellValue("");

    c110.setCellValue("TOTAL -VE(M)");

    c111.setCellValue("Paeds <15Yr");
    c112.setCellValue("");
    c113.setCellValue("");
    c114.setCellValue("");
    c115.setCellValue("Adults 15+Yr");
    c116.setCellValue("");
    c117.setCellValue("");
    c118.setCellValue("");
    c119.setCellValue("DQA");

    for (int i = 0; i <= 22; i++) {
        c11 = rw0.getCell(i);
        c11.setCellStyle(styleHeader);
    }

    shet3.addMergedRegion(new CellRangeAddress(3, 3, 8, 11));
    shet3.addMergedRegion(new CellRangeAddress(3, 3, 12, 15));
    shet3.addMergedRegion(new CellRangeAddress(3, 3, 17, 20));
    shet3.addMergedRegion(new CellRangeAddress(3, 3, 21, 24));
    //     
    for (int k = 23; k <= 43; k++) {
        c113 = rw0.getCell(k);
        c113.setCellStyle(styleHeader);
    }

    shet3.addMergedRegion(new CellRangeAddress(3, 3, 26, 29));
    shet3.addMergedRegion(new CellRangeAddress(3, 3, 30, 33));
    shet3.addMergedRegion(new CellRangeAddress(3, 3, 35, 38));
    shet3.addMergedRegion(new CellRangeAddress(3, 3, 39, 42));
    shet3.addMergedRegion(new CellRangeAddress(3, 4, 43, 43));

    rw0 = shet3.createRow(4);
    rw0.setHeightInPoints(30);
    c211 = rw0.createCell(0);
    c212 = rw0.createCell(1);
    c213 = rw0.createCell(2);
    c214 = rw0.createCell(3);
    c215 = rw0.createCell(4);
    c216 = rw0.createCell(5);
    c217 = rw0.createCell(6);

    // for ther est
    c11 = rw0.createCell(7);
    c12 = rw0.createCell(8);
    c13 = rw0.createCell(9);
    c14 = rw0.createCell(10);
    c15 = rw0.createCell(11);
    c16 = rw0.createCell(12);
    c17 = rw0.createCell(13);
    c18 = rw0.createCell(14);
    c19 = rw0.createCell(15);
    c110 = rw0.createCell(16);
    c111 = rw0.createCell(17);
    c112 = rw0.createCell(18);
    c113 = rw0.createCell(19);
    c114 = rw0.createCell(20);
    c115 = rw0.createCell(21);
    c116 = rw0.createCell(22);
    c117 = rw0.createCell(23);
    c118 = rw0.createCell(24);

    c11.setCellValue("NUM");
    c216.setCellValue("TOTAL HIV+");
    c217.setCellValue("TOTAL +VE(F)");
    c12.setCellValue("<1 ");
    c13.setCellValue("1-4Y");
    c14.setCellValue("5-9Y");
    c15.setCellValue("10-14Y");
    c16.setCellValue("15-19Y");
    c17.setCellValue("20-24Y");
    c18.setCellValue("25-49Y");
    c19.setCellValue("50+Y");

    c110.setCellValue("TOTAL +VE MALE");
    shet3.addMergedRegion(new CellRangeAddress(3, 4, 16, 16));
    c111.setCellValue("<1");
    c112.setCellValue("1-4Y");
    c113.setCellValue("5-9Y");
    c114.setCellValue("10-14Y");
    c115.setCellValue("15-19Y");
    c116.setCellValue("20-24Y");
    c117.setCellValue("25-49Y");
    c118.setCellValue("50+Y");

    for (int i = 0; i <= 22; i++) {
        c11 = rw0.getCell(i);
        c11.setCellStyle(styleHeader);
    }
    //     

    // for negative

    c11 = rw0.createCell(25);
    c12 = rw0.createCell(26);
    c13 = rw0.createCell(27);
    c14 = rw0.createCell(28);
    c15 = rw0.createCell(29);
    c16 = rw0.createCell(30);
    c17 = rw0.createCell(31);
    c18 = rw0.createCell(32);
    c19 = rw0.createCell(33);
    c110 = rw0.createCell(34);
    c111 = rw0.createCell(35);
    c112 = rw0.createCell(36);
    c113 = rw0.createCell(37);
    c114 = rw0.createCell(38);
    c115 = rw0.createCell(39);
    c116 = rw0.createCell(40);
    c117 = rw0.createCell(41);
    c118 = rw0.createCell(42);
    c119 = rw0.createCell(43);

    c11.setCellValue("TOTAL -VE(F)");
    shet3.addMergedRegion(new CellRangeAddress(3, 4, 25, 25));
    c12.setCellValue("<1");
    c13.setCellValue("1-4Y");
    c14.setCellValue("5-9Y");
    c15.setCellValue("10-14Y");
    c16.setCellValue("15-19Y");
    c17.setCellValue("20-24Y");
    c18.setCellValue("25-49Y");
    c19.setCellValue("50+Y");

    c110.setCellValue("TOTAL -VE(M)");
    shet3.addMergedRegion(new CellRangeAddress(3, 4, 34, 34));
    c111.setCellValue("<1");
    c112.setCellValue("1-4Y");
    c113.setCellValue("5-9Y");
    c114.setCellValue("10-14Y");
    c115.setCellValue("15-19Y");
    c116.setCellValue("20-24Y");
    c117.setCellValue("25-49Y");
    c118.setCellValue("50+Y");
    c119.setCellValue("");

    for (int l = 20; l <= 43; l++) {
        c113 = rw0.getCell(l);
        c113.setCellStyle(styleHeader);
    }

    double checkdiff = 0;
    int count = 4;
    TestedAdultMale = 0;
    TestedAdultFemale = 0;
    TestedChildMale = 0;
    TestedChildFemale = 0;
    HIV_AdultMale = 0;
    HIV_AdultFemale = 0;
    HIV_ChildMale = 0;
    HIV_ChildFemale = 0;

    //---------------------------------------------------------------------------

    String facilid = "";
    String facilname = "";
    String dsdta = "";

    String get711data = "SELECT(sum(VCTClient_Tested_CF) +sum( VCTClient_Tested_AF)+sum(DTCB_Test_Out_AF)+sum(DTCB_Test_In_AF))" //ADULTS TESTED FEMALE  
            + ",(sum(VCTClient_Tested_CM)+ sum(VCTClient_Tested_AM) +  sum(DTCB_Test_Out_AM) + sum(DTCB_Test_In_AM))"//ADULTS TESTED MALES
            + ", (sum(VCTClient_HIV_CF)+ sum(VCTClient_HIV_AF)+sum(DTCC_HIV_In_AF)+ sum(DTCC_HIV_Out_AF))" // ADULTS HIV+ FEMALE
            + ",(sum(VCTClient_HIV_CM)+sum(VCTClient_HIV_AM)+ sum(DTCC_HIV_In_AM) +sum(DTCC_HIV_Out_AM)) " // ADULTS HIV+ MALE
            + ", (sum(DTCB_Test_Out_CF) + sum(DTCB_Test_In_CF))" // CHILDREN TOTAL TESTED FEMALE
            + ", (sum(DTCB_Test_Out_CM) + sum(DTCB_Test_In_CM))" // CHILDREN TOTAL TESTED MALE
            + ", ( sum(DTCC_HIV_In_CF)+ sum(DTCC_HIV_Out_CF))" // CHILDREN OSITIVE FEMALE
            + ", (sum(DTCC_HIV_In_CM)+ sum(DTCC_HIV_Out_CM)),county.County,district.DistrictNom,"
            + "subpartnera.SubPartnerNom,subpartnera.CentreSanteId,subpartnera.HTC_Support1"// CHILDREN POSITIVE MALE
            + " FROM moh711 JOIN subpartnera " + "ON moh711.SubPartnerID=subpartnera.SubPartnerID "
            + "JOIN district ON subpartnera.DistrictID=district.DistrictID JOIN county ON "
            + "district.CountyID=county.CountyID" + " WHERE " + " " + facilityIds1 + " " + duration1
            + " && subpartnera.HTC=1  " + "GROUP BY moh711.SubPartnerID ";
    System.out.println("711 : " + get711data);
    conn.rs = conn.st.executeQuery(get711data);
    while (conn.rs.next()) {

        county = conn.rs.getString(9);
        district = conn.rs.getString(10);
        facilityname = conn.rs.getString(11);
        mflcode = conn.rs.getString(12);
        dsdta = conn.rs.getString(13);

        TestedAdultFemale = conn.rs.getInt(1);
        TestedAdultMale = conn.rs.getInt(2);
        HIV_AdultFemale = conn.rs.getInt(3);
        HIV_AdultMale = conn.rs.getInt(4);
        TestedChildFemale = conn.rs.getInt(5);
        TestedChildMale = conn.rs.getInt(6);
        HIV_ChildFemale = conn.rs.getInt(7);
        HIV_ChildMale = conn.rs.getInt(8);
        System.out.println(facilityname + " KKK " + HIV_AdultFemale + " " + HIV_AdultMale + " "
                + HIV_ChildFemale + "  " + HIV_ChildMale);
        System.out.println(
                facilityname + "TestedChildFemale " + TestedChildFemale + "  HIV_ChildFemale " + HIV_ChildFemale
                        + "  TestedChildMale " + TestedChildMale + " HIV_ChildMale   " + HIV_ChildMale);

        String basicDetails = county + "@" + district + "@" + facilityname + "@" + mflcode + "@" + dsdta;
        String arrayDetails[] = basicDetails.split("@");

        count++;
        rw0 = shet3.createRow(count);
        int facilno = 0;

        for (int j = 0; j < arrayDetails.length; j++) {

            HSSFCell S3cell = rw0.createCell(facilno);
            S3cell.setCellValue(arrayDetails[j]);
            //    System.out.println(arrayDetails[j]);
            S3cell.setCellStyle(stborder);
            System.out.println("facildet pos : " + facilno + "     det : " + arrayDetails[j]);
            facilno++;
        }

        System.out.println(facilityname + "   TestedAdultFemale " + TestedAdultFemale + "TestedAdultMale  "
                + TestedAdultMale + " TestedChildFemale  " + TestedChildFemale + " TestedChildMale "
                + TestedChildMale + " HIV_AdultFemale  " + HIV_AdultFemale + " HIV_AdultMale " + HIV_AdultMale
                + " HIV_ChildFemale " + HIV_ChildFemale + " HIV_ChildMale " + HIV_ChildMale);

        //      FEMALES

        FemaleAdultTested19 = (float) Math.round((0.05 * TestedAdultFemale));
        FemaleAdultTested24 = (float) Math.round((0.11 * TestedAdultFemale));
        FemaleAdultTested49 = (float) Math.round((0.72 * TestedAdultFemale));
        FemaleAdultTested50 = (float) Math.round((0.12 * TestedAdultFemale));

        FemaleTestedChild1 = (float) Math.round((0.05 * TestedChildFemale));
        FemaleTestedChild4 = (float) Math.round((0.26 * TestedChildFemale));
        FemaleTestedChild9 = (float) Math.round((0.29 * TestedChildFemale));
        FemaleTestedChild14 = (float) Math.round((0.40 * TestedChildFemale));

        //postive
        AdultFemaleHIV19 = (float) Math.round((0.02 * HIV_AdultFemale));
        AdultFemaleHIV24 = (float) Math.round((0.09 * HIV_AdultFemale));
        AdultFemaleHIV49 = (float) Math.round((0.79 * HIV_AdultFemale));
        AdultFemaleHIV50 = (float) Math.round((0.10 * HIV_AdultFemale));

        //positve
        ChildFemaleHIV1 = (float) Math.round((0.13 * HIV_ChildFemale));
        ChildFemaleHIV4 = (float) Math.round((0.37 * HIV_ChildFemale));
        ChildFemaleHIV9 = (float) Math.round((0.25 * HIV_ChildFemale));
        ChildFemaleHIV14 = (float) Math.round((0.25 * HIV_ChildFemale));

        // MALES

        MaleAdultTested19 = (float) Math.round((0.05 * TestedAdultMale));
        MaleAdultTested24 = (float) Math.round((0.11 * TestedAdultMale));
        MaleAdultTested49 = (float) Math.round((0.72 * TestedAdultMale));
        MaleAdultTested50 = (float) Math.round((0.12 * TestedAdultMale));

        MaleTestedChild1 = (float) Math.round((0.05 * TestedChildMale));
        MaleTestedChild4 = (float) Math.round((0.26 * TestedChildMale));
        MaleTestedChild9 = (float) Math.round((0.29 * TestedChildMale));
        MaleTestedChild14 = (float) Math.round((0.40 * TestedChildMale));

        //positive
        AdultMaleHIV19 = (float) Math.round((0.02 * HIV_AdultMale));
        AdultMaleHIV24 = (float) Math.round((0.09 * HIV_AdultMale));
        AdultMaleHIV49 = (float) Math.round((0.79 * HIV_AdultMale));
        AdultMaleHIV50 = (float) Math.round((0.10 * HIV_AdultMale));

        //positives
        ChildMaleHIV1 = (float) Math.round((0.13 * HIV_ChildMale));
        ChildMaleHIV4 = (float) Math.round((0.37 * HIV_ChildMale));
        ChildMaleHIV9 = (float) Math.round((0.25 * HIV_ChildMale));
        ChildMaleHIV14 = (float) Math.round((0.25 * HIV_ChildMale));

        //            TestedAdultFemale=conn.rs.getInt(1);
        //    TestedAdultMale=conn.rs.getInt(2);
        //    HIV_AdultFemale=conn.rs.getInt(3);
        //    HIV_AdultMale=conn.rs.getInt(4);
        //    TestedChildFemale=conn.rs.getInt(5);
        //    TestedChildMale=conn.rs.getInt(6);
        //    HIV_ChildFemale=conn.rs.getInt(7);
        //    HIV_ChildMale=conn.rs.getInt(8);
        //           TotalTested=FemaleTestedChild1+FemaleTestedChild4+FemaleTestedChild9+FemaleTestedChild14+FemaleAdultTested19+FemaleAdultTested24+FemaleAdultTested49+FemaleAdultTested50+ MaleAdultTested19+MaleAdultTested24+MaleAdultTested49+MaleAdultTested50+MaleTestedChild1+MaleTestedChild4+MaleTestedChild9+MaleTestedChild14;
        //                 TotalNegativeFemale1=AdultFemaleHIV19Neg+AdultFemaleHIV24Neg+AdultFemaleHIV49Neg+AdultFemaleHIV50Neg+ ChildFemaleHIV1Neg+ChildFemaleHIV4Neg+ChildFemaleHIV9Neg+ChildFemaleHIV14Neg;
        //                TotalNegativeMale1=AdultMaleHIV19Neg+AdultMaleHIV24Neg+AdultMaleHIV49Neg+AdultMaleHIV50Neg+ChildMaleHIV1Neg+ChildMaleHIV4Neg+ChildMaleHIV9Neg+ChildMaleHIV14Neg;

        //negative

        int neg1male = 0;
        int neg4male = 0;
        int neg9male = 0;
        int neg14male = 0;
        int neg19male = 0;
        int neg24male = 0;
        int neg49male = 0;
        int neg50male = 0;
        AdultMaleHIV19Neg = (float) Math.round(MaleAdultTested19) - (AdultMaleHIV19);
        AdultMaleHIV24Neg = (float) Math.round(MaleAdultTested24) - (AdultMaleHIV24);
        AdultMaleHIV49Neg = (float) Math.round(MaleAdultTested49) - (AdultMaleHIV49);
        AdultMaleHIV50Neg = (float) Math.round(MaleAdultTested50) - (AdultMaleHIV50);
        if (AdultMaleHIV19Neg <= -1) {
            neg19male = 1;
        }
        if (AdultMaleHIV24Neg <= -1) {
            neg24male = 1;
        }
        if (AdultMaleHIV49Neg <= -1) {
            neg49male = 1;
        }
        if (AdultMaleHIV50Neg <= -1) {
            neg50male = 1;
        }
        // child male negatives
        ChildMaleHIV1Neg = (float) Math.round(MaleTestedChild1) - (ChildMaleHIV1);
        ChildMaleHIV4Neg = (float) Math.round(MaleTestedChild4) - (ChildMaleHIV4);
        ChildMaleHIV9Neg = (float) Math.round(MaleTestedChild9) - (ChildMaleHIV9);
        ChildMaleHIV14Neg = (float) Math.round(MaleTestedChild14) - (ChildMaleHIV14);

        if (ChildMaleHIV1Neg <= -1) {
            neg1male = 1;
        }
        if (ChildMaleHIV4Neg <= -1) {
            neg4male = 1;
        }
        if (ChildMaleHIV9Neg <= -1) {
            neg9male = 1;
        }
        if (ChildMaleHIV14Neg <= -1) {
            neg14male = 1;
        }

        //negative

        int neg1female = 0;
        int neg4female = 0;
        int neg9female = 0;
        int neg14female = 0;
        int neg19female = 0;
        int neg24female = 0;
        int neg49female = 0;
        int neg50female = 0;
        ChildFemaleHIV1Neg = (float) Math.round(FemaleTestedChild1) - (ChildFemaleHIV1);
        ChildFemaleHIV4Neg = (float) Math.round(FemaleTestedChild4) - (ChildFemaleHIV4);
        ChildFemaleHIV9Neg = (float) Math.round(FemaleTestedChild9) - (ChildFemaleHIV9);
        ChildFemaleHIV14Neg = (float) Math.round(FemaleTestedChild14) - (ChildFemaleHIV14);

        if (ChildFemaleHIV1Neg <= -1) {
            neg1female = 1;
        }
        if (ChildFemaleHIV4Neg <= -1) {
            neg4female = 1;
        }
        if (ChildFemaleHIV9Neg <= -1) {
            neg9female = 1;
        }
        if (ChildFemaleHIV14Neg <= -1) {
            neg14female = 1;
        }

        System.out.println(facilityname + " fffff " + ChildFemaleHIV1Neg + " " + ChildFemaleHIV4Neg + " "
                + ChildFemaleHIV9Neg + "  " + ChildFemaleHIV14Neg);
        //negative

        AdultFemaleHIV19Neg = (float) Math.round(FemaleAdultTested19) - (AdultFemaleHIV19);
        AdultFemaleHIV24Neg = (float) Math.round(FemaleAdultTested24) - (AdultFemaleHIV24);
        AdultFemaleHIV49Neg = (float) Math.round(FemaleAdultTested49) - (AdultFemaleHIV49);
        AdultFemaleHIV50Neg = (float) Math.round(FemaleAdultTested50) - (AdultFemaleHIV50);

        if (AdultFemaleHIV19Neg <= -1) {
            neg19female = 1;
        }
        if (AdultFemaleHIV24Neg <= -1) {
            neg24female = 1;
        }
        if (AdultFemaleHIV49Neg <= -1) {
            neg49female = 1;
        }
        if (AdultFemaleHIV50Neg <= -1) {
            neg50female = 1;
        }

        double totalpositivesmale = 0;
        double totalpositivesfemale = 0;
        double totalpositives = 0;
        double totalnegatives = 0;
        double totalfemalehiv = 0;
        double totalmalehiv = 0;
        double totalfemaletesteddis = 0;
        double totalmaletesteddis = 0;
        double totalfemaletested = 0;
        double totalmaletested = 0;
        double negfem = 0;
        double negmale = 0;
        int redalert = 0;
        int redalert1 = 0;
        int redalert2 = 0;
        int redalert3 = 0;
        int finalalert = 0;
        totalpositives = AdultFemaleHIV19 + AdultFemaleHIV24 + AdultFemaleHIV49 + AdultFemaleHIV50
                + ChildFemaleHIV1 + ChildFemaleHIV4 + ChildFemaleHIV9 + ChildFemaleHIV14 + AdultMaleHIV19
                + AdultMaleHIV24 + AdultMaleHIV49 + AdultMaleHIV50 + ChildMaleHIV1 + ChildMaleHIV4
                + ChildMaleHIV9 + ChildMaleHIV14;
        totalnegatives = AdultFemaleHIV19Neg + AdultFemaleHIV24Neg + AdultFemaleHIV49Neg + AdultFemaleHIV50Neg
                + ChildFemaleHIV1Neg + ChildFemaleHIV4Neg + ChildFemaleHIV9Neg + ChildFemaleHIV14Neg
                + AdultMaleHIV19Neg + AdultMaleHIV24Neg + AdultMaleHIV49Neg + AdultMaleHIV50Neg
                + ChildMaleHIV1Neg + ChildMaleHIV4Neg + ChildMaleHIV9Neg + ChildMaleHIV14Neg;
        totalpositivesfemale = AdultFemaleHIV19 + AdultFemaleHIV24 + AdultFemaleHIV49 + AdultFemaleHIV50
                + ChildFemaleHIV1 + ChildFemaleHIV4 + ChildFemaleHIV9 + ChildFemaleHIV14;
        totalpositivesmale = AdultMaleHIV19 + AdultMaleHIV24 + AdultMaleHIV49 + AdultMaleHIV50 + ChildMaleHIV1
                + ChildMaleHIV4 + ChildMaleHIV9 + ChildMaleHIV14;
        //              

        //   total tested after distribution
        totalfemaletesteddis = FemaleTestedChild1 + FemaleTestedChild4 + FemaleTestedChild9
                + FemaleTestedChild14 + FemaleAdultTested19 + FemaleAdultTested24 + FemaleAdultTested49
                + FemaleAdultTested50;
        totalmaletesteddis = MaleAdultTested19 + MaleAdultTested24 + MaleAdultTested49 + MaleAdultTested50
                + MaleTestedChild1 + MaleTestedChild4 + MaleTestedChild9 + MaleTestedChild14;
        // totaltested

        totalfemaletested = TestedAdultFemale + TestedChildFemale;
        totalmaletested = TestedAdultMale + TestedChildMale;

        //poistives
        totalfemalehiv = HIV_AdultFemale + HIV_ChildFemale;
        totalmalehiv = HIV_AdultMale + HIV_ChildMale;
        // negative 
        negfem = totalfemaletested - totalfemalehiv;
        negmale = totalmaletested - totalmalehiv;
        double TotalNegativeFemale1 = 0;
        double TotalNegativeMale1 = 0;

        TotalNegativeFemale1 = AdultFemaleHIV19Neg + AdultFemaleHIV24Neg + AdultFemaleHIV49Neg
                + AdultFemaleHIV50Neg + ChildFemaleHIV1Neg + ChildFemaleHIV4Neg + ChildFemaleHIV9Neg
                + ChildFemaleHIV14Neg;
        TotalNegativeMale1 = AdultMaleHIV19Neg + AdultMaleHIV24Neg + AdultMaleHIV49Neg + AdultMaleHIV50Neg
                + ChildMaleHIV1Neg + ChildMaleHIV4Neg + ChildMaleHIV9Neg + ChildMaleHIV14Neg;
        double checkdiff1 = 0;
        double checkdiff2 = 0;
        double checkdiff3 = 0;
        double totalcheckdiff = 0;
        int redfemalealert = 0;
        int redmalealert = 0;

        System.out.println(facilityname + " KKK " + HIV_AdultFemale + " " + HIV_AdultMale + " "
                + HIV_ChildFemale + "  " + HIV_ChildMale);
        System.out.println(
                facilityname + "TestedChildFemale " + TestedChildFemale + "  HIV_ChildFemale " + HIV_ChildFemale
                        + "  TestedChildMale " + TestedChildMale + " HIV_ChildMale   " + HIV_ChildMale);
        double totaltestedmale1 = 0;
        double totaltestedfemale1 = 0;
        TotalTested = TestedChildFemale + TestedChildMale + TestedAdultMale + TestedAdultFemale;
        totaltestedmale1 = TestedChildMale + TestedAdultMale;
        totaltestedfemale1 = TestedChildFemale + TestedAdultFemale;
        TotalPositiveFemale = HIV_ChildFemale + HIV_AdultFemale;
        TotalPositiveMale = HIV_ChildMale + HIV_AdultMale;
        TotalPositive = HIV_ChildFemale + HIV_AdultFemale + HIV_ChildMale + HIV_AdultMale;
        TotalNegativeFemale = totaltestedfemale1 - TotalPositiveFemale;
        TotalNegativeMale = totaltestedmale1 - TotalPositiveMale;

        checkdiff = totalfemalehiv - totalpositivesfemale;
        // positive female
        if (checkdiff > 2 || checkdiff < -2) {
            redalert = 1;
        }
        // positive male
        checkdiff1 = totalmalehiv - totalpositivesmale;
        if (checkdiff1 > 2 || checkdiff1 < -2) {
            redalert1 = 1;
        }
        // negative female
        checkdiff2 = negfem - TotalNegativeFemale1;
        if (checkdiff2 > 2 || checkdiff2 < -2) {
            redalert2 = 1;
        }

        // negativemale
        checkdiff3 = negmale - TotalNegativeMale1;
        if (checkdiff3 > 2 || checkdiff3 < -2) {
            redalert3 = 1;
        }
        totalcheckdiff = TotalTested - (totalfemaletesteddis + totalmaletesteddis);
        if (totalcheckdiff > 2 || totalcheckdiff < -2) {
            finalalert = 1;
        }

        rw0.setHeightInPoints(25);
        c211 = rw0.createCell(0);
        c212 = rw0.createCell(1);
        c213 = rw0.createCell(2);
        c214 = rw0.createCell(3);
        c215 = rw0.createCell(4);
        c216 = rw0.createCell(5);
        c217 = rw0.createCell(6);

        // the rest
        c11 = rw0.createCell(7);
        c12 = rw0.createCell(8);
        c13 = rw0.createCell(9);
        c14 = rw0.createCell(10);
        c15 = rw0.createCell(11);
        c16 = rw0.createCell(12);
        c17 = rw0.createCell(13);
        c18 = rw0.createCell(14);
        c19 = rw0.createCell(15);
        c20 = rw0.createCell(16);
        c110 = rw0.createCell(17);
        c111 = rw0.createCell(18);
        c112 = rw0.createCell(19);
        c113 = rw0.createCell(20);
        c114 = rw0.createCell(21);
        c115 = rw0.createCell(22);
        c116 = rw0.createCell(23);
        c117 = rw0.createCell(24);

        //c11.setCellValue(facilname);
        //String basicDetails=county+"@"+district+"@"+facilityname+"@"+mflcode+"@"+dsdta;
        c211.setCellValue(county);
        c212.setCellValue(district);
        c213.setCellValue(facilityname);
        c214.setCellValue(mflcode);
        c215.setCellValue(dsdta);
        shet3.addMergedRegion(new CellRangeAddress(2, 4, 0, 0));
        shet3.addMergedRegion(new CellRangeAddress(2, 4, 1, 1));
        shet3.addMergedRegion(new CellRangeAddress(2, 4, 2, 2));
        shet3.addMergedRegion(new CellRangeAddress(2, 4, 3, 3));
        shet3.addMergedRegion(new CellRangeAddress(2, 4, 4, 4));
        //      Female   
        c11.setCellValue(TotalTested);
        c216.setCellValue(TotalPositive);

        c217.setCellValue(TotalPositiveFemale);

        shet3.addMergedRegion(new CellRangeAddress(2, 4, 5, 5));
        shet3.addMergedRegion(new CellRangeAddress(2, 4, 6, 6));
        shet3.addMergedRegion(new CellRangeAddress(3, 4, 7, 7));
        c12.setCellValue((float) Math.round(ChildFemaleHIV1));
        c13.setCellValue((float) Math.round(ChildFemaleHIV4));
        c14.setCellValue((float) Math.round(ChildFemaleHIV9));
        c15.setCellValue((float) Math.round(ChildFemaleHIV14));
        c16.setCellValue((float) Math.round(AdultFemaleHIV19));
        c17.setCellValue((float) Math.round(AdultFemaleHIV24));
        c18.setCellValue((float) Math.round(AdultFemaleHIV49));
        c19.setCellValue((float) Math.round(AdultFemaleHIV50));

        c20.setCellValue(TotalPositiveMale);

        //male
        c110.setCellValue((float) Math.round(ChildMaleHIV1));
        c111.setCellValue((float) Math.round(ChildMaleHIV4));
        c112.setCellValue((float) Math.round(ChildMaleHIV9));
        c113.setCellValue((float) Math.round(ChildMaleHIV14));
        c114.setCellValue((float) Math.round(AdultMaleHIV19));
        c115.setCellValue((float) Math.round(AdultMaleHIV24));
        c116.setCellValue((float) Math.round(AdultMaleHIV49));
        c117.setCellValue((float) Math.round(AdultMaleHIV50));

        for (int i = 0; i <= 22; i++) {
            c11 = rw0.getCell(i);
            c11.setCellStyle(stborder);

            if (redalert == 1) {
                c217 = rw0.getCell(6);
                c217.setCellStyle(redstyle);
            }
            if (redalert1 == 1) {
                c20 = rw0.getCell(16);
                c20.setCellStyle(redstyle);
            }
        }

        //      shet3.addMergedRegion(new CellRangeAddress(2,5,0,0));

        c11 = rw0.createCell(25);
        c12 = rw0.createCell(26);
        c13 = rw0.createCell(27);
        c14 = rw0.createCell(28);
        c15 = rw0.createCell(29);
        c16 = rw0.createCell(30);
        c17 = rw0.createCell(31);
        c18 = rw0.createCell(32);
        c19 = rw0.createCell(33);
        c110 = rw0.createCell(34);
        c111 = rw0.createCell(35);
        c112 = rw0.createCell(36);
        c113 = rw0.createCell(37);
        c114 = rw0.createCell(38);
        c115 = rw0.createCell(39);
        c116 = rw0.createCell(40);
        c117 = rw0.createCell(41);
        c118 = rw0.createCell(42);
        c119 = rw0.createCell(43);

        c11.setCellValue((float) Math.round(TotalNegativeFemale));
        c12.setCellValue((float) Math.round(ChildFemaleHIV1Neg));
        c13.setCellValue((float) Math.round(ChildFemaleHIV4Neg));
        c14.setCellValue((float) Math.round(ChildFemaleHIV9Neg));
        c15.setCellValue((float) Math.round(ChildFemaleHIV14Neg));
        c16.setCellValue((float) Math.round(AdultFemaleHIV19Neg));
        c17.setCellValue((float) Math.round(AdultFemaleHIV24Neg));
        c18.setCellValue((float) Math.round(AdultFemaleHIV49Neg));
        c19.setCellValue((float) Math.round(AdultFemaleHIV50Neg));

        c110.setCellValue((float) Math.round(TotalNegativeMale));

        c111.setCellValue((float) Math.round(ChildMaleHIV1Neg));
        c112.setCellValue((float) Math.round(ChildMaleHIV4Neg));
        c113.setCellValue((float) Math.round(ChildMaleHIV9Neg));
        c114.setCellValue((float) Math.round(ChildMaleHIV14Neg));
        c115.setCellValue((float) Math.round(AdultMaleHIV19Neg));
        c116.setCellValue((float) Math.round(AdultMaleHIV24Neg));
        c117.setCellValue((float) Math.round(AdultMaleHIV49Neg));
        c118.setCellValue((float) Math.round(AdultMaleHIV50Neg));
        c119.setCellValue("");
        System.out.println(facilityname + "    jjj  " + AdultMaleHIV19Neg + "__________" + AdultMaleHIV24Neg
                + "__________" + AdultMaleHIV49Neg + "__________" + AdultMaleHIV50Neg + "__________"
                + ChildMaleHIV1Neg + "__________" + ChildMaleHIV4Neg + "__________" + ChildMaleHIV9Neg
                + "__________" + ChildMaleHIV14Neg);

        for (int i = 23; i <= 43; i++) {
            c11 = rw0.getCell(i);
            c11.setCellStyle(stborder);

            if (redalert2 == 1) {
                c11 = rw0.getCell(25);
                c11.setCellStyle(redstyle);
            }
            if (redalert3 == 1) {
                c110 = rw0.getCell(34);
                c110.setCellStyle(redstyle);
            }
            if (finalalert == 1) {
                c119 = rw0.getCell(43);
                c119.setCellStyle(redstyle);
            }

            if (neg1female == 1) {
                c12 = rw0.getCell(26);
                c12.setCellStyle(redstyle);
            }
            if (neg4female == 1) {
                c12 = rw0.getCell(27);
                c12.setCellStyle(redstyle);
            }
            if (neg9female == 1) {
                c13 = rw0.getCell(28);
                c13.setCellStyle(redstyle);
            }
            if (neg14female == 1) {
                c14 = rw0.getCell(29);
                c14.setCellStyle(redstyle);
            }
            if (neg19female == 1) {
                c15 = rw0.getCell(30);
                c15.setCellStyle(redstyle);
            }
            if (neg24female == 1) {
                c16 = rw0.getCell(31);
                c16.setCellStyle(redstyle);
            }
            if (neg49female == 1) {
                c17 = rw0.getCell(32);
                c17.setCellStyle(redstyle);
            }
            if (neg50female == 1) {
                c18 = rw0.getCell(33);
                c18.setCellStyle(redstyle);
            }

            //male
            if (neg1male == 1) {
                c111 = rw0.getCell(35);
                c111.setCellStyle(redstyle);
            }
            if (neg4male == 1) {
                c112 = rw0.getCell(36);
                c112.setCellStyle(redstyle);
            }
            if (neg9male == 1) {
                c113 = rw0.getCell(37);
                c113.setCellStyle(redstyle);
            }
            if (neg14male == 1) {
                c114 = rw0.getCell(38);
                c114.setCellStyle(redstyle);
            }
            if (neg19male == 1) {
                c115 = rw0.getCell(39);
                c115.setCellStyle(redstyle);
            }
            if (neg24male == 1) {
                c116 = rw0.getCell(40);
                c116.setCellStyle(redstyle);
            }
            if (neg49male == 1) {
                c117 = rw0.getCell(41);
                c117.setCellStyle(redstyle);
            }
            if (neg50male == 1) {
                c118 = rw0.getCell(42);
                c118.setCellStyle(redstyle);
            }

        }
        //      shet3.addMergedRegion(new CellRangeAddress(2,5,20,20));
    }

    if (conn.st != null) {
        conn.st.close();
    }
    if (conn.st1 != null) {
        conn.st1.close();
    }
    if (conn.st2 != null) {
        conn.st2.close();
    }

    if (conn.rs != null) {
        conn.rs.close();
    }
    if (conn.rs1 != null) {
        conn.rs1.close();
    }
    if (conn.rs2 != null) {
        conn.rs2.close();
    }
    if (conn.conn != null) {
        conn.conn.close();
    }

    IdGenerator IG = new IdGenerator();
    createdOn = IG.CreatedOn();

    // write it as an excel attachment
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
    wb.write(outByteStream);
    byte[] outArray = outByteStream.toByteArray();
    response.setContentType("application/ms-excel");
    response.setContentLength(outArray.length);
    response.setHeader("Expires:", "0"); // eliminates browser caching
    response.setHeader("Content-Disposition",
            "attachment; filename=DATIM_VERIFICATION_REPORT_CREATED_ON_" + createdOn.trim() + ".xls");
    OutputStream outStream = response.getOutputStream();
    outStream.write(outArray);
    outStream.flush();

}

From source file:reports.vmmcexcel.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from ww  w.j  a  v  a  2  s .  co  m
        response.setContentType("text/html;charset=UTF-8");
        session = request.getSession();

        dbConn conn = new dbConn();
        //get the existing data for the month, year and facility that is already on session

        String month = "";
        String year = "";
        String facil = "361";

        String form = "vmmc";

        //=====================================================================================================

        year = "2015";
        month = "5";
        String county = "";

        String header = "";

        String reportType = "";
        if (request.getParameter("reportType") != null) {
            reportType = request.getParameter("reportType");
        }
        String reportDuration = "";
        if (request.getParameter("reportDuration") != null) {
            reportDuration = request.getParameter("reportDuration");
        }

        if (request.getParameter("year") != null) {
            year = request.getParameter("year");
        }

        if (request.getParameter("facility") != null && reportType.equals("2")) {
            facil = request.getParameter("facility");

            String getfacil = "select SubPartnerNom,CentreSanteId as mflcode from subpartnera where SubPartnerID='"
                    + facil + "'";
            conn.rs = conn.st.executeQuery(getfacil);

            while (conn.rs.next()) {

                header += " FACILITY : " + conn.rs.getString(1).toUpperCase() + "     MFL CODE  :  "
                        + conn.rs.getString(2) + "  ";

            }

        }

        if (request.getParameter("county") != null && reportType.equals("2")) {
            county = request.getParameter("county");

            String getcounty = "select County from county where CountyID='" + county + "'";
            conn.rs = conn.st.executeQuery(getcounty);

            while (conn.rs.next()) {

                header += " COUNTY : " + conn.rs.getString(1).toUpperCase() + " ";

            }

        }

        if (request.getParameter("month") != null && reportDuration.equals("4")) {
            month = request.getParameter("month");

            String getmonth = "select name as monthname from month where id='" + month + "'";
            conn.rs = conn.st.executeQuery(getmonth);

            while (conn.rs.next()) {

                header += " MONTH : " + conn.rs.getString(1).toUpperCase() + "";

            }

        }

        header += " YEAR : " + year + "";

        String facilitywhere = "";
        String yearwhere = "";
        String monthwhere = "";
        String countywhere = "";
        String duration = "";
        String semi_annual = "";
        String quarter = "";

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        int yearcopy = Integer.parseInt(year);

        //        reportType="2";
        //        year=2015;
        //        reportDuration="3";
        String yearmonth = "" + year;
        int prevYear = yearcopy - 1;
        int maxYearMonth = 0;
        int monthcopy = 0;
        //        GET REPORT DURATION============================================

        if (reportDuration.equals("1")) {
            yearmonth += "_AnnualReport";
            duration = " " + form + ".yearmonth BETWEEN " + prevYear + "10 AND " + year + "09";
        } else if (reportDuration.equals("2")) {
            semi_annual = request.getParameter("semi_annual");
            //        semi_annual="2";
            if (semi_annual.equals("1")) {
                yearmonth = prevYear + "_Oct_" + year + "_Mar";
                duration = " " + form + ".yearmonth BETWEEN " + prevYear + "10 AND " + year + "03";
            } else {
                yearmonth += "_Apr_Sep";
                duration = " " + form + ".yearmonth BETWEEN " + year + "04 AND " + year + "09";
            }
        }

        else if (reportDuration.equals("3")) {
            String startMonth, endMonth;
            quarter = request.getParameter("quarter");
            //       quarter="3";
            String getMonths = "SELECT months,name FROM quarter WHERE id='" + quarter + "'";
            conn.rs = conn.st.executeQuery(getMonths);
            if (conn.rs.next() == true) {

                String months[] = conn.rs.getString(1).split(",");
                startMonth = months[0];
                endMonth = months[2];
                if (quarter.equals("1")) {
                    duration = " " + form + ".yearmonth BETWEEN " + prevYear + "" + startMonth + " AND "
                            + prevYear + "" + endMonth;
                    yearmonth = prevYear + "_" + conn.rs.getString(2);
                } else {
                    yearmonth = year + "_" + conn.rs.getString(2);
                    duration = " " + form + ".yearmonth BETWEEN " + year + "" + startMonth + " AND " + year + ""
                            + endMonth;
                }
            }
        }

        else if (reportDuration.equals("4")) {
            monthcopy = Integer.parseInt(request.getParameter("month"));

            //     month=5;
            if (monthcopy >= 10) {
                yearmonth = prevYear + "_" + month;
                duration = " " + form + ".yearmonth=" + prevYear + "" + month;
            } else {
                duration = " " + form + ".yearmonth=" + year + "0" + month;
                yearmonth = year + "_(" + month + ")";
            }
        } else {
            duration = "";
        }

        //======================================================================

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        String getexistingdata = "";

        if (!county.equals("")) {

            countywhere = " and countyid = '" + county + "'";

        }

        if (!facil.equals("") && reportType.equalsIgnoreCase("2")) {

            facilitywhere = " and " + form + ".SubPartnerID = '" + facil + "' ";

        }

        String joinedwhwere = " where 1=1 " + facilitywhere + "  " + yearwhere + " && " + duration;

        //=====================================================================================================    

        //=====================================================================================================    

        //______________________________________________________________________________________
        //                       NOW CREATE THE WORKSHEETS          
        //______________________________________________________________________________________  

        HSSFWorkbook wb = new HSSFWorkbook();

        //______________________________________________________________________________________
        //______________________________________________________________________________________

        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        HSSFSheet shet = wb.createSheet(form);

        //create headers for that worksheet

        HSSFRow rw = shet.createRow(0);
        rw.setHeightInPoints(25);
        HSSFCell cl0 = rw.createCell(0);
        cl0.setCellValue("VOLUNTARY MALE CIRCUMCISION REPORTING FORM");
        cl0.setCellStyle(stylex);

        for (int a = 1; a <= 4; a++) {
            HSSFCell clx = rw.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        HSSFRow rw1 = shet.createRow(1);
        rw1.setHeightInPoints(23);
        HSSFCell cl = rw1.createCell(0);
        cl.setCellValue(header);
        cl.setCellStyle(stylex);

        for (int a = 1; a <= 4; a++) {
            HSSFCell clx = rw1.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }

        HSSFRow rw2 = shet.createRow(2);
        rw2.setHeightInPoints(23);
        HSSFCell cl3 = rw2.createCell(0);
        cl3.setCellValue("P5.1.D:");
        cl3.setCellStyle(style2);

        HSSFCell cl31 = rw2.createCell(1);
        cl31.setCellValue(
                "Number of Males Circumcised as part of the minimum package of MC for HIV prevention services:");
        cl31.setCellStyle(stylex);

        for (int a = 2; a <= 4; a++) {
            HSSFCell clx = rw2.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }
        shet.addMergedRegion(new CellRangeAddress(2, 11, 0, 0));
        shet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
        shet.addMergedRegion(new CellRangeAddress(1, 1, 0, 4));
        shet.addMergedRegion(new CellRangeAddress(2, 2, 1, 4));
        shet.setColumnWidth(0, 2000);
        shet.setColumnWidth(1, 9000);
        shet.setColumnWidth(2, 5000);
        shet.setColumnWidth(3, 5000);
        shet.setColumnWidth(4, 5000);

        getexistingdata = "select sum(P51D1) as P51D1,   sum(P51D9) as P51D9,   sum(P51D10) as P51D10,   sum(P51D19) as P51D19,sum(P51D24) as P51D24, sum(P51D29) as P51D29, sum(P51D49) as  P51D49,   sum(P51D50) as P51D50,    sum(P51DT) as P51DT,   sum(P521DM) as  P521DM,    sum(P521DS) as P521DS,   sum(P521DT) as P521DT,   sum(P522DM) as P522DM,    sum(P522DS) as P522DS,    sum(P522DT) as P522DT,   sum(P52DM) as  P52DM,   sum(P52DS) as P52DS,    sum(P52DT) as P52DT,   sum(P511KP) as P511KP,   sum(P511KN) as P511KN,   sum(P511KU) as P511KU,   sum(P511Surg) as P511Surg,   sum(P511Dev) as P511Dev,   sum(P53DF) as P53DF,    sum(P53DO) as P53DO,   sum(P53DM) as P53DM,    sum(P53D) as P53D,   sum(P54D) as P54D  from "
                + form
                + " join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                + form + ".SubPartnerID = subpartnera.SubPartnerID   " + joinedwhwere + "  ";

        System.out.println(getexistingdata);
        String P51D1 = "";
        String P51D9 = "";
        String P51D10 = "";
        String P51D19 = "";
        String P51D24 = "";
        String P51D29 = "";
        String P51D49 = "";
        String P51D50 = "";
        String P51DT = "";
        String P521DM = "";
        String P521DS = "";
        String P521DT = "";
        String P522DM = "";
        String P522DS = "";
        String P522DT = "";
        String P52DM = "";
        String P52DS = "";
        String P52DT = "";
        String P511KP = "";
        String P511KN = "";
        String P511KU = "";
        String P511Surg = "";
        String P511Dev = "";
        String P53DF = "";
        String P53DO = "";
        String P53DM = "";
        String P53D = "";
        String P54D = "";

        String distid = "";

        if (session.getAttribute("subcountyid") != null) {
            distid = session.getAttribute("subcountyid").toString();
        }

        int counter = 0;

        conn.rs = conn.st.executeQuery(getexistingdata);
        while (conn.rs.next()) {
            //now check if form was updated and if its one month after data entry
            //now load the column values here

            P51D1 = conn.rs.getString("P51D1");
            if (P51D1 == null) {
                P51D1 = "";
            }

            P51D9 = conn.rs.getString("P51D9");
            if (P51D9 == null) {
                P51D9 = "";
            }

            P51D10 = conn.rs.getString("P51D10");
            if (P51D10 == null) {
                P51D10 = "";
            }

            P51D19 = conn.rs.getString("P51D19");
            if (P51D19 == null) {
                P51D19 = "";
            }

            P51D24 = conn.rs.getString("P51D24");
            if (P51D24 == null) {
                P51D24 = "";
            }

            P51D29 = conn.rs.getString("P51D29");
            if (P51D29 == null) {
                P51D29 = "";
            }

            P51D49 = conn.rs.getString("P51D49");
            if (P51D49 == null) {
                P51D49 = "";
            }

            P51D50 = conn.rs.getString("P51D50");
            if (P51D50 == null) {
                P51D50 = "";
            }

            P51DT = conn.rs.getString("P51DT");
            if (P51DT == null) {
                P51DT = "";
            }

            P521DM = conn.rs.getString("P521DM");
            if (P521DM == null) {
                P521DM = "";
            }

            P521DS = conn.rs.getString("P521DS");
            if (P521DS == null) {
                P521DS = "";
            }

            P521DT = conn.rs.getString("P521DT");
            if (P521DT == null) {
                P521DT = "";
            }

            P522DM = conn.rs.getString("P522DM");
            if (P522DM == null) {
                P522DM = "";
            }

            P522DS = conn.rs.getString("P522DS");
            if (P522DS == null) {
                P522DS = "";
            }

            P522DT = conn.rs.getString("P522DT");
            if (P522DT == null) {
                P522DT = "";
            }

            P52DM = conn.rs.getString("P52DM");
            if (P52DM == null) {
                P52DM = "";
            }

            P52DS = conn.rs.getString("P52DS");
            if (P52DS == null) {
                P52DS = "";
            }

            P52DT = conn.rs.getString("P52DT");
            if (P52DT == null) {
                P52DT = "";
            }

            P511KP = conn.rs.getString("P511KP");
            if (P511KP == null) {
                P511KP = "";
            }

            P511KN = conn.rs.getString("P511KN");
            if (P511KN == null) {
                P511KN = "";
            }

            P511KU = conn.rs.getString("P511KU");
            if (P511KU == null) {
                P511KU = "";
            }

            P511Surg = conn.rs.getString("P511Surg");
            if (P511Surg == null) {
                P511Surg = "";
            }

            P511Dev = conn.rs.getString("P511Dev");
            if (P511Dev == null) {
                P511Dev = "";
            }

            P53DF = conn.rs.getString("P53DF");
            if (P53DF == null) {
                P53DF = "";
            }

            P53DO = conn.rs.getString("P53DO");
            if (P53DO == null) {
                P53DO = "";
            }

            P53DM = conn.rs.getString("P53DM");
            if (P53DM == null) {
                P53DM = "";
            }

            P53D = conn.rs.getString("P53D");
            if (P53D == null) {
                P53D = "";
            }

            P54D = conn.rs.getString("P54D");
            if (P54D == null) {
                P54D = "";
            }

        }

        String createdtable = "";

        if (1 == 1) {

            if (1 == 1) {
                int r = 3;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("< 1");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51D1);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }

            if (1 == 1) {
                int r = 4;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("1-9");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51D9);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));

            }

            //=====================================================================================

            if (1 == 1) {
                int r = 5;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("10-14");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51D10);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));

            }

            //=====================================================================================

            if (1 == 1) {
                int r = 6;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("15-19");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51D19);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));

            }
            //================================================================================== 

            if (1 == 1) {
                int r = 7;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("20-24");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51D24);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 8;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("25-29");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51D29);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));

            }
            //==================================================================================  

            if (1 == 1) {
                int r = 9;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("30-49");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51D49);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 10;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("50 +");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51D50);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 11;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Total");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P51DT);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 12;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("P5.2.D");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue(
                        "Number of Clients circumcised who experienced one or more moderate or severe adverse events(s)");
                clx.setCellStyle(stylex);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue("");
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 4));
                shet.addMergedRegion(new CellRangeAddress(r, r + 4, 0, 0));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 13;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("");
                clx.setCellStyle(style2);

                HSSFCell clxm = rwx.createCell(2);
                clxm.setCellValue("Moderate");
                clxm.setCellStyle(stylex);

                HSSFCell clxs = rwx.createCell(3);
                clxs.setCellValue("Severe");
                clxs.setCellStyle(stylex);

                HSSFCell clxt = rwx.createCell(4);
                clxt.setCellValue("Total");
                clxt.setCellStyle(stylex);

                //shet.addMergedRegion(new CellRangeAddress(r,r,1,3));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 14;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("During Circumcission");
                clx.setCellStyle(stylex);

                HSSFCell clxm = rwx.createCell(2);
                clxm.setCellValue(P521DM);
                clxm.setCellStyle(style2);

                HSSFCell clxs = rwx.createCell(3);
                clxs.setCellValue(P521DS);
                clxs.setCellStyle(style2);

                HSSFCell clxt = rwx.createCell(4);
                clxt.setCellValue(P521DT);
                clxt.setCellStyle(style2);

                //shet.addMergedRegion(new CellRangeAddress(r,r,1,3));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 15;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Post CircumCission");
                clx.setCellStyle(stylex);

                HSSFCell clxm = rwx.createCell(2);
                clxm.setCellValue(P522DM);
                clxm.setCellStyle(style2);

                HSSFCell clxs = rwx.createCell(3);
                clxs.setCellValue(P522DS);
                clxs.setCellStyle(style2);

                HSSFCell clxt = rwx.createCell(4);
                clxt.setCellValue(P522DT);
                clxt.setCellStyle(style2);

                //shet.addMergedRegion(new CellRangeAddress(r,r,1,3));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 16;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Total Adverse Events");
                clx.setCellStyle(stylex);

                HSSFCell clxm = rwx.createCell(2);
                clxm.setCellValue(P52DM);
                clxm.setCellStyle(style2);

                HSSFCell clxs = rwx.createCell(3);
                clxs.setCellValue(P52DS);
                clxs.setCellStyle(style2);

                HSSFCell clxt = rwx.createCell(4);
                clxt.setCellValue(P52DT);
                clxt.setCellStyle(style2);

                //shet.addMergedRegion(new CellRangeAddress(r,r,1,3));

            }
            //==================================================================================
            if (1 == 1) {
                int r = 17;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("P5.1.1.K");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("HIV Status of MC clients)");
                clx.setCellStyle(stylex);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue("");
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 4));
                shet.addMergedRegion(new CellRangeAddress(r, r + 3, 0, 0));

            }
            //==================================================================================
            if (1 == 1) {
                int r = 18;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Tested/self-reported positive");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P511KP);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }

            //==================================================================================
            if (1 == 1) {
                int r = 19;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Tested negative");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P511KN);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }

            //==================================================================================

            if (1 == 1) {
                int r = 20;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Unknown/self-reported negative");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P511KU);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }

            //==================================================================================
            //==================================================================================
            if (1 == 1) {
                int r = 21;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("P5.1.1.T");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Circumcission Technique)");
                clx.setCellStyle(stylex);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue("");
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 4));
                shet.addMergedRegion(new CellRangeAddress(r, r + 2, 0, 0));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 22;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Surgical VMMC");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P511Surg);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }

            //==================================================================================

            if (1 == 1) {
                int r = 23;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Device-Based VMMC");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P511Dev);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }

            //==================================================================================

            //==================================================================================
            if (1 == 1) {
                int r = 24;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("P5.3.D:");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue(
                        "Number of locations providing MC surgery as part of the minimum package of MC for HIV prevention services within the reporting period ");
                clx.setCellStyle(stylex);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue("");
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 4));
                shet.addMergedRegion(new CellRangeAddress(r, r + 4, 0, 0));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 25;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Fixed/Static");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P53DF);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }

            //==================================================================================
            if (1 == 1) {
                int r = 26;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Outreach");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P53DO);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }
            //==============================================================================================
            //==================================================================================
            if (1 == 1) {
                int r = 27;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Mobile");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P53DM);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }
            //==============================================================================================
            //==================================================================================
            if (1 == 1) {
                int r = 28;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);
                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("Total");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P53D);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }
            //==============================================================================================

            //==================================================================================
            if (1 == 1) {
                int r = 29;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(28);

                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("P5.3.D:");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue(
                        "Number of males circumcised within the reporting period who return at least once for postoperative follow?up care (routine or emergent) within 14 days of surgery");
                clx.setCellStyle(stylex);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue("");
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                }
                shet.addMergedRegion(new CellRangeAddress(r, r, 1, 4));
                shet.addMergedRegion(new CellRangeAddress(r, r + 1, 0, 0));

            }
            //==================================================================================

            if (1 == 1) {
                int r = 30;
                HSSFRow rwx = shet.createRow(r);
                rwx.setHeightInPoints(23);
                HSSFCell clx0 = rwx.createCell(0);
                clx0.setCellValue("");
                clx0.setCellStyle(style2);

                HSSFCell clx = rwx.createCell(1);
                clx.setCellValue("");
                clx.setCellStyle(style2);

                HSSFCell clx1 = rwx.createCell(4);
                clx1.setCellValue(P54D);
                clx1.setCellStyle(style2);

                for (int a = 2; a <= 3; a++) {
                    HSSFCell clx2 = rwx.createCell(a);
                    clx2.setCellValue("");
                    clx2.setCellStyle(style2);
                    shet.addMergedRegion(new CellRangeAddress(r, r, 1, 3));
                }

            }

            //==================================================================================

        }

        //System.out.println(createdtable);

        if (conn.conn != null) {
            conn.conn.close();
        }
        if (conn.rs != null) {
            conn.rs.close();
        }
        if (conn.rs1 != null) {
            conn.rs1.close();
        }
        if (conn.rs2 != null) {
            conn.rs2.close();
        }
        if (conn.st != null) {
            conn.st.close();
        }
        if (conn.st2 != null) {
            conn.st2.close();
        }

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition",
                "attachment; filename=" + form + yearmonth + "_Generatted_On_" + createdOn + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
        outStream.close();

    } catch (SQLException ex) {
        Logger.getLogger(Vmmcpdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}