Example usage for org.apache.poi.ss.usermodel CellStyle setFillPattern

List of usage examples for org.apache.poi.ss.usermodel CellStyle setFillPattern

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel CellStyle setFillPattern.

Prototype

void setFillPattern(FillPatternType fp);

Source Link

Document

setting to one fills the cell with the foreground color...

Usage

From source file:packtest.FillsAndColors.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    Sheet sheet = wb.createSheet("new sheet");

    // Create a row and put some cells in it. Rows are 0 based.
    Row row = sheet.createRow((short) 1);

    // Aqua background
    CellStyle style = wb.createCellStyle();
    style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
    style.setFillPattern(CellStyle.BIG_SPOTS);
    Cell cell = row.createCell((short) 1);
    cell.setCellValue(new XSSFRichTextString("X"));
    cell.setCellStyle(style);//from   w w  w  .ja  v  a2  s  . c o  m

    // Orange "foreground", foreground being the fill foreground not the font color.
    style = wb.createCellStyle();
    style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    cell = row.createCell((short) 2);
    cell.setCellValue(new XSSFRichTextString("X"));
    cell.setCellStyle(style);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream(Utils.getPath("fill_colors.xlsx"));
    wb.write(fileOut);
    fileOut.close();

}

From source file:poi.xssf.usermodel.examples.FillsAndColors.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    Sheet sheet = wb.createSheet("new sheet");

    // Create a row and put some cells in it. Rows are 0 based.
    Row row = sheet.createRow((short) 1);

    // Aqua background
    CellStyle style = wb.createCellStyle();
    style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
    style.setFillPattern(CellStyle.BIG_SPOTS);
    Cell cell = row.createCell((short) 1);
    cell.setCellValue(new XSSFRichTextString("X"));
    cell.setCellStyle(style);/*from   w  w w  .  j  a v a2  s. c  om*/

    // Orange "foreground", foreground being the fill foreground not the font color.
    style = wb.createCellStyle();
    style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    cell = row.createCell((short) 2);
    cell.setCellValue(new XSSFRichTextString("X"));
    cell.setCellStyle(style);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
    wb.write(fileOut);
    fileOut.close();

}

From source file:PPMP.ppmpreport.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    response.setContentType("text/html;charset=UTF-8");

    try {//from   www  . j  a v a2 s .c  om
        /* TODO output your page here. You may use following sample code. */

        //create ppmp report here

        //define some variables for keeping number of columns. 
        // this should be dynamic because of the annual cumulatives depending on the selected year
        //the minimum year is 2011
        //
        int selectedyear = 2018;
        int projectstartyear = 2018;
        int minimumcolumns = 9;//this is if the year is 2011
        int currentcolumns = minimumcolumns + (selectedyear - projectstartyear);
        String selectedQTR = "Q2";

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

            selectedyear = new Integer(request.getParameter("year"));

        }

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

            selectedQTR = request.getParameter("quarter");

        }

        HSSFWorkbook wb = new HSSFWorkbook();

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        String month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        String date = String.format("%02d", cal.get(Calendar.DATE));
        String hour = String.format("%02d", cal.get(Calendar.HOUR_OF_DAY));
        String min = String.format("%02d", cal.get(Calendar.MINUTE));
        String sec = String.format("%02d", cal.get(Calendar.SECOND));

        String generationtime = "(" + year + "_" + month + "_" + date + ")_" + hour + "-" + min + "-" + sec;

        //______________________________________________________________________________________
        //______________________________________________________________________________________

        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setFontName("Times New Roman");
        font.setColor((short) 0000);
        font.setBoldweight(HSSFFont.COLOR_NORMAL);

        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setWrapText(true);

        CellStyle spstyle = wb.createCellStyle();
        spstyle.setFont(font);
        spstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        spstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        spstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        spstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        spstyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        spstyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        spstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        spstyle.setWrapText(true);
        spstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        System.out.println("Blue index:" + HSSFColor.BLUE.index);

        HSSFFont font2 = wb.createFont();
        font2.setFontHeightInPoints((short) 12);
        font2.setFontName("Times New Roman");
        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);
        style2.setWrapText(true);

        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.WHITE.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.setFontHeightInPoints((short) 12);
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Times New Roman");
        fontx.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        fontx.setFontHeightInPoints((short) 16);
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        HSSFSheet shet = wb.createSheet("PPMP " + selectedyear + " Report ");

        //create headers for that worksheet

        HSSFRow rw = shet.createRow(0);
        rw.setHeightInPoints(25);
        HSSFCell cl0 = rw.createCell(0);
        cl0.setCellValue("PROJECT PERFORMANCE MONITORING PLAN (PPMP)");
        cl0.setCellStyle(stylex);

        for (int a = 1; a < currentcolumns; a++) {
            HSSFCell clx = rw.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }
        //merge row one

        shet.addMergedRegion(new CellRangeAddress(0, 0, 0, currentcolumns - 1));

        //firt row

        ArrayList headerone = new ArrayList();
        //headerone.add("Sub Purpose");
        headerone.add("Code");
        headerone.add("Indicator");
        headerone.add("Baseline");
        headerone.add("Year " + selectedyear + " Target");
        headerone.add(selectedyear + " Quarterly Achievements ");
        headerone.add("");
        headerone.add("");
        headerone.add("");
        headerone.add("Cumulative Year Achievements");
        //the header Cumulative Year Achievements could be in the report depending on the selected year
        //for 2011, its not expected to appear in the report

        for (int a = 0; a <= (selectedyear - projectstartyear); a++) {
            if (a == 0) {
                //do nothing 
            } else {
                headerone.add("");
            }

        }

        headerone.add("Percentage (%) Achieved vs Year " + selectedyear);

        //header two which contains quartersa dn yearly achievement

        ArrayList headertwo = new ArrayList();
        //headertwo.add("Sub Purpose");
        headertwo.add("Code");
        headertwo.add("Indicator");
        headertwo.add("Baseline");
        headertwo.add("");
        headertwo.add("Oct-Dec " + (selectedyear - 1));
        headertwo.add("Jan-Mar");
        headertwo.add("Apr-Jun");
        headertwo.add("Jul-Sep");
        headertwo.add(selectedyear);
        //the header Cumulative Year Achievements could be in the report depending on the selected year
        //for 2011, its not expected to appear in the report

        for (int a = 0; a <= (selectedyear - projectstartyear); a++) {
            if (a == 0) {
                //do nothing 
            } else {
                headertwo.add(selectedyear - a);
                //eg 2016, 2015, 2014 ...
            }

        }

        headertwo.add("");

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

        //DISPLAY HEADER   DISPLAY HEADER   DISPLAY HEADER   DISPLAY HEADER  DISPLAY HEADER

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

        //display the header values for row one and two
        HSSFRow rw1 = shet.createRow(1);
        for (int a = 0; a < headerone.size(); a++) {
            HSSFCell cellx = rw1.createCell(a);

            cellx.setCellValue(headerone.get(a).toString());
            cellx.setCellStyle(style);
            shet.setColumnWidth(a, 3500);

        }

        //===================row 2=======================

        //display the header values for row one and two
        HSSFRow rw2 = shet.createRow(2);
        rw2.setHeightInPoints(35);
        for (int a = 0; a < headertwo.size(); a++) {
            HSSFCell cellx = rw2.createCell(a);

            if (headertwo.get(a).toString().startsWith("20")) {

                cellx.setCellValue(new Integer(headertwo.get(a).toString()));
            } else {
                cellx.setCellValue(headertwo.get(a).toString());
            }

            cellx.setCellStyle(style);

        }

        // shet.addMergedRegion(new CellRangeAddress(start row, end row, start column ,end column));   
        String mergingarray[] = { "1_2_0_0", "1_2_1_1", "1_2_2_2", "1_2_3_3", "1_1_4_7",
                "1_1_8_" + (8 + (selectedyear - projectstartyear)),
                "1_2_" + (8 + (selectedyear - projectstartyear) + 1) + "_"
                        + (8 + (selectedyear - projectstartyear) + 1) };

        for (int a = 0; a < mergingarray.length; a++) {

            String content[] = mergingarray[a].split("_");

            shet.addMergedRegion(new CellRangeAddress(new Integer(content[0]), new Integer(content[1]),
                    new Integer(content[2]), new Integer(content[3])));

        }

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

        //DISPLAY VALUES    DISPLAY VALUES    DISPLAY VALUES   DISPLAY VALUES  DISPLAY VALUES

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

        String getindicators = "select * from indicatortitles where  active='yes' and inppmp='yes' order by  tableNo,output   ";

        dbConnect conn = new dbConnect();

        conn.rs = conn.state.executeQuery(getindicators);
        int rownumber = 3;

        shet.setColumnWidth(1, 20000);
        shet.setColumnWidth(2, 2300);
        shet.setColumnWidth(0, 2100);
        shet.setColumnWidth(3, 2500);
        shet.setColumnWidth(4, 2500);
        shet.setColumnWidth(5, 2500);
        shet.setColumnWidth(6, 2500);
        shet.setColumnWidth(7, 2500);
        shet.setColumnWidth(8, 2500);
        shet.setColumnWidth(9, 2500);
        shet.setColumnWidth(10, 2500);
        shet.setColumnWidth(11, 2500);
        shet.setColumnWidth(12, 2500);
        shet.setColumnWidth(13, 2500);
        shet.setColumnWidth(14, 2500);
        ArrayList sp = new ArrayList();
        int subpurposerow = 3;
        int subpurposerowcopy = 3;

        ArrayList op = new ArrayList();
        int outputrow = 3;
        int outputrowcopy = 4;
        int colpos = 0;
        int count = 0;
        int rowgani = 1;
        while (conn.rs.next()) {
            System.out.println("SP__" + conn.rs.getString("output"));
            //merge subpartner row
            sp.add(conn.rs.getString("output"));

            if (sp.size() > 1) {
                //check if subporpose has changed
                if (!sp.get(count).toString().equals(sp.get(count - 1).toString())) {

                    subpurposerow = rownumber;

                    //===================================================subpurpose========================

                    HSSFRow rwxa = shet.createRow(rownumber);
                    rwxa.setHeightInPoints(25);
                    HSSFCell cl01 = rwxa.createCell(colpos);
                    cl01.setCellValue(conn.rs.getString("output"));
                    cl01.setCellStyle(spstyle);

                    subpurposerowcopy = subpurposerow;
                    //should merge entire row
                    shet.addMergedRegion(
                            new CellRangeAddress(subpurposerow, subpurposerow, 0, selectedyear - 2009));

                    rownumber++;
                }

            }

            else {

                subpurposerow = rownumber;

                //===================================================subpurpose========================

                HSSFRow rwxa = shet.createRow(rownumber);
                rwxa.setHeightInPoints(25);
                HSSFCell cl01 = rwxa.createCell(colpos);
                cl01.setCellValue(conn.rs.getString("output"));
                cl01.setCellStyle(spstyle);

                subpurposerowcopy = subpurposerow;
                //should merge entire row
                shet.addMergedRegion(
                        new CellRangeAddress(subpurposerow, subpurposerow, 0, selectedyear - 2009));

                rownumber++;

            }
            String outputval = "";

            if (conn.rs.getString("output") != null) {
                outputval = conn.rs.getString("output");
            }

            //merge ouput rows
            op.add(outputval);
            if (op.size() > 1) {
                //check if out has changed
                if (!op.get(count).toString().equals(op.get(count - 1).toString())) {

                    outputrow = rownumber;

                    //should merge
                    shet.addMergedRegion(new CellRangeAddress(outputrowcopy, outputrow - 1, 0, 0));
                    outputrowcopy = outputrow;
                    System.out.println(" Comparison :" + op.get(count).toString() + "  %%% "
                            + op.get(count - 1).toString());

                }

            }

            //now output the first part of the report

            HSSFRow rwx = shet.createRow(rownumber);

            //====================================================output============================= 
            HSSFCell cl02 = rwx.createCell(colpos);
            //  cl02.setCellValue(conn.rs.getString("output"));

            String tn = conn.rs.getString("tableno");

            if (!tn.contains(".")) {
                if (isNumeric(tn)) {
                    cl02.setCellValue(new Integer(tn));
                } else {
                    cl02.setCellValue(tn);

                }

            } else {
                cl02.setCellValue(tn);
            }
            cl02.setCellStyle(style2);

            colpos++;

            //===================================================indicators===========================
            HSSFCell cl03 = rwx.createCell(colpos);
            cl03.setCellValue(conn.rs.getString("title"));
            cl03.setCellStyle(style2);
            colpos++;
            //====================================================baseline=============================
            HSSFCell cl04 = rwx.createCell(colpos);
            cl04.setCellValue(conn.rs.getString("totalbaseline"));
            cl04.setCellStyle(style2);
            colpos++;
            //====================================================targets=================================
            String gettargets = " select sum(target_combined) as target from yearly_targets where indicator_id='"
                    + conn.rs.getString("titleID") + "' and year='" + selectedyear + "' ";

            //for percent indicators, get avg
            if (conn.rs.getInt("percentage") == 1) {

                gettargets = "select avg(target_combined) as target from yearly_targets where indicator_id='"
                        + conn.rs.getString("titleID") + "'  and year='" + selectedyear + "' ";

            }

            HSSFCell cl05 = rwx.createCell(colpos);
            colpos++;
            int annualtarget = 1;

            conn.rs1 = conn.state1.executeQuery(gettargets);
            if (conn.rs1.next()) {
                //set the target
                cl05.setCellValue(conn.rs1.getInt("target"));
                if (conn.rs.getInt("percentage") == 1) {
                    if (conn.rs1.getInt("target") < 200) {
                        cl05.setCellValue(conn.rs1.getInt("target") + "%");

                    } else {
                        cl05.setCellValue(conn.rs1.getInt("target"));
                    }
                } else {
                    cl05.setCellValue(conn.rs1.getInt("target"));
                }

                cl05.setCellStyle(style2);
                if (conn.rs1.getString("target") != null) {
                    if (!conn.rs1.getString("target").equals("")) {

                        annualtarget = conn.rs1.getInt("target");

                    }
                }

            }

            //===========================================current year values====================================

            String ispercent = "";

            int highestvalue = 0;
            String getdata = " select sum(case  when  reportingPeriod='Q1' then totalAchieved end) as Q1, sum(case  when  reportingPeriod='Q2' then totalAchieved end) as Q2, sum(case  when  reportingPeriod='Q3' then totalAchieved end) as Q3, sum(case  when  reportingPeriod='Q4' then totalAchieved end) as Q4  where titleID='"
                    + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                    + "' group by titleID ";

            //for percent indicators, get avg
            if (conn.rs.getInt("percentage") == 1) {
                ispercent = "%";
                if (conn.rs.getString("tableIdentifier").equals("1")) {
                    //by gender and thus separate columns
                    if (selectedyear >= 2018) {
                        getdata = " select  ROUND((sum(case  when  reportingPeriod='Q1' then ((men_numerator + women_numerator)) end)/sum(case  when  reportingPeriod='Q1' then ((men_denominator + women_denominator)) end))*100 ) as Q1, ROUND((sum(case  when  reportingPeriod='Q2' then ((men_numerator + women_numerator)) end)/sum(case  when  reportingPeriod='Q2' then ((men_denominator + women_denominator)) end))*100 ) as Q2, ROUND((sum(case  when  reportingPeriod='Q3' then ((men_numerator + women_numerator)) end)/sum(case  when  reportingPeriod='Q3' then ((men_denominator + women_denominator)) end))*100 ) as Q3, ROUND((sum(case  when  reportingPeriod='Q4' then ((men_numerator + women_numerator)) end)/sum(case  when  reportingPeriod='Q4' then ((men_denominator + women_denominator)) end))*100 ) as Q4 from indicatorachieved   where titleID='"
                                + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                                + "' group by titleID ";
                        System.out.println("@@" + getdata);
                    }

                    else {
                        getdata = " select  ROUND(AVG(case  when  reportingPeriod='Q1' then ((menAchieved + womenAchieved)/2) end)) as Q1, ROUND(AVG(case  when  reportingPeriod='Q2' then ((menAchieved + womenAchieved)/2) end)) as Q2, ROUND(AVG(case  when  reportingPeriod='Q3' then ((menAchieved + womenAchieved)/2) end)) as Q3, ROUND(AVG(case  when  reportingPeriod='Q4' then ((menAchieved + womenAchieved)/2) end)) as Q4 from indicatorachieved   where titleID='"
                                + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                                + "' group by titleID ";

                    }
                }

                else {
                    //combined i.e male and female
                    if (selectedyear >= 2018) {
                        getdata = "select ROUND((SUM(case  when  reportingPeriod='Q1' then numerator end)/SUM(case  when  reportingPeriod='Q1' then denominator end))*100) as Q1  , ROUND((SUM(case  when  reportingPeriod='Q2' then numerator end)/SUM(case  when  reportingPeriod='Q2' then denominator end))*100) as Q2, ROUND((SUM(case  when  reportingPeriod='Q3' then numerator end)/SUM(case  when  reportingPeriod='Q3' then denominator end))*100) as Q3, ROUND((SUM(case  when  reportingPeriod='Q4' then numerator end)/SUM(case  when  reportingPeriod='Q4' then denominator end))*100) as Q4   from indicatorachievedcombined    where titleID='"
                                + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                                + "' group by titleID ";
                    } else {
                        //use old way of averages
                        getdata = " select ROUND(AVG(case  when  reportingPeriod='Q1' then totalAchieved end)) as Q1,ROUND(AVG(case  when  reportingPeriod='Q2' then totalAchieved end)) as Q2, ROUND(AVG(case  when  reportingPeriod='Q3' then totalAchieved end)) as Q3, ROUND(AVG(case  when  reportingPeriod='Q4' then totalAchieved end)) as Q4  from indicatorachievedcombined    where titleID='"
                                + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                                + "' group by titleID ";

                    }
                    System.out.println("@@" + getdata);

                }
            }
            //non percentages
            else {
                //if 
                if (conn.rs.getString("tableIdentifier").equals("1")) {
                    //by gender and thus separate columns
                    getdata = " select  sum(case  when  reportingPeriod='Q1' then (menAchieved + womenAchieved) end) as Q1,sum(case  when  reportingPeriod='Q2' then (menAchieved + womenAchieved) end) as Q2, sum(case  when  reportingPeriod='Q3' then (menAchieved + womenAchieved) end) as Q3, sum(case  when  reportingPeriod='Q4' then (menAchieved + womenAchieved) end) as Q4 from indicatorachieved  where titleID='"
                            + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                            + "' group by titleID ";

                } else {

                    getdata = " select sum(case  when  reportingPeriod='Q1' then totalAchieved end) as Q1, sum(case  when  reportingPeriod='Q2' then totalAchieved end) as Q2, sum(case  when  reportingPeriod='Q3' then totalAchieved end) as Q3, sum(case  when  reportingPeriod='Q4' then totalAchieved end) as Q4 from indicatorachievedcombined  where titleID='"
                            + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                            + "' group by titleID ";

                }

            }

            String Q1 = "";
            String Q2 = "";
            String Q3 = "";
            String Q4 = "";

            conn.rs1 = conn.state1.executeQuery(getdata);

            //Q1

            HSSFCell clQ1 = rwx.createCell(colpos);
            colpos++;
            HSSFCell clQ2 = rwx.createCell(colpos);
            colpos++;
            HSSFCell clQ3 = rwx.createCell(colpos);
            colpos++;
            HSSFCell clQ4 = rwx.createCell(colpos);
            colpos++;

            if (conn.rs1.next()) {

                if (conn.rs1.getString("Q1") != null) {
                    if (!conn.rs1.getString("Q1").equals("")) {
                        highestvalue = conn.rs1.getInt("Q1");
                        if (!ispercent.equals("")) {

                            clQ1.setCellValue(conn.rs1.getInt("Q1") + ispercent);

                        } else {
                            clQ1.setCellValue(conn.rs1.getInt("Q1"));
                        }

                    }
                }

                if (conn.rs1.getString("Q2") != null) {
                    if (!conn.rs1.getString("Q2").equals("")) {
                        if (conn.rs1.getInt("Q2") > highestvalue) {
                            highestvalue = conn.rs1.getInt("Q2");
                        }
                        if (!ispercent.equals("")) {
                            clQ2.setCellValue(conn.rs1.getInt("Q2") + ispercent);

                        } else {
                            clQ2.setCellValue(conn.rs1.getInt("Q2"));
                        }

                    }
                }

                if (conn.rs1.getString("Q3") != null) {
                    if (!conn.rs1.getString("Q3").equals("")) {

                        if (conn.rs1.getInt("Q3") > highestvalue) {
                            highestvalue = conn.rs1.getInt("Q3");
                        }
                        if (!ispercent.equals("")) {
                            clQ3.setCellValue(conn.rs1.getInt("Q3") + ispercent);
                        } else {
                            clQ3.setCellValue(conn.rs1.getInt("Q3"));
                        }

                    }
                }

                if (conn.rs1.getString("Q4") != null) {
                    if (!conn.rs1.getString("Q4").equals("")) {
                        if (conn.rs1.getInt("Q4") > highestvalue) {
                            highestvalue = conn.rs1.getInt("Q4");
                        }
                        if (!ispercent.equals("")) {
                            clQ4.setCellValue(conn.rs1.getInt("Q4") + ispercent);
                        } else {
                            clQ4.setCellValue(conn.rs1.getInt("Q4"));
                        }

                    }
                }

            }

            clQ2.setCellStyle(style2);
            clQ1.setCellStyle(style2);
            clQ3.setCellStyle(style2);
            clQ4.setCellStyle(style2);

            //====================================Annual figures=======================  
            String percentageachievement = "";
            String achievednonpercent = "No target / achieved value";
            int curcol = colpos;
            String annualispercent = "";

            int currentyearvalue = 0;
            int currentyearhighestqtr = 0;
            for (int yearval = selectedyear; yearval >= projectstartyear; yearval--) {

                HSSFCell clx = rwx.createCell(curcol);

                // System.out.println("******"+curcol);
                //separate cumulates + average with the rest
                if (conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Cumulative")
                        || conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Average")) {
                    String qry = "";

                    if (conn.rs.getString("percentage").equals("1"))

                    {
                        annualispercent = "%";
                        if (conn.rs.getString("tableidentifier").equals("2")) {
                            //no gender thus its combined 
                            if (yearval >= 2018) {

                                qry = " select ROUND((SUM(case  when  financialYear='" + yearval
                                        + "' then numerator end)/SUM(case  when   financialYear='" + yearval
                                        + "' then denominator end))*100)  as y" + yearval
                                        + " from indicatorachievedcombined where financialyear='" + yearval
                                        + "' and titleID='" + conn.rs.getString("titleID")
                                        + "' group by titleID";

                            } else {
                                qry = " select ROUND(AVG(totalAchieved))  as y" + yearval
                                        + " from indicatorachievedcombined where financialyear='" + yearval
                                        + "' and titleID='" + conn.rs.getString("titleID")
                                        + "' group by titleID";

                            }

                        } else {

                            if (yearval >= 2018) {

                                qry = " select ROUND((sum(case  when  financialYear='" + yearval
                                        + "' then ((men_numerator + women_numerator)) end)/sum(case  when  financialYear='"
                                        + yearval
                                        + "' then ((men_denominator + women_denominator)) end))*100)  as y"
                                        + yearval + " from indicatorachieved where financialyear='" + yearval
                                        + "' and titleID='" + conn.rs.getString("titleID")
                                        + "' group by titleID";
                            } else {

                                qry = " select ROUND(AVG((menAchieved + womenAchieved)/2))  as y" + yearval
                                        + " from indicatorachieved where financialyear='" + yearval
                                        + "' and titleID='" + conn.rs.getString("titleID")
                                        + "' group by titleID";

                            }

                        }

                    }

                    //non percents
                    else {
                        //for cumulatives
                        //check tabletype
                        //1 is by gender

                        //_____________CUMULATIVES______________

                        if (conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Cumulative")) {

                            if (conn.rs.getString("tableIdentifier").equals("1")) {

                                qry = " select sum((menAchieved + womenAchieved)) as y" + yearval
                                        + " from indicatorachieved where financialyear='" + yearval
                                        + "' and titleID='" + conn.rs.getString("titleID")
                                        + "' group by titleID";

                            }

                            else {

                                qry = " select sum(totalAchieved) as y" + yearval
                                        + " from indicatorachievedcombined where financialyear='" + yearval
                                        + "' and titleID='" + conn.rs.getString("titleID")
                                        + "' group by titleID";

                            } //end of else of table identifier

                        } //end of sum/cumulatives
                        else {

                            System.out.println("failed:" + conn.rs.getString("cumulative_chooser") + " *** "
                                    + conn.rs.getString("title"));

                        }

                    } //end of else of non percents

                    System.out.println("@ annual query" + qry);

                    conn.rs1 = conn.state1.executeQuery(qry);

                    if (conn.rs1.next()) {

                        // System.out.println("__"+conn.rs1.getString(1));

                        if (conn.rs1.getString(1) != null) {
                            if (!conn.rs1.getString(1).equals("")) {
                                if (annualispercent.equals("")) {

                                    clx.setCellValue(conn.rs1.getInt(1));
                                    //achieved nonpercentage
                                    if (yearval == selectedyear) {

                                        if (annualtarget > 1) {
                                            achievednonpercent = ""
                                                    + (int) (((double) conn.rs1.getDouble(1) * 100)
                                                            / (double) annualtarget)
                                                    + "%";

                                            //System.out.println("For id "+conn.rs.getString("titleID")+" "+achievednonpercent);

                                        }
                                    }

                                } else {
                                    clx.setCellValue(conn.rs1.getInt(1) + annualispercent);
                                    //do this for the cureent year
                                    if (yearval == selectedyear) {
                                        percentageachievement = conn.rs1.getInt(1) + annualispercent;

                                    }
                                }

                            }
                        }
                    }
                    clx.setCellStyle(style2);

                } //end of cumulatives and percentages

                else if (conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Highest")) {
                    String qry = "";

                    if (conn.rs.getString("tableIdentifier").equals("1")) {
                        //by gender and thus separate columns
                        qry = " select  sum(case  when  reportingPeriod='Q1' then (menAchieved + womenAchieved) end) as Q1,sum(case  when  reportingPeriod='Q2' then (menAchieved + womenAchieved) end) as Q2, sum(case  when  reportingPeriod='Q3' then (menAchieved + womenAchieved) end) as Q3, sum(case  when  reportingPeriod='Q4' then (menAchieved + womenAchieved) end) as Q4 from indicatorachieved  where titleID='"
                                + conn.rs.getString("titleID") + "' and financialyear='" + yearval
                                + "' group by titleID ";

                    } else {

                        qry = " select sum(case  when  reportingPeriod='Q1' then totalAchieved end) as Q1, sum(case  when  reportingPeriod='Q2' then totalAchieved end) as Q2, sum(case  when  reportingPeriod='Q3' then totalAchieved end) as Q3, sum(case  when  reportingPeriod='Q4' then totalAchieved end) as Q4 from indicatorachievedcombined  where titleID='"
                                + conn.rs.getString("titleID") + "' and financialyear='" + yearval
                                + "' group by titleID ";

                    }
                    int highestqtr = 0;
                    //excecute query
                    conn.rs1 = conn.state1.executeQuery(qry);
                    while (conn.rs1.next()) {
                        //

                        if (conn.rs1.getString("Q1") != null) {
                            if (!conn.rs1.getString("Q1").equals("")) {
                                if (conn.rs1.getInt("Q1") > highestqtr) {
                                    highestqtr = conn.rs1.getInt("Q1");
                                }
                            }
                        } else if (conn.rs1.getString("Q2") != null) {
                            if (!conn.rs1.getString("Q2").equals("")) {
                                if (conn.rs1.getInt("Q2") > highestqtr) {
                                    highestqtr = conn.rs1.getInt("Q2");
                                }
                            }
                        }

                        else if (conn.rs1.getString("Q3") != null) {
                            if (!conn.rs1.getString("Q3").equals("")) {
                                if (conn.rs1.getInt("Q3") > highestqtr) {
                                    highestqtr = conn.rs1.getInt("Q3");
                                }
                            }
                        }

                        else if (conn.rs1.getString("Q4") != null) {
                            if (!conn.rs1.getString("Q4").equals("")) {
                                if (conn.rs1.getInt("Q4") > highestqtr) {
                                    highestqtr = conn.rs1.getInt("Q4");
                                }
                            }
                        }

                    }
                    if (highestqtr > 0) {
                        clx.setCellValue(highestqtr);

                    } else {
                        clx.setCellValue("");
                    }

                    //achieved nonpercentage
                    if (yearval == selectedyear) {

                        if (annualtarget != 1) {
                            achievednonpercent = "" + (int) highestqtr * 100 / (int) annualtarget + "%";

                            System.out.println(highestqtr + " / " + annualtarget + "___"
                                    + (int) highestqtr * 100 / (int) (annualtarget) + "%");
                        }
                    }

                    clx.setCellStyle(style2);

                } //   end of highest 

                else if (conn.rs.getString("cumulative_chooser").equalsIgnoreCase("OLMIS")
                        || conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Last Reported")) {

                    String qry = "";
                    //get data for the last input quarter
                    if (yearval == selectedyear) {
                        //get data for that quarter

                        if (conn.rs.getString("tableidentifier").equals("2")) {
                            //no gender
                            qry = " select sum((totalAchieved)) as y" + yearval
                                    + " from indicatorachievedcombined where financialyear='" + yearval
                                    + "' and reportingPeriod='" + selectedQTR + "' and  titleID='"
                                    + conn.rs.getString("titleID") + "' group by titleID";

                        } else {

                            qry = " select sum((menAchieved + womenAchieved)) as y" + yearval
                                    + " from indicatorachieved where financialyear='" + yearval
                                    + "' and reportingPeriod='" + selectedQTR + "' and  titleID='"
                                    + conn.rs.getString("titleID") + "' group by titleID";

                        }

                    }

                    else {

                        if (conn.rs.getString("tableidentifier").equals("2")) {
                            //no gender
                            qry = " select sum((totalAchieved)) as y" + yearval
                                    + " from indicatorachievedcombined where financialyear='" + yearval
                                    + "' and reportingPeriod='Q4' and  titleID='" + conn.rs.getString("titleID")
                                    + "' group by titleID";

                        } else {
                            qry = " select sum((menAchieved + womenAchieved)) as y" + yearval
                                    + " from indicatorachieved where financialyear='" + yearval
                                    + "' and reportingPeriod='Q4' and  titleID='" + conn.rs.getString("titleID")
                                    + "' group by titleID";

                        }

                    }

                    //execute the query  
                    conn.rs1 = conn.state1.executeQuery(qry);

                    if (conn.rs1.next()) {
                        // System.out.println("__"+conn.rs1.getString(1));

                        if (conn.rs1.getString(1) != null) {
                            if (!conn.rs1.getString(1).equals("")) {

                                clx.setCellValue(conn.rs1.getInt(1));
                                //this is for percentage purpose
                                if (selectedyear == yearval) {
                                    currentyearvalue = conn.rs1.getInt(1);
                                }

                            }
                        }

                    }

                    //achieved nonpercentage
                    if (yearval == selectedyear) {

                        if (annualtarget != 1 && annualtarget != 0) {
                            achievednonpercent = "" + (((int) currentyearvalue * 100) / (int) annualtarget)
                                    + "%";
                        }
                    }

                    clx.setCellStyle(style2);

                } //end of olmis and last reported indicators

                curcol++;

            } //end of for loop
            HSSFCell clx = rwx.createCell(curcol);

            if (conn.rs.getInt("percentage") == 1) {

                clx.setCellValue(percentageachievement);

            } else {
                clx.setCellValue(achievednonpercent);

            }

            clx.setCellStyle(style2);
            rwx.setHeightInPoints(42);

            rownumber++;
            count++;
            colpos = 0;
        }

        for (int e = 0; e < 13; e++) {
            //shet.getRow(rowgani).autoSizeColumn(e,true);
        }
        //shet.autoSizeColumn(1,false);

        //Made my life veery simple...
        shet.setDisplayGridlines(false);
        shet.createFreezePane(2, 3);

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

        // 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=PPMPREPORT_" + selectedyear + "_"
                + selectedQTR + "_gen_on_" + generationtime + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();

    } finally {

    }
}

From source file:PPMP.ppmpreport_2.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    response.setContentType("text/html;charset=UTF-8");

    try {/* ww w  .ja  v a  2 s  . c om*/
        /* TODO output your page here. You may use following sample code. */

        //create ppmp report here

        //define some variables for keeping number of columns. 
        // this should be dynamic because of the annual cumulatives depending on the selected year
        //the minimum year is 2011
        //
        int selectedyear = 2016;
        int projectstartyear = 2011;
        int minimumcolumns = 11;//this is if the year is 2011
        int currentcolumns = minimumcolumns + (selectedyear - projectstartyear);
        String selectedQTR = "Q2";

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

            selectedyear = new Integer(request.getParameter("year"));

        }

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

            selectedQTR = request.getParameter("quarter");

        }

        HSSFWorkbook wb = new HSSFWorkbook();

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        String month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        String date = String.format("%02d", cal.get(Calendar.DATE));
        String hour = String.format("%02d", cal.get(Calendar.HOUR_OF_DAY));
        String min = String.format("%02d", cal.get(Calendar.MINUTE));
        String sec = String.format("%02d", cal.get(Calendar.SECOND));

        String generationtime = "(" + year + "_" + month + "_" + date + ")_" + hour + "-" + min + "-" + sec;

        //______________________________________________________________________________________
        //______________________________________________________________________________________

        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setFontName("Arial Narrow");
        font.setColor((short) 0000);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setBorderTop(HSSFCellStyle.BORDER_THICK);
        style.setBorderBottom(HSSFCellStyle.BORDER_THICK);
        style.setBorderLeft(HSSFCellStyle.BORDER_THICK);
        style.setBorderRight(HSSFCellStyle.BORDER_THICK);
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setWrapText(true);

        CellStyle spstyle = wb.createCellStyle();
        spstyle.setFont(font);
        spstyle.setBorderTop(HSSFCellStyle.BORDER_THICK);
        spstyle.setBorderBottom(HSSFCellStyle.BORDER_THICK);
        spstyle.setBorderLeft(HSSFCellStyle.BORDER_THICK);
        spstyle.setBorderRight(HSSFCellStyle.BORDER_THICK);
        spstyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        spstyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
        spstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        spstyle.setWrapText(true);
        System.out.println("Blue index:" + HSSFColor.BLUE.index);

        HSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THICK);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THICK);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THICK);
        style2.setBorderRight(HSSFCellStyle.BORDER_THICK);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style2.setWrapText(true);

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

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

        HSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Arial Narrow");
        fontx.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        fontx.setFontHeightInPoints((short) 16);
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        HSSFSheet shet = wb.createSheet("PPMP " + selectedyear + " Report ");

        //create headers for that worksheet

        HSSFRow rw = shet.createRow(0);
        rw.setHeightInPoints(25);
        HSSFCell cl0 = rw.createCell(0);
        cl0.setCellValue("PROJECT PERFORMANCE MONITORING PLAN (PPMP)");
        cl0.setCellStyle(stylex);

        for (int a = 1; a < currentcolumns; a++) {
            HSSFCell clx = rw.createCell(a);
            clx.setCellValue("");
            clx.setCellStyle(stylex);
        }
        //merge row one

        shet.addMergedRegion(new CellRangeAddress(0, 0, 0, currentcolumns - 1));

        //firt row

        ArrayList headerone = new ArrayList();
        //headerone.add("Sub Purpose");
        headerone.add("Output");
        headerone.add("Indicators");
        headerone.add("Baseline");
        headerone.add("Year " + selectedyear + " Target");
        headerone.add(selectedyear + " Quarterly Achievements ");
        headerone.add("");
        headerone.add("");
        headerone.add("");
        headerone.add("Cumulative Year Achievements");
        //the header Cumulative Year Achievements could be in the report depending on the selected year
        //for 2011, its not expected to appear in the report

        for (int a = 0; a <= (selectedyear - projectstartyear); a++) {
            if (a == 0) {
                //do nothing 
            } else {
                headerone.add("");
            }

        }

        headerone.add("Percentage (%) Achieved vs Year " + selectedyear);

        //header two which contains quartersa dn yearly achievement

        ArrayList headertwo = new ArrayList();
        //headertwo.add("Sub Purpose");
        headertwo.add("Output");
        headertwo.add("Indicators");
        headertwo.add("Baseline");
        headertwo.add("");
        headertwo.add("Oct-Dec " + (selectedyear - 1));
        headertwo.add("Jan-Mar");
        headertwo.add("Apr-Jun");
        headertwo.add("Jul-Sep");
        headertwo.add(selectedyear);
        //the header Cumulative Year Achievements could be in the report depending on the selected year
        //for 2011, its not expected to appear in the report

        for (int a = 0; a <= (selectedyear - projectstartyear); a++) {
            if (a == 0) {
                //do nothing 
            } else {
                headertwo.add(selectedyear - a);
                //eg 2016, 2015, 2014 ...
            }

        }

        headertwo.add("");

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

        //DISPLAY HEADER   DISPLAY HEADER   DISPLAY HEADER   DISPLAY HEADER  DISPLAY HEADER

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

        //display the header values for row one and two
        HSSFRow rw1 = shet.createRow(1);
        for (int a = 0; a < headerone.size(); a++) {
            HSSFCell cellx = rw1.createCell(a);

            cellx.setCellValue(headerone.get(a).toString());
            cellx.setCellStyle(style);
            shet.setColumnWidth(a, 3500);

        }

        //===================row 2=======================

        //display the header values for row one and two
        HSSFRow rw2 = shet.createRow(2);
        rw2.setHeightInPoints(35);
        for (int a = 0; a < headertwo.size(); a++) {
            HSSFCell cellx = rw2.createCell(a);

            if (headertwo.get(a).toString().startsWith("20")) {

                cellx.setCellValue(new Integer(headertwo.get(a).toString()));
            } else {
                cellx.setCellValue(headertwo.get(a).toString());
            }

            cellx.setCellStyle(style);

        }

        // shet.addMergedRegion(new CellRangeAddress(start row, end row, start column ,end column));   
        String mergingarray[] = { "1_2_0_0", "1_2_1_1", "1_2_2_2", "1_2_3_3", "1_1_4_7",
                "1_1_8_" + (8 + (selectedyear - projectstartyear)),
                "1_2_" + (8 + (selectedyear - projectstartyear) + 1) + "_"
                        + (8 + (selectedyear - projectstartyear) + 1) };

        for (int a = 0; a < mergingarray.length; a++) {

            String content[] = mergingarray[a].split("_");

            shet.addMergedRegion(new CellRangeAddress(new Integer(content[0]), new Integer(content[1]),
                    new Integer(content[2]), new Integer(content[3])));

        }

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

        //DISPLAY VALUES    DISPLAY VALUES    DISPLAY VALUES   DISPLAY VALUES  DISPLAY VALUES

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

        String getindicators = "select * from indicatortitles where  active='yes' order by subpurpose, output , title ";

        dbConnect conn = new dbConnect();

        conn.rs = conn.state.executeQuery(getindicators);
        int rownumber = 3;

        shet.setColumnWidth(1, 14000);
        shet.setColumnWidth(2, 2300);
        shet.setColumnWidth(0, 7000);
        shet.setColumnWidth(3, 2300);
        shet.setColumnWidth(4, 2300);
        shet.setColumnWidth(5, 2300);
        shet.setColumnWidth(6, 2300);
        shet.setColumnWidth(7, 2300);
        shet.setColumnWidth(8, 2300);
        shet.setColumnWidth(9, 2300);
        shet.setColumnWidth(10, 2300);
        shet.setColumnWidth(11, 2300);
        shet.setColumnWidth(12, 2300);
        shet.setColumnWidth(13, 2300);
        shet.setColumnWidth(14, 2300);
        ArrayList sp = new ArrayList();
        int subpurposerow = 3;
        int subpurposerowcopy = 3;

        ArrayList op = new ArrayList();
        int outputrow = 3;
        int outputrowcopy = 4;
        int colpos = 0;
        int count = 0;

        while (conn.rs.next()) {
            System.out.println("SP__" + conn.rs.getString("subpurpose"));
            //merge subpartner row
            sp.add(conn.rs.getString("subpurpose"));
            if (sp.size() > 1) {
                //check if subporpose has changed
                if (!sp.get(count).toString().equals(sp.get(count - 1).toString())) {

                    subpurposerow = rownumber;

                    //===================================================subpurpose========================

                    HSSFRow rwxa = shet.createRow(rownumber);

                    HSSFCell cl01 = rwxa.createCell(colpos);
                    cl01.setCellValue(conn.rs.getString("subpurpose"));
                    cl01.setCellStyle(spstyle);

                    subpurposerowcopy = subpurposerow;
                    //should merge entire row
                    shet.addMergedRegion(new CellRangeAddress(subpurposerow, subpurposerow, 0, 15));

                    rownumber++;
                }

            }

            else {

                subpurposerow = rownumber;

                //===================================================subpurpose========================

                HSSFRow rwxa = shet.createRow(rownumber);

                HSSFCell cl01 = rwxa.createCell(colpos);
                cl01.setCellValue(conn.rs.getString("subpurpose"));
                cl01.setCellStyle(spstyle);

                subpurposerowcopy = subpurposerow;
                //should merge entire row
                shet.addMergedRegion(new CellRangeAddress(subpurposerow, subpurposerow, 0, 15));

                rownumber++;

            }
            String outputval = "";

            if (conn.rs.getString("output") != null) {
                outputval = conn.rs.getString("output");
            }

            //merge ouput rows
            op.add(outputval);
            if (op.size() > 1) {
                //check if out has changed
                if (!op.get(count).toString().equals(op.get(count - 1).toString())) {

                    outputrow = rownumber;

                    //should merge
                    shet.addMergedRegion(new CellRangeAddress(outputrowcopy, outputrow - 1, 0, 0));
                    outputrowcopy = outputrow;
                    System.out.println(" Comparison :" + op.get(count).toString() + "  %%% "
                            + op.get(count - 1).toString());

                }

            }

            //now output the first part of the report

            HSSFRow rwx = shet.createRow(rownumber);

            //====================================================output============================= 
            HSSFCell cl02 = rwx.createCell(colpos);
            cl02.setCellValue(conn.rs.getString("output"));
            cl02.setCellStyle(style2);

            colpos++;

            //===================================================indicators===========================
            HSSFCell cl03 = rwx.createCell(colpos);
            cl03.setCellValue(conn.rs.getString("title"));
            cl03.setCellStyle(style2);
            colpos++;
            //====================================================baseline=============================
            HSSFCell cl04 = rwx.createCell(colpos);
            cl04.setCellValue(conn.rs.getString("totalbaseline"));
            cl04.setCellStyle(style2);
            colpos++;
            //====================================================targets=================================
            String gettargets = " select sum(target_combined) as target from yearly_targets where indicator_id='"
                    + conn.rs.getString("titleID") + "' and year='" + selectedyear + "' ";

            //for percent indicators, get avg
            if (conn.rs.getInt("percentage") == 1) {

                gettargets = "select avg(target_combined) as target from yearly_targets where indicator_id='"
                        + conn.rs.getString("titleID") + "'  and year='" + selectedyear + "' ";

            }

            HSSFCell cl05 = rwx.createCell(colpos);
            colpos++;
            int annualtarget = 1;

            conn.rs1 = conn.state1.executeQuery(gettargets);
            if (conn.rs1.next()) {
                //set the target
                cl05.setCellValue(conn.rs1.getInt("target"));
                if (conn.rs.getInt("percentage") == 1) {
                    if (conn.rs1.getInt("target") < 200) {
                        cl05.setCellValue(conn.rs1.getInt("target") + "%");

                    } else {
                        cl05.setCellValue(conn.rs1.getInt("target"));
                    }
                } else {
                    cl05.setCellValue(conn.rs1.getInt("target"));
                }

                cl05.setCellStyle(style2);
                if (conn.rs1.getString("target") != null) {
                    if (!conn.rs1.getString("target").equals("")) {

                        annualtarget = conn.rs1.getInt("target");

                    }
                }

            }

            //===========================================current year values====================================

            String ispercent = "";

            int highestvalue = 0;
            String getdata = " select sum(case  when  reportingPeriod='Q1' then totalAchieved end) as Q1, sum(case  when  reportingPeriod='Q2' then totalAchieved end) as Q2, sum(case  when  reportingPeriod='Q3' then totalAchieved end) as Q3, sum(case  when  reportingPeriod='Q4' then totalAchieved end) as Q4  where titleID='"
                    + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                    + "' group by titleID ";

            //for percent indicators, get avg
            if (conn.rs.getInt("percentage") == 1) {
                ispercent = "%";
                if (conn.rs.getString("tableIdentifier").equals("1")) {
                    //by gender and thus separate columns

                    getdata = " select  ROUND(AVG(case  when  reportingPeriod='Q1' then ((menAchieved + womenAchieved)/2) end)) as Q1, ROUND(AVG(case  when  reportingPeriod='Q2' then ((menAchieved + womenAchieved)/2) end)) as Q2, ROUND(AVG(case  when  reportingPeriod='Q3' then ((menAchieved + womenAchieved)/2) end)) as Q3, ROUND(AVG(case  when  reportingPeriod='Q4' then ((menAchieved + womenAchieved)/2) end)) as Q4 from indicatorachieved   where titleID='"
                            + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                            + "' group by titleID ";
                    System.out.println("@@" + getdata);

                }

                else {
                    //combined i.e male and female
                    getdata = " select ROUND(AVG(case  when  reportingPeriod='Q1' then totalAchieved end)) as Q1,ROUND(AVG(case  when  reportingPeriod='Q2' then totalAchieved end)) as Q2, ROUND(AVG(case  when  reportingPeriod='Q3' then totalAchieved end)) as Q3, ROUND(AVG(case  when  reportingPeriod='Q4' then totalAchieved end)) as Q4  from indicatorachievedcombined    where titleID='"
                            + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                            + "' group by titleID ";

                    System.out.println("@@" + getdata);
                }
            }
            //non percentages
            else {
                //if 
                if (conn.rs.getString("tableIdentifier").equals("1")) {
                    //by gender and thus separate columns
                    getdata = " select  sum(case  when  reportingPeriod='Q1' then (menAchieved + womenAchieved) end) as Q1,sum(case  when  reportingPeriod='Q2' then (menAchieved + womenAchieved) end) as Q2, sum(case  when  reportingPeriod='Q3' then (menAchieved + womenAchieved) end) as Q3, sum(case  when  reportingPeriod='Q4' then (menAchieved + womenAchieved) end) as Q4 from indicatorachieved  where titleID='"
                            + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                            + "' group by titleID ";

                } else {

                    getdata = " select sum(case  when  reportingPeriod='Q1' then totalAchieved end) as Q1, sum(case  when  reportingPeriod='Q2' then totalAchieved end) as Q2, sum(case  when  reportingPeriod='Q3' then totalAchieved end) as Q3, sum(case  when  reportingPeriod='Q4' then totalAchieved end) as Q4 from indicatorachievedcombined  where titleID='"
                            + conn.rs.getString("titleID") + "' and financialyear='" + selectedyear
                            + "' group by titleID ";

                }

            }

            String Q1 = "";
            String Q2 = "";
            String Q3 = "";
            String Q4 = "";

            conn.rs1 = conn.state1.executeQuery(getdata);

            //Q1

            HSSFCell clQ1 = rwx.createCell(colpos);
            colpos++;
            HSSFCell clQ2 = rwx.createCell(colpos);
            colpos++;
            HSSFCell clQ3 = rwx.createCell(colpos);
            colpos++;
            HSSFCell clQ4 = rwx.createCell(colpos);
            colpos++;

            if (conn.rs1.next()) {

                if (conn.rs1.getString("Q1") != null) {
                    if (!conn.rs1.getString("Q1").equals("")) {
                        highestvalue = conn.rs1.getInt("Q1");
                        if (!ispercent.equals("")) {

                            clQ1.setCellValue(conn.rs1.getInt("Q1") + ispercent);

                        } else {
                            clQ1.setCellValue(conn.rs1.getInt("Q1"));
                        }

                    }
                }

                if (conn.rs1.getString("Q2") != null) {
                    if (!conn.rs1.getString("Q2").equals("")) {
                        if (conn.rs1.getInt("Q2") > highestvalue) {
                            highestvalue = conn.rs1.getInt("Q2");
                        }
                        if (!ispercent.equals("")) {
                            clQ2.setCellValue(conn.rs1.getInt("Q2") + ispercent);

                        } else {
                            clQ2.setCellValue(conn.rs1.getInt("Q2"));
                        }

                    }
                }

                if (conn.rs1.getString("Q3") != null) {
                    if (!conn.rs1.getString("Q3").equals("")) {

                        if (conn.rs1.getInt("Q3") > highestvalue) {
                            highestvalue = conn.rs1.getInt("Q3");
                        }
                        if (!ispercent.equals("")) {
                            clQ3.setCellValue(conn.rs1.getInt("Q3") + ispercent);
                        } else {
                            clQ3.setCellValue(conn.rs1.getInt("Q3"));
                        }

                    }
                }

                if (conn.rs1.getString("Q4") != null) {
                    if (!conn.rs1.getString("Q4").equals("")) {
                        if (conn.rs1.getInt("Q4") > highestvalue) {
                            highestvalue = conn.rs1.getInt("Q4");
                        }
                        if (!ispercent.equals("")) {
                            clQ4.setCellValue(conn.rs1.getInt("Q4") + ispercent);
                        } else {
                            clQ4.setCellValue(conn.rs1.getInt("Q4"));
                        }

                    }
                }

            }

            clQ2.setCellStyle(style2);
            clQ1.setCellStyle(style2);
            clQ3.setCellStyle(style2);
            clQ4.setCellStyle(style2);

            //====================================Annual figures=======================  
            String percentageachievement = "";
            String achievednonpercent = "No target / achieved value";
            int curcol = colpos;
            String annualispercent = "";

            int currentyearvalue = 0;
            int currentyearhighestqtr = 0;
            for (int yearval = selectedyear; yearval >= projectstartyear; yearval--) {

                HSSFCell clx = rwx.createCell(curcol);

                // System.out.println("******"+curcol);
                //separate cumulates + average with the rest
                if (conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Cumulative")
                        || conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Average")) {
                    String qry = "";

                    if (conn.rs.getString("percentage").equals("1"))

                    {
                        annualispercent = "%";
                        if (conn.rs.getString("tableidentifier").equals("2")) {
                            //no gender thus its combined 

                            qry = " select ROUND(AVG(totalAchieved))  as y" + yearval
                                    + " from indicatorachievedcombined where financialyear='" + yearval
                                    + "' and titleID='" + conn.rs.getString("titleID") + "' group by titleID";

                        } else {

                            qry = " select ROUND(AVG((menAchieved + womenAchieved)/2))  as y" + yearval
                                    + " from indicatorachieved where financialyear='" + yearval
                                    + "' and titleID='" + conn.rs.getString("titleID") + "' group by titleID";

                        }

                    }

                    //non percents
                    else {
                        //for cumulatives
                        //check tabletype
                        //1 is by gender

                        //_____________CUMULATIVES______________

                        if (conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Cumulative")) {

                            if (conn.rs.getString("tableIdentifier").equals("1")) {

                                qry = " select sum((menAchieved + womenAchieved)) as y" + yearval
                                        + " from indicatorachieved where financialyear='" + yearval
                                        + "' and titleID='" + conn.rs.getString("titleID")
                                        + "' group by titleID";

                            }

                            else {

                                qry = " select sum(totalAchieved) as y" + yearval
                                        + " from indicatorachievedcombined where financialyear='" + yearval
                                        + "' and titleID='" + conn.rs.getString("titleID")
                                        + "' group by titleID";

                            } //end of else of table identifier

                        } //end of sum/cumulatives

                    } //end of else of non percents
                    System.out.println("@" + qry);

                    conn.rs1 = conn.state1.executeQuery(qry);

                    if (conn.rs1.next()) {

                        // System.out.println("__"+conn.rs1.getString(1));

                        if (conn.rs1.getString(1) != null) {
                            if (!conn.rs1.getString(1).equals("")) {
                                if (annualispercent.equals("")) {

                                    clx.setCellValue(conn.rs1.getInt(1));
                                    //achieved nonpercentage
                                    if (yearval == selectedyear) {

                                        if (annualtarget > 1) {
                                            achievednonpercent = ""
                                                    + (int) conn.rs1.getInt(1) * 100 / (int) annualtarget + "%";
                                        }
                                    }

                                } else {
                                    clx.setCellValue(conn.rs1.getInt(1) + annualispercent);
                                    //do this for the cureent year
                                    if (yearval == selectedyear) {
                                        percentageachievement = conn.rs1.getInt(1) + annualispercent;

                                    }
                                }

                            }
                        }
                    }
                    clx.setCellStyle(style2);

                } //end of cumulatives and percentages

                else if (conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Highest")) {
                    String qry = "";

                    if (conn.rs.getString("tableIdentifier").equals("1")) {
                        //by gender and thus separate columns
                        qry = " select  sum(case  when  reportingPeriod='Q1' then (menAchieved + womenAchieved) end) as Q1,sum(case  when  reportingPeriod='Q2' then (menAchieved + womenAchieved) end) as Q2, sum(case  when  reportingPeriod='Q3' then (menAchieved + womenAchieved) end) as Q3, sum(case  when  reportingPeriod='Q4' then (menAchieved + womenAchieved) end) as Q4 from indicatorachieved  where titleID='"
                                + conn.rs.getString("titleID") + "' and financialyear='" + yearval
                                + "' group by titleID ";

                    } else {

                        qry = " select sum(case  when  reportingPeriod='Q1' then totalAchieved end) as Q1, sum(case  when  reportingPeriod='Q2' then totalAchieved end) as Q2, sum(case  when  reportingPeriod='Q3' then totalAchieved end) as Q3, sum(case  when  reportingPeriod='Q4' then totalAchieved end) as Q4 from indicatorachievedcombined  where titleID='"
                                + conn.rs.getString("titleID") + "' and financialyear='" + yearval
                                + "' group by titleID ";

                    }
                    int highestqtr = 0;
                    //excecute query
                    conn.rs1 = conn.state1.executeQuery(qry);
                    while (conn.rs1.next()) {
                        //

                        if (conn.rs1.getString("Q1") != null) {
                            if (!conn.rs1.getString("Q1").equals("")) {
                                if (conn.rs1.getInt("Q1") > highestqtr) {
                                    highestqtr = conn.rs1.getInt("Q1");
                                }
                            }
                        } else if (conn.rs1.getString("Q2") != null) {
                            if (!conn.rs1.getString("Q2").equals("")) {
                                if (conn.rs1.getInt("Q2") > highestqtr) {
                                    highestqtr = conn.rs1.getInt("Q2");
                                }
                            }
                        }

                        else if (conn.rs1.getString("Q3") != null) {
                            if (!conn.rs1.getString("Q3").equals("")) {
                                if (conn.rs1.getInt("Q3") > highestqtr) {
                                    highestqtr = conn.rs1.getInt("Q3");
                                }
                            }
                        }

                        else if (conn.rs1.getString("Q4") != null) {
                            if (!conn.rs1.getString("Q4").equals("")) {
                                if (conn.rs1.getInt("Q4") > highestqtr) {
                                    highestqtr = conn.rs1.getInt("Q4");
                                }
                            }
                        }

                    }
                    if (highestqtr > 0) {
                        clx.setCellValue(highestqtr);

                    } else {
                        clx.setCellValue("");
                    }

                    //achieved nonpercentage
                    if (yearval == selectedyear) {

                        if (annualtarget != 1) {
                            achievednonpercent = "" + (int) highestqtr * 100 / (int) annualtarget + "%";

                            System.out.println(highestqtr + " / " + annualtarget + "___"
                                    + (int) highestqtr * 100 / (int) (annualtarget) + "%");
                        }
                    }

                    clx.setCellStyle(style2);

                } //   end of highest 

                else if (conn.rs.getString("cumulative_chooser").equalsIgnoreCase("OLMIS")
                        || conn.rs.getString("cumulative_chooser").equalsIgnoreCase("Last Reported")) {

                    String qry = "";
                    //get data for the last input quarter
                    if (yearval == selectedyear) {
                        //get data for that quarter

                        if (conn.rs.getString("tableidentifier").equals("2")) {
                            //no gender
                            qry = " select sum((totalAchieved)) as y" + yearval
                                    + " from indicatorachievedcombined where financialyear='" + yearval
                                    + "' and reportingPeriod='" + selectedQTR + "' and  titleID='"
                                    + conn.rs.getString("titleID") + "' group by titleID";

                        } else {

                            qry = " select sum((menAchieved + womenAchieved)) as y" + yearval
                                    + " from indicatorachieved where financialyear='" + yearval
                                    + "' and reportingPeriod='" + selectedQTR + "' and  titleID='"
                                    + conn.rs.getString("titleID") + "' group by titleID";

                        }

                    }

                    else {

                        if (conn.rs.getString("tableidentifier").equals("2")) {
                            //no gender
                            qry = " select sum((totalAchieved)) as y" + yearval
                                    + " from indicatorachievedcombined where financialyear='" + yearval
                                    + "' and reportingPeriod='Q4' and  titleID='" + conn.rs.getString("titleID")
                                    + "' group by titleID";

                        } else {
                            qry = " select sum((menAchieved + womenAchieved)) as y" + yearval
                                    + " from indicatorachieved where financialyear='" + yearval
                                    + "' and reportingPeriod='Q4' and  titleID='" + conn.rs.getString("titleID")
                                    + "' group by titleID";

                        }

                    }

                    //execute the query  
                    conn.rs1 = conn.state1.executeQuery(qry);

                    if (conn.rs1.next()) {
                        // System.out.println("__"+conn.rs1.getString(1));

                        if (conn.rs1.getString(1) != null) {
                            if (!conn.rs1.getString(1).equals("")) {

                                clx.setCellValue(conn.rs1.getInt(1));
                                //this is for percentage purpose
                                if (selectedyear == yearval) {
                                    currentyearvalue = conn.rs1.getInt(1);
                                }

                            }
                        }

                    }

                    //achieved nonpercentage
                    if (yearval == selectedyear) {

                        if (annualtarget != 1) {
                            achievednonpercent = "" + (int) currentyearvalue * 100 / (int) annualtarget + "%";
                        }
                    }

                    clx.setCellStyle(style2);

                } //end of olmis and last reported indicators

                curcol++;

            } //end of for loop
            HSSFCell clx = rwx.createCell(curcol);

            if (conn.rs.getInt("percentage") == 1) {

                clx.setCellValue(percentageachievement);

            } else {
                clx.setCellValue(achievednonpercent);

            }

            clx.setCellStyle(style2);
            rwx.setHeightInPoints(42);

            rownumber++;
            count++;
            colpos = 0;
        }

        for (int e = 0; e < 13; e++) {
            //shet.autoSizeColumn(e);
        }
        //Made my life veery simple...
        shet.setDisplayGridlines(false);
        shet.createFreezePane(2, 3);

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

        // 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=PPMPREPORT_" + selectedyear + "_"
                + selectedQTR + "_gen_on_" + generationtime + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();

    } finally {

    }
}

From source file:reports.barCharts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w ww. ja v  a  2s .co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        dbConn conn = new dbConn();

        wb = new HSSFWorkbook();

        HSSFSheet shet2 = null;

        String year = "";
        String site = "";
        String period = "";
        String cbo = "";
        String startdate = "2015-01-01";
        String enddate = "2015-03-30";

        startdate = request.getParameter("startdate");
        enddate = request.getParameter("enddate");

        //            year=request.getParameter("year");
        //site=request.getParameter("sitecbo");
        //period=request.getParameter("period");
        //cbo=request.getParameter("staffcbo");

        String sitename = "";
        String cboname = "";

        //begin a loop that will create as many reports as possible

        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setFontName("Cambria");
        //    font.setItalic(true);
        font.setBoldweight((short) 02);
        font.setColor(HSSFColor.BLACK.index);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setWrapText(true);
        style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

        style.setAlignment(style.ALIGN_CENTER);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        //%%%%%%%%%%%%%%%%HEADER FONTS AND COLORATION%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        HSSFFont font_header = wb.createFont();
        font_header.setFontHeightInPoints((short) 10);
        font_header.setFontName("Eras Bold ITC");
        //    font.setItalic(true);
        font_header.setBoldweight((short) 05);
        font_header.setColor(HSSFColor.BLACK.index);
        CellStyle style_header = wb.createCellStyle();
        style_header.setFont(font_header);
        style_header.setWrapText(true);
        style_header.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
        style_header.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style_header.setAlignment(style_header.ALIGN_CENTER);

        //            style_header.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //            style_header.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //            style_header.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //            style_header.setBorderLeft(HSSFCellStyle.BORDER_THIN);

        //%%%%%%%%%%%%%%%%%%%%%%%%%DATA FONT%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        //font data
        HSSFFont datafont = wb.createFont();
        datafont.setBoldweight((short) 03);
        datafont.setColor(HSSFColor.BLACK.index);
        datafont.setFontHeightInPoints((short) 10);
        datafont.setFontName("Cambria");
        datafont.setItalic(true);

        //bold font 
        HSSFFont bolfont = wb.createFont();

        bolfont.setBoldweight((short) 05);
        bolfont.setColor(HSSFColor.BLACK.index);
        bolfont.setFontHeightInPoints((short) 12);
        bolfont.setFontName("Cambria");

        //=========================ROW STYLE===============================

        HSSFCellStyle rowstyle = wb.createCellStyle();
        rowstyle.setWrapText(true);

        //=======INNER DATA STYLING===========================

        CellStyle innerdata_style = wb.createCellStyle();
        innerdata_style.setFont(datafont);
        innerdata_style.setWrapText(true);
        innerdata_style.setAlignment(innerdata_style.ALIGN_CENTER);
        innerdata_style.setFillForegroundColor(HSSFColor.WHITE.index);
        innerdata_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        innerdata_style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle lastcellrighborder = wb.createCellStyle();
        lastcellrighborder.setFont(datafont);
        lastcellrighborder.setWrapText(true);
        lastcellrighborder.setAlignment(lastcellrighborder.ALIGN_CENTER);
        lastcellrighborder.setFillForegroundColor(HSSFColor.WHITE.index);
        lastcellrighborder.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //            lastcellrighborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //            lastcellrighborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        lastcellrighborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //            lastcellrighborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        lastcellrighborder.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle innerdata_style2 = wb.createCellStyle();
        innerdata_style2.setFont(bolfont);
        innerdata_style2.setWrapText(true);
        innerdata_style2.setAlignment(innerdata_style.ALIGN_LEFT);
        innerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
        innerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        innerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle orangestyle = wb.createCellStyle();
        orangestyle.setFont(bolfont);
        orangestyle.setWrapText(true);
        orangestyle.setAlignment(orangestyle.ALIGN_CENTER);
        orangestyle.setFillForegroundColor(HSSFColor.ORANGE.index);
        orangestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //          innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //          innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //          innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //          innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        orangestyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        //Code colors

        CellStyle lg = wb.createCellStyle();
        lg.setFont(bolfont);
        lg.setWrapText(true);
        lg.setAlignment(lg.ALIGN_CENTER);
        lg.setFillForegroundColor(HSSFColor.GREEN.index);
        lg.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        lg.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        lg.setBorderTop(HSSFCellStyle.BORDER_THIN);
        lg.setBorderRight(HSSFCellStyle.BORDER_THIN);
        lg.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        lg.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle Y = wb.createCellStyle();
        Y.setFont(bolfont);
        Y.setWrapText(true);
        Y.setAlignment(Y.ALIGN_CENTER);
        Y.setFillForegroundColor(HSSFColor.WHITE.index);
        Y.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        Y.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        Y.setBorderTop(HSSFCellStyle.BORDER_THIN);
        Y.setBorderRight(HSSFCellStyle.BORDER_THIN);
        Y.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        Y.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle R = wb.createCellStyle();
        R.setFont(bolfont);
        R.setWrapText(true);
        R.setAlignment(R.ALIGN_CENTER);
        R.setFillForegroundColor(HSSFColor.RED.index);
        R.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        R.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        R.setBorderTop(HSSFCellStyle.BORDER_THIN);
        R.setBorderRight(HSSFCellStyle.BORDER_THIN);
        R.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        R.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        //=======INNER LEFT DATA STYLING===========================

        CellStyle binnerdata_style2 = wb.createCellStyle();
        binnerdata_style2.setFont(datafont);
        binnerdata_style2.setWrapText(true);
        binnerdata_style2.setAlignment(binnerdata_style2.ALIGN_LEFT);
        binnerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
        binnerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        binnerdata_style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        binnerdata_style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        binnerdata_style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        binnerdata_style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        binnerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //create a header

        //=======================Domainname styles
        CellStyle dnamestyle = wb.createCellStyle();
        dnamestyle.setFont(bolfont);
        dnamestyle.setWrapText(true);
        dnamestyle.setAlignment(dnamestyle.ALIGN_LEFT);
        dnamestyle.setFillForegroundColor(HSSFColor.WHITE.index);
        dnamestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        dnamestyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        dnamestyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        dnamestyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        dnamestyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        dnamestyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        shet2 = wb.createSheet("Column Charts Per Cbo");
        shet2.setColumnWidth(0, 12000);
        shet2.setColumnWidth(1, 12000);
        shet2.setColumnWidth(2, 4000);
        shet2.setColumnWidth(3, 10000);
        shet2.setColumnWidth(4, 5000);
        shet2.setColumnWidth(5, 5000);
        shet2.setColumnWidth(6, 5000);
        shet2.setColumnWidth(7, 5000);
        shet2.setColumnWidth(8, 5000);
        shet2.setColumnWidth(9, 5000);
        shet2.setColumnWidth(10, 5000);
        shet2.setColumnWidth(11, 5000);
        shet2.setColumnWidth(12, 5000);
        shet2.setColumnWidth(13, 5000);

        //11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111           
        //11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111           
        //11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111           
        //11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111  

        String gettables = "SELECT avg(value) as domainvalue,domain_totals.domainid as domainid,domain_name, section_name,cbo,avg(aggregate_sum) as aggregate_sum FROM ovc_lip.domain_totals join (sites join cbo on sites.cbo_id=cbo.cboid) on domain_totals.site=sites.site_id join ( domains join sections on domains.section_id=sections.section_id ) on domain_totals.domainid=domains.domain_id where  date between '"
                + startdate + "' and '" + enddate + "' group by cbo.cboid,domainid order by cbo,domainid";

        System.out.println(gettables);
        conn.rs = conn.st.executeQuery(gettables);
        int rwcount = 0;
        int rowcountcopy = 0;
        String tableheaders[] = { "Section", "Domain", "% Overall Achievement", "Column chart" };

        HSSFRow rwx = null;
        int monitorrows = 0;
        int secAcopy = 0;
        int secBcopy = 0;

        HSSFCell celx = null;
        int noofcols = 3;
        boolean isrow1 = true;
        while (conn.rs.next()) {
            //if the section has changed
            monitorrows++;
            String domainid = conn.rs.getString("domainid");
            float domainvalue = conn.rs.getFloat("domainvalue");
            domainvalue = domainvalue * 100;
            domainvalue = Math.round(domainvalue);
            float totalsum = conn.rs.getFloat("aggregate_sum");
            int dmn = (int) domainvalue;
            totalsum = Math.round(totalsum);
            //determine the cell to print data on
            int ttlsm = (int) totalsum;
            int hearderheight = 40;
            //if its the first row in each 
            if (isrow1) {
                isrow1 = false;
                rwx = shet2.createRow(rwcount);

                HSSFCell headercel = rwx.createCell(0);
                headercel.setCellValue(conn.rs.getString("cbo"));
                headercel.setCellStyle(style);
                rwx.setHeightInPoints(hearderheight);

                //create a blank
                HSSFCell cel = null;

                for (int b = 1; b < tableheaders.length; b++) {
                    cel = rwx.createCell(b);
                    cel.setCellValue("");
                    cel.setCellStyle(style);
                }
                //now merge the header cell
                shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, tableheaders.length - 1));
                rwcount++;

                //now create the header part

                HSSFRow headerrw = shet2.createRow(rwcount);
                rwx.setHeightInPoints(hearderheight);
                for (int b = 0; b < tableheaders.length; b++) {
                    HSSFCell cel1 = headerrw.createCell(b);
                    cel1.setCellValue(tableheaders[b]);
                    cel1.setCellStyle(style);
                }

                rwcount++;
            }

            //create the section part

            HSSFRow rw = shet2.createRow(rwcount);

            rw.setHeightInPoints(25);
            //column one --- section

            HSSFCell seccell = rw.createCell(0);
            seccell.setCellValue(conn.rs.getString("section_name"));
            seccell.setCellStyle(dnamestyle);

            HSSFCell domcell = rw.createCell(1);
            domcell.setCellValue(conn.rs.getString("domain_name"));
            domcell.setCellStyle(dnamestyle);

            //values only
            HSSFCell domval = rw.createCell(2);
            domval.setCellValue(dmn);
            domval.setCellStyle(dnamestyle);

            HSSFCell blank = rw.createCell(3);
            blank.setCellValue("");
            blank.setCellStyle(dnamestyle);

            //now, draw the chart
            HSSFPatriarch patriarch = shet2.createDrawingPatriarch();
            HSSFTextbox textbox1 = patriarch.createTextbox(
                    new HSSFClientAnchor(0, 0, (dmn * 10), 255, (short) 3, rwcount, (short) 3, rwcount));
            textbox1.setString(new HSSFRichTextString("" + dmn));
            textbox1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            //green 18,174,55
            //red 250 32 32
            //yellow 248 255 9
            if (dmn >= 75) {
                textbox1.setFillColor(18, 174, 55);
            } else if (dmn > 59 && dmn < 75) {

                textbox1.setFillColor(248, 255, 9);

            }

            else {

                textbox1.setFillColor(250, 32, 32);

            }
            rwcount++;

            if (monitorrows == 4) {
                shet2.addMergedRegion(new CellRangeAddress(rwcount - 4, rwcount - 1, 0, 0));
            }

            if (monitorrows == 12) {

                shet2.addMergedRegion(new CellRangeAddress(rwcount - 8, rwcount - 1, 0, 0));

                HSSFRow lastrw = shet2.createRow(rwcount);
                lastrw.setHeightInPoints(25);
                //now create a row with average
                HSSFCell avcell0 = lastrw.createCell(0);
                avcell0.setCellValue("Average");
                avcell0.setCellStyle(dnamestyle);

                HSSFCell avcell = lastrw.createCell(1);
                avcell.setCellValue("Average");
                avcell.setCellStyle(dnamestyle);

                HSSFCell avcell1 = lastrw.createCell(2);
                avcell1.setCellValue(ttlsm);
                avcell1.setCellStyle(dnamestyle);

                HSSFCell blank1 = lastrw.createCell(3);
                blank1.setCellValue("");
                blank1.setCellStyle(dnamestyle);
                HSSFTextbox textbox = patriarch.createTextbox(
                        new HSSFClientAnchor(0, 0, (dmn * (10)), 255, (short) 3, rwcount, (short) 3, rwcount));
                textbox.setString(new HSSFRichTextString("" + ttlsm));
                if (dmn >= 75) {

                    textbox.setFillColor(18, 174, 55);

                } else if (dmn > 59 && dmn < 75) {

                    textbox.setFillColor(248, 255, 9);

                }

                else {

                    textbox.setFillColor(250, 32, 32);

                }
                textbox.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

                isrow1 = true;
                monitorrows = 0;
                //dont print anything 
                rwcount++;

                //last blank cell

                HSSFRow blankrow = shet2.createRow(rwcount);
                blankrow.setHeightInPoints(30);
                for (int b = 0; b < tableheaders.length; b++) {
                    HSSFCell cel1 = blankrow.createCell(b);
                    cel1.setCellValue("");
                    cel1.setCellStyle(innerdata_style);
                }

                rwcount++;
            }

        }

        ///=========================end of while loop 

        //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=OVC_CBO_CHARTS_FROM_" + startdate + "_TO_" + enddate + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(resultspercbo.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:reports.basicreports.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w w  .  ja  v a  2s. c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        dbConn conn = new dbConn();

        wb = new HSSFWorkbook();

        HSSFSheet shet2 = null;

        String year = "";
        String site = "";
        String period = "";
        String cbo = "";

        year = request.getParameter("year");
        site = request.getParameter("sitecbo");
        period = request.getParameter("period");
        cbo = request.getParameter("staffcbo");

        String sitename = "";
        String cboname = "";

        conn.rs = conn.st.executeQuery("select cbo from cbo where cboid='" + cbo + "'");
        if (conn.rs.next()) {
            cboname = conn.rs.getString(1);
        }

        conn.rs = conn.st.executeQuery("select site_name from sites where site_id='" + site + "'");
        if (conn.rs.next()) {
            sitename = conn.rs.getString(1);
        }

        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setFontName("Cambria");
        //    font.setItalic(true);
        font.setBoldweight((short) 02);
        font.setColor(HSSFColor.BLACK.index);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setWrapText(true);
        style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

        style.setAlignment(style.ALIGN_CENTER);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        //%%%%%%%%%%%%%%%%HEADER FONTS AND COLORATION%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        HSSFFont font_header = wb.createFont();
        font_header.setFontHeightInPoints((short) 10);
        font_header.setFontName("Eras Bold ITC");
        //    font.setItalic(true);
        font_header.setBoldweight((short) 05);
        font_header.setColor(HSSFColor.BLACK.index);
        CellStyle style_header = wb.createCellStyle();
        style_header.setFont(font_header);
        style_header.setWrapText(true);
        style_header.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
        style_header.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style_header.setAlignment(style_header.ALIGN_CENTER);

        //            style_header.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //            style_header.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //            style_header.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //            style_header.setBorderLeft(HSSFCellStyle.BORDER_THIN);

        //%%%%%%%%%%%%%%%%%%%%%%%%%DATA FONT%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        //font data
        HSSFFont datafont = wb.createFont();
        datafont.setBoldweight((short) 03);
        datafont.setColor(HSSFColor.BLACK.index);
        datafont.setFontHeightInPoints((short) 10);
        datafont.setFontName("Cambria");
        datafont.setItalic(true);

        //bold font 
        HSSFFont bolfont = wb.createFont();

        bolfont.setBoldweight((short) 05);
        bolfont.setColor(HSSFColor.BLACK.index);
        bolfont.setFontHeightInPoints((short) 12);
        bolfont.setFontName("Cambria");

        //=======INNER DATA STYLING===========================

        CellStyle innerdata_style = wb.createCellStyle();
        innerdata_style.setFont(datafont);
        innerdata_style.setWrapText(true);
        innerdata_style.setAlignment(innerdata_style.ALIGN_CENTER);
        innerdata_style.setFillForegroundColor(HSSFColor.WHITE.index);
        innerdata_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        innerdata_style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle lastcellrighborder = wb.createCellStyle();
        lastcellrighborder.setFont(datafont);
        lastcellrighborder.setWrapText(true);
        lastcellrighborder.setAlignment(lastcellrighborder.ALIGN_CENTER);
        lastcellrighborder.setFillForegroundColor(HSSFColor.WHITE.index);
        lastcellrighborder.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //            lastcellrighborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //            lastcellrighborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        lastcellrighborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //            lastcellrighborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        lastcellrighborder.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle innerdata_style2 = wb.createCellStyle();
        innerdata_style2.setFont(bolfont);
        innerdata_style2.setWrapText(true);
        innerdata_style2.setAlignment(innerdata_style.ALIGN_LEFT);
        innerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
        innerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        innerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        //Code colors

        CellStyle lg = wb.createCellStyle();
        lg.setFont(bolfont);
        lg.setWrapText(true);
        lg.setAlignment(lg.ALIGN_CENTER);
        lg.setFillForegroundColor(HSSFColor.GREEN.index);
        lg.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        lg.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        lg.setBorderTop(HSSFCellStyle.BORDER_THIN);
        lg.setBorderRight(HSSFCellStyle.BORDER_THIN);
        lg.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        lg.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle Y = wb.createCellStyle();
        Y.setFont(bolfont);
        Y.setWrapText(true);
        Y.setAlignment(Y.ALIGN_CENTER);
        Y.setFillForegroundColor(HSSFColor.YELLOW.index);
        Y.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        Y.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        Y.setBorderTop(HSSFCellStyle.BORDER_THIN);
        Y.setBorderRight(HSSFCellStyle.BORDER_THIN);
        Y.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        Y.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle R = wb.createCellStyle();
        R.setFont(bolfont);
        R.setWrapText(true);
        R.setAlignment(R.ALIGN_CENTER);
        R.setFillForegroundColor(HSSFColor.RED.index);
        R.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        R.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        R.setBorderTop(HSSFCellStyle.BORDER_THIN);
        R.setBorderRight(HSSFCellStyle.BORDER_THIN);
        R.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        R.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        //=======INNER LEFT DATA STYLING===========================

        CellStyle binnerdata_style2 = wb.createCellStyle();
        binnerdata_style2.setFont(datafont);
        binnerdata_style2.setWrapText(true);
        binnerdata_style2.setAlignment(binnerdata_style2.ALIGN_LEFT);
        binnerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
        binnerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        binnerdata_style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        binnerdata_style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        binnerdata_style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        binnerdata_style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        binnerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //create a header

        //=======================Domainname styles
        CellStyle dnamestyle = wb.createCellStyle();
        dnamestyle.setFont(bolfont);
        dnamestyle.setWrapText(true);
        dnamestyle.setAlignment(dnamestyle.ALIGN_LEFT);
        dnamestyle.setFillForegroundColor(HSSFColor.WHITE.index);
        dnamestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        dnamestyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        dnamestyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        dnamestyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        dnamestyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        dnamestyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        shet2 = wb.createSheet("Report");
        shet2.setColumnWidth(0, 10000);
        shet2.setColumnWidth(1, 5000);
        shet2.setColumnWidth(2, 5000);
        shet2.setColumnWidth(3, 5000);
        shet2.setColumnWidth(4, 8000);
        shet2.setColumnWidth(5, 8000);
        //create header one
        HSSFRow header = shet2.createRow(0);
        header.setHeightInPoints(30);
        HSSFCell cel1 = header.createCell(0);
        cel1.setCellValue("APHIAplus NURU YA BONDE");
        cel1.setCellStyle(style);
        for (int b = 1; b <= 5; b++) {
            cel1 = header.createCell(b);
            cel1.setCellValue("");
            cel1.setCellStyle(style);
        }

        shet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));

        //create header two
        HSSFRow header2 = shet2.createRow(1);
        header2.setHeightInPoints(28);
        HSSFCell cel2 = null;
        for (int b = 1; b <= 5; b++) {
            cel2 = header2.createCell(b);
            cel2.setCellValue("");
            cel2.setCellStyle(style);
        }

        cel2 = header2.createCell(0);
        cel2.setCellValue("OVC LIP SUPPORT SUPERVISION DASH BOARD");
        cel2.setCellStyle(style);

        shet2.addMergedRegion(new CellRangeAddress(1, 1, 0, 5));

        //cbo name
        //create header three
        HSSFRow header3 = shet2.createRow(2);
        HSSFCell cel3 = header3.createCell(0);
        cel3.setCellValue("Name of LIP/CBO");
        cel3.setCellStyle(innerdata_style2);

        HSSFCell cel4 = header3.createCell(1);
        cel4.setCellValue("" + cboname);
        cel4.setCellStyle(innerdata_style);
        //blank cells for purpose of clear worksheet only
        for (int x = 2; x <= 3; x++) {
            HSSFCell cel = header3.createCell(x);
            cel.setCellValue("");
            cel.setCellStyle(innerdata_style);
        }

        HSSFCell cel5 = header3.createCell(4);
        cel5.setCellValue("Site Visited:");
        cel5.setCellStyle(innerdata_style2);

        HSSFCell cel6 = header3.createCell(5);
        cel6.setCellValue("" + sitename);
        cel6.setCellStyle(lastcellrighborder);

        //add the width of this column

        //create a blank row whose last cell has a border

        HSSFRow blankrw = shet2.createRow(3);
        for (int z = 0; z < 5; z++) {

            HSSFCell cl = blankrw.createCell(z);
            cl.setCellValue("");
            cl.setCellStyle(innerdata_style);
        }
        HSSFCell cl = blankrw.createCell(5);
        cl.setCellValue("");
        cl.setCellStyle(lastcellrighborder);
        //==========DATE OF VISIT

        String mywhere = "site='" + site + "' and period='" + period + "' and year='" + year + "' ";

        String supervisor = "";
        String dateofvisit = "";

        String strengths = "";
        String constraints = "";

        String loadbasicdetails = "select * from backgroundinfor join staff on backgroundinfor.supervisor=staff.staff_id where "
                + mywhere + " ";
        System.out.println(loadbasicdetails);
        conn.rs = conn.st.executeQuery(loadbasicdetails);
        while (conn.rs.next()) {
            supervisor = conn.rs.getString("fname") + " " + conn.rs.getString("mname");
            dateofvisit = conn.rs.getString("ass_date");
            strengths = conn.rs.getString("strengths");
            constraints = conn.rs.getString("constraints");

        }

        //================Create the second header=================
        //create header three
        HSSFRow header4 = shet2.createRow(4);
        HSSFCell cel = header4.createCell(0);
        cel.setCellValue("Date of Visit");
        cel.setCellStyle(innerdata_style2);

        HSSFCell cell = header4.createCell(1);
        cell.setCellValue("" + dateofvisit);
        cell.setCellStyle(innerdata_style);

        //blank cells for purpose of clear worksheet only
        for (int x = 2; x <= 3; x++) {
            HSSFCell ceel = header4.createCell(x);
            ceel.setCellValue("");
            ceel.setCellStyle(innerdata_style);
        }

        HSSFCell cell5 = header4.createCell(4);
        cell5.setCellValue("Supervision Team Lead:");
        cell5.setCellStyle(innerdata_style2);

        HSSFCell cell6 = header4.createCell(5);
        cell6.setCellValue("" + supervisor);
        cell6.setCellStyle(lastcellrighborder);

        //another blank row
        HSSFRow blankrw2 = shet2.createRow(5);
        for (int z = 0; z < 5; z++) {

            HSSFCell cl2 = blankrw2.createCell(z);
            cl2.setCellValue("");
            cl2.setCellStyle(innerdata_style);
        }
        HSSFCell cl2 = blankrw2.createCell(5);
        cl2.setCellValue("");
        cl2.setCellStyle(lastcellrighborder);

        //create a header

        String theaderar[] = { "Assesment Domain", "LG", "Y", "R", "Comments/Action", "" };

        HSSFRow theader = shet2.createRow(6);

        for (int x = 0; x < theaderar.length; x++) {
            HSSFCell tcel = theader.createCell(x);
            tcel.setCellValue(theaderar[x]);
            if (theaderar[x].equalsIgnoreCase("LG")) {
                tcel.setCellStyle(lg);
            } else if (theaderar[x].equalsIgnoreCase("Y")) {
                tcel.setCellStyle(Y);
            } else if (theaderar[x].equalsIgnoreCase("R")) {
                tcel.setCellStyle(R);
            } else {
                tcel.setCellStyle(style);
            }

        }
        shet2.addMergedRegion(new CellRangeAddress(6, 6, 4, 5));
        //SECTION A HEADER
        HSSFRow seca = shet2.createRow(7);
        HSSFCell tcel1 = seca.createCell(0);
        tcel1.setCellValue("Section A: Data management and Reporting Systems");
        tcel1.setCellStyle(style);
        for (int b = 1; b <= 5; b++) {
            cel1 = seca.createCell(b);
            cel1.setCellValue("");
            cel1.setCellStyle(style);
        }

        shet2.addMergedRegion(new CellRangeAddress(7, 7, 0, 5));

        String gettables = "SELECT domain_name,domains.domain_id as domainid,section_name,domains.section_id as secid,value as domainvalue,aggregate_sum,period,year,site FROM domains join sections on domains.section_id=sections.section_id join domain_totals on domains.domain_id=domain_totals.domainid where "
                + mywhere + " order by domainid";
        System.out.println(gettables);
        conn.rs = conn.st.executeQuery(gettables);
        int rwcount = 8;
        HSSFRow rwx = null;
        HSSFCell celx = null;
        String sectioncopy = "";
        while (conn.rs.next()) {
            if (sectioncopy.equals("")) {
                sectioncopy = conn.rs.getString("section_name");
            }
            //if the section has changed
            if (!sectioncopy.equals(conn.rs.getString("section_name"))) {
                //create a section header
                //``````````````````````````````INNER SECTION HEADERS``````````````````            
                //``````````````````````````````INNER SECTION HEADERS``````````````````            
                //``````````````````````````````INNER SECTION HEADERS``````````````````            
                HSSFRow secb = shet2.createRow(rwcount);
                HSSFCell t = secb.createCell(0);
                t.setCellValue("Section " + conn.rs.getString("section_name"));
                t.setCellStyle(style);
                //for purpose of merging
                for (int b = 1; b <= 5; b++) {
                    cel1 = secb.createCell(b);
                    cel1.setCellValue("");
                    cel1.setCellStyle(style);
                }
                //equalize copy and current value       
                sectioncopy = conn.rs.getString("section_name");
                shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

                //increment rowcount to skip the current row 
                rwcount++;
            }

            String valu[] = { conn.rs.getString("domain_name"), "", "", "", "", "" };

            rwx = shet2.createRow(rwcount);
            for (int t = 0; t < valu.length; t++) {
                celx = rwx.createCell(t);
                celx.setCellValue("" + valu[t]);
                celx.setCellStyle(dnamestyle);
            }
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 4, 5));
            //get the value of percentange achievement per domian
            //multiply by 100
            //round off
            float domainvalue = conn.rs.getFloat("domainvalue");

            domainvalue = domainvalue * 100;
            //BigDecimal bd=new BigDecimal(domainvalue).setScale(0,RoundingMode.HALF_EVEN);
            //domainval=bd.doubleValue();
            domainvalue = Math.round(domainvalue);

            //determine the cell to print data on
            if (domainvalue >= 75) {

                celx = rwx.createCell(1);
                celx.setCellValue("" + domainvalue + "%");
                celx.setCellStyle(lg);

            } else if (domainvalue >= 60 && domainvalue < 75) {
                celx = rwx.createCell(2);
                celx.setCellValue("" + domainvalue + "%");
                celx.setCellStyle(Y);

            } else if (domainvalue < 60) {

                celx = rwx.createCell(3);
                celx.setCellValue("" + domainvalue + "%");
                celx.setCellStyle(R);
            }

            rwcount++;
        }

        ///=========================end of while loop 

        //====================STRENGTHS=========================== 
        HSSFRow secb = shet2.createRow(rwcount);

        //for purpose of merging
        for (int b = 1; b <= 5; b++) {
            cel1 = secb.createCell(b);
            cel1.setCellValue("");
            cel1.setCellStyle(style);
        }

        HSSFCell t = secb.createCell(0);
        t.setCellValue("What has worked well and key areas of strengths observed");
        t.setCellStyle(style);
        shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

        rwcount++;

        HSSFRow str = shet2.createRow(rwcount);

        for (int b = 1; b <= 5; b++) {
            cel1 = str.createCell(b);
            cel1.setCellValue("");
            cel1.setCellStyle(dnamestyle);
        }

        HSSFCell t1 = str.createCell(0);
        t1.setCellValue("" + strengths);
        t1.setCellStyle(dnamestyle);
        shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));
        //for purpose of merging

        str.setHeightInPoints(50);
        rwcount++;

        //=======Contraints
        HSSFRow sec3 = shet2.createRow(rwcount);

        //for purpose of merging
        for (int b = 1; b <= 5; b++) {
            cel1 = sec3.createCell(b);
            cel1.setCellValue("");
            cel1.setCellStyle(style);
        }

        HSSFCell t2 = sec3.createCell(0);
        t2.setCellValue("Critical consraints affecting quality programming and data management");
        t2.setCellStyle(style);
        shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

        rwcount++;

        HSSFRow str2 = shet2.createRow(rwcount);

        for (int b = 1; b <= 5; b++) {
            cel1 = str2.createCell(b);
            cel1.setCellValue("");
            cel1.setCellStyle(dnamestyle);
        }

        HSSFCell t4 = str2.createCell(0);
        t4.setCellValue("" + constraints);
        t4.setCellStyle(dnamestyle);
        shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));
        str2.setHeightInPoints(50);

        rwcount++;
        //a line of codes
        String codes[] = { "LG - Meets Expectations (>=75%); ", " Y- Needs Improvement (60%- 74%);",
                "R - Needs Urgent Attention (<=59%);" };
        HSSFRow rwl = shet2.createRow(rwcount);
        HSSFCell ce = rwl.createCell(0);
        ce.setCellValue("CODES");
        ce.setCellStyle(dnamestyle);
        for (int b = 0; b < codes.length; b++) {
            ce = rwl.createCell(b + 1);
            ce.setCellValue("" + codes[b]);
            if (b == 0) {
                ce.setCellStyle(lg);
            } else if (b == 1) {

                ce.setCellStyle(Y);
            } else {
                ce.setCellStyle(R);
            }
        }
        ce = rwl.createCell(4);
        ce.setCellValue("");
        ce.setCellStyle(dnamestyle);
        ce = rwl.createCell(5);
        ce.setCellValue("");
        ce.setCellStyle(dnamestyle);
        shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 4, 5));

        //write it as an excel attachment
        sitename = sitename.replace(" ", "_");
        sitename = sitename.replace("'", "");
        cboname = cboname.replace(" ", "_");
        cboname = cboname.replace("'", "_");
        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=OVC_LIP_REPORT_" + cboname + "_" + sitename + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(basicreports.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:reports.countyreport.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w w  .  j  a v  a  2 s  . c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        dbConn conn = new dbConn();

        wb = new HSSFWorkbook();

        HSSFSheet shet2 = null;

        String year = "";
        String site = "";
        String period = "";
        String cbo = "";
        String startdate = "2015-01-01";
        String enddate = "2015-03-30";

        startdate = request.getParameter("startdate");
        enddate = request.getParameter("enddate");

        String getdistinctsites = "SELECT county.county_id as countyid,county_name FROM ovc_lip.backgroundinfor join (sites join (district join county on district.county_id=county.county_id) on sites.districtid=district.district_id) on backgroundinfor.site=sites.site_id where ass_date between '"
                + startdate + "' and '" + enddate + "' group by county_name ";

        ArrayList countyids = new ArrayList();
        ArrayList countynames = new ArrayList();
        countyids.add("1000");
        countynames.add("OVERALL COUNTIES REPORT");
        //ArrayList years=new ArrayList();
        //ArrayList periods=new ArrayList();
        //ArrayList cbos=new ArrayList();
        conn.rs = conn.st.executeQuery(getdistinctsites);
        while (conn.rs.next()) {

            countyids.add(conn.rs.getString(1));
            countynames.add(conn.rs.getString(2).toUpperCase() + " COUNTY");

        }
        //            year=request.getParameter("year");
        //site=request.getParameter("sitecbo");
        //period=request.getParameter("period");
        //cbo=request.getParameter("staffcbo");

        String sitename = "";
        String cboname = "";

        //begin a loop that will create as many reports as possible
        for (int u = 0; u < countyids.size(); u++) {

            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short) 12);
            font.setFontName("Cambria");
            //    font.setItalic(true);
            font.setBoldweight((short) 02);
            font.setColor(HSSFColor.BLACK.index);
            CellStyle style = wb.createCellStyle();
            style.setFont(font);
            style.setWrapText(true);
            style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

            style.setAlignment(style.ALIGN_CENTER);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

            //%%%%%%%%%%%%%%%%HEADER FONTS AND COLORATION%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            HSSFFont font_header = wb.createFont();
            font_header.setFontHeightInPoints((short) 10);
            font_header.setFontName("Eras Bold ITC");
            //    font.setItalic(true);
            font_header.setBoldweight((short) 05);
            font_header.setColor(HSSFColor.BLACK.index);
            CellStyle style_header = wb.createCellStyle();
            style_header.setFont(font_header);
            style_header.setWrapText(true);
            style_header.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
            style_header.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style_header.setAlignment(style_header.ALIGN_CENTER);

            //            style_header.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderLeft(HSSFCellStyle.BORDER_THIN);

            //%%%%%%%%%%%%%%%%%%%%%%%%%DATA FONT%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            //font data
            HSSFFont datafont = wb.createFont();
            datafont.setBoldweight((short) 03);
            datafont.setColor(HSSFColor.BLACK.index);
            datafont.setFontHeightInPoints((short) 10);
            datafont.setFontName("Cambria");
            datafont.setItalic(true);

            //bold font 
            HSSFFont bolfont = wb.createFont();

            bolfont.setBoldweight((short) 05);
            bolfont.setColor(HSSFColor.BLACK.index);
            bolfont.setFontHeightInPoints((short) 12);
            bolfont.setFontName("Cambria");

            //=========================ROW STYLE===============================

            HSSFCellStyle rowstyle = wb.createCellStyle();
            rowstyle.setWrapText(true);

            //=======INNER DATA STYLING===========================

            CellStyle innerdata_style = wb.createCellStyle();
            innerdata_style.setFont(datafont);
            innerdata_style.setWrapText(true);
            innerdata_style.setAlignment(innerdata_style.ALIGN_CENTER);
            innerdata_style.setFillForegroundColor(HSSFColor.WHITE.index);
            innerdata_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            innerdata_style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle lastcellrighborder = wb.createCellStyle();
            lastcellrighborder.setFont(datafont);
            lastcellrighborder.setWrapText(true);
            lastcellrighborder.setAlignment(lastcellrighborder.ALIGN_CENTER);
            lastcellrighborder.setFillForegroundColor(HSSFColor.WHITE.index);
            lastcellrighborder.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            lastcellrighborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            lastcellrighborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
            lastcellrighborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            lastcellrighborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            lastcellrighborder.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle innerdata_style2 = wb.createCellStyle();
            innerdata_style2.setFont(bolfont);
            innerdata_style2.setWrapText(true);
            innerdata_style2.setAlignment(innerdata_style.ALIGN_LEFT);
            innerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
            innerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            innerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle orangestyle = wb.createCellStyle();
            orangestyle.setFont(bolfont);
            orangestyle.setWrapText(true);
            orangestyle.setAlignment(orangestyle.ALIGN_CENTER);
            orangestyle.setFillForegroundColor(HSSFColor.ORANGE.index);
            orangestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //          innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //          innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //          innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //          innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            orangestyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            //Code colors

            CellStyle lg = wb.createCellStyle();
            lg.setFont(bolfont);
            lg.setWrapText(true);
            lg.setAlignment(lg.ALIGN_CENTER);
            lg.setFillForegroundColor(HSSFColor.GREEN.index);
            lg.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            lg.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            lg.setBorderTop(HSSFCellStyle.BORDER_THIN);
            lg.setBorderRight(HSSFCellStyle.BORDER_THIN);
            lg.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            lg.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle Y = wb.createCellStyle();
            Y.setFont(bolfont);
            Y.setWrapText(true);
            Y.setAlignment(Y.ALIGN_CENTER);
            Y.setFillForegroundColor(HSSFColor.YELLOW.index);
            Y.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            Y.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            Y.setBorderTop(HSSFCellStyle.BORDER_THIN);
            Y.setBorderRight(HSSFCellStyle.BORDER_THIN);
            Y.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            Y.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle R = wb.createCellStyle();
            R.setFont(bolfont);
            R.setWrapText(true);
            R.setAlignment(R.ALIGN_CENTER);
            R.setFillForegroundColor(HSSFColor.RED.index);
            R.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            R.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            R.setBorderTop(HSSFCellStyle.BORDER_THIN);
            R.setBorderRight(HSSFCellStyle.BORDER_THIN);
            R.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            R.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            //=======INNER LEFT DATA STYLING===========================

            CellStyle binnerdata_style2 = wb.createCellStyle();
            binnerdata_style2.setFont(datafont);
            binnerdata_style2.setWrapText(true);
            binnerdata_style2.setAlignment(binnerdata_style2.ALIGN_LEFT);
            binnerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
            binnerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            binnerdata_style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            //create a header

            //=======================Domainname styles
            CellStyle dnamestyle = wb.createCellStyle();
            dnamestyle.setFont(bolfont);
            dnamestyle.setWrapText(true);
            dnamestyle.setAlignment(dnamestyle.ALIGN_LEFT);
            dnamestyle.setFillForegroundColor(HSSFColor.WHITE.index);
            dnamestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            dnamestyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            shet2 = wb.createSheet(countynames.get(u).toString().toUpperCase());
            shet2.setColumnWidth(0, 10000);
            shet2.setColumnWidth(1, 5000);
            shet2.setColumnWidth(2, 5000);
            shet2.setColumnWidth(3, 5000);
            shet2.setColumnWidth(4, 8000);
            shet2.setColumnWidth(5, 8000);
            //create header one
            HSSFRow header = shet2.createRow(0);
            header.setHeightInPoints(30);
            HSSFCell cel1 = header.createCell(0);
            cel1.setCellValue("APHIAplus NURU YA BONDE");
            cel1.setCellStyle(style);
            for (int b = 1; b <= 5; b++) {
                cel1 = header.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(style);
            }

            shet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));

            //create header two
            HSSFRow header2 = shet2.createRow(1);
            header2.setHeightInPoints(28);
            HSSFCell cel2 = null;
            for (int b = 1; b <= 5; b++) {
                cel2 = header2.createCell(b);
                cel2.setCellValue("");
                cel2.setCellStyle(style);
            }

            cel2 = header2.createCell(0);
            cel2.setCellValue("OVC LIP SUPPORT SUPERVISION DASH BOARD");
            cel2.setCellStyle(style);

            shet2.addMergedRegion(new CellRangeAddress(1, 1, 0, 5));

            //cbo name
            //create header three
            HSSFRow header3 = shet2.createRow(2);
            HSSFCell cel3 = header3.createCell(0);
            cel3.setCellValue(countynames.get(u).toString());
            cel3.setCellStyle(orangestyle);

            HSSFCell cel4 = header3.createCell(1);
            cel4.setCellValue("");
            cel4.setCellStyle(orangestyle);
            //blank cells for purpose of clear worksheet only
            for (int x = 2; x <= 3; x++) {
                HSSFCell cel = header3.createCell(x);
                cel.setCellValue("");
                cel.setCellStyle(orangestyle);
            }

            HSSFCell cel5 = header3.createCell(4);
            cel5.setCellValue("");
            cel5.setCellStyle(orangestyle);

            HSSFCell cel6 = header3.createCell(5);
            cel6.setCellValue("");
            cel6.setCellStyle(orangestyle);

            //create a merged region
            shet2.addMergedRegion(new CellRangeAddress(2, 2, 0, 5));

            //create a blank row whose last cell has a border

            HSSFRow blankrw = shet2.createRow(3);
            for (int z = 0; z < 5; z++) {

                HSSFCell cl = blankrw.createCell(z);
                cl.setCellValue("");
                cl.setCellStyle(innerdata_style);
            }
            HSSFCell cl = blankrw.createCell(5);
            cl.setCellValue("");
            cl.setCellStyle(lastcellrighborder);
            //==========DATE OF VISIT

            String mywhere = " district.county_id='" + countyids.get(u).toString() + "' and ass_date between '"
                    + startdate + "' and '" + enddate + "' ";
            //if the current countyid is 0, then the where code should not specify the county name 

            if (countyids.get(u).toString().equals("1000")) {
                mywhere = "  ass_date between '" + startdate + "' and '" + enddate + "' ";

            }

            String supervisor = "";
            String dateofvisit = "";

            String strengths = "";
            String constraints = "";

            // String loadbasicdetails="select * from backgroundinfor join staff on backgroundinfor.supervisor=staff.staff_id where "+mywhere+" ";
            String loadbasicdetails = "select strengths,constraints,county_name from backgroundinfor join (sites join (district join county on district.county_id=county.county_id) on sites.districtid=district.district_id) on backgroundinfor.site=sites.site_id where "
                    + mywhere + " order by county_name";

            //System.out.println("~~~~ "+loadbasicdetails);
            conn.rs = conn.st.executeQuery(loadbasicdetails);

            //if this is the overal query

            ArrayList countycomments = new ArrayList();

            if (countyids.get(u).toString().equals("1000")) {
                while (conn.rs.next()) {
                    // supervisor=conn.rs.getString("fname")+" "+conn.rs.getString("mname");
                    //dateofvisit=conn.rs.getString("ass_date");
                    if (!conn.rs.getString("strengths").equals("")) {

                        //add the county header if it has not been added before only
                        if (countycomments.contains(conn.rs.getString("county_name"))) {
                        } else {
                            countycomments.add(conn.rs.getString("county_name"));
                            strengths += "________________________________________"
                                    + conn.rs.getString("county_name")
                                    + " County ________________________________________\n";
                            constraints += "________________________________________"
                                    + conn.rs.getString("county_name")
                                    + " County ________________________________________\n";
                        }
                    }

                    strengths += conn.rs.getString("strengths");

                    constraints += conn.rs.getString("constraints");
                    if (!conn.rs.getString("strengths").equals("")) {
                        strengths += "\n";
                        constraints += "\n";
                    }
                }
            } else {
                while (conn.rs.next()) {
                    // supervisor=conn.rs.getString("fname")+" "+conn.rs.getString("mname");
                    //dateofvisit=conn.rs.getString("ass_date");

                    strengths += conn.rs.getString("strengths");

                    constraints += conn.rs.getString("constraints");
                    if (!conn.rs.getString("strengths").equals("")) {
                        strengths += "\n";
                        constraints += "\n";
                    }
                }
            } //end of while

            //================Create the second header=================
            //create header three
            HSSFRow header4 = shet2.createRow(4);
            HSSFCell cel = header4.createCell(0);
            cel.setCellValue("");
            cel.setCellStyle(innerdata_style);

            HSSFCell cell = header4.createCell(1);
            cell.setCellValue("");
            cell.setCellStyle(innerdata_style);

            //blank cells for purpose of clear worksheet only
            for (int x = 2; x <= 3; x++) {
                HSSFCell ceel = header4.createCell(x);
                ceel.setCellValue("");
                ceel.setCellStyle(innerdata_style);
            }

            HSSFCell cell5 = header4.createCell(4);
            cell5.setCellValue("");
            cell5.setCellStyle(innerdata_style);

            HSSFCell cell6 = header4.createCell(5);
            cell6.setCellValue("");
            cell6.setCellStyle(lastcellrighborder);

            //another blank row
            HSSFRow blankrw2 = shet2.createRow(5);
            for (int z = 0; z < 5; z++) {

                HSSFCell cl2 = blankrw2.createCell(z);
                cl2.setCellValue("");
                cl2.setCellStyle(innerdata_style);
            }
            HSSFCell cl2 = blankrw2.createCell(5);
            cl2.setCellValue("");
            cl2.setCellStyle(lastcellrighborder);

            //create a header

            String theaderar[] = { "Assesment Domain", "LG", "Y", "R", "Comments/Action", "" };

            HSSFRow theader = shet2.createRow(6);

            for (int x = 0; x < theaderar.length; x++) {
                HSSFCell tcel = theader.createCell(x);
                tcel.setCellValue(theaderar[x]);
                if (theaderar[x].equalsIgnoreCase("LG")) {
                    tcel.setCellStyle(lg);
                } else if (theaderar[x].equalsIgnoreCase("Y")) {
                    tcel.setCellStyle(Y);
                } else if (theaderar[x].equalsIgnoreCase("R")) {
                    tcel.setCellStyle(R);
                } else {
                    tcel.setCellStyle(style);
                }

            }
            shet2.addMergedRegion(new CellRangeAddress(6, 6, 4, 5));
            //SECTION A HEADER
            HSSFRow seca = shet2.createRow(7);
            HSSFCell tcel1 = seca.createCell(0);
            tcel1.setCellValue("Section A: Data management and Reporting Systems");
            tcel1.setCellStyle(style);
            for (int b = 1; b <= 5; b++) {
                cel1 = seca.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(style);
            }

            shet2.addMergedRegion(new CellRangeAddress(7, 7, 0, 5));

            // String gettables = "SELECT domain_name,domains.domain_id as domainid,section_name,domains.section_id as secid,value as domainvalue,aggregate_sum,period,year,site FROM domains join sections on domains.section_id=sections.section_id join domain_totals on domains.domain_id=domain_totals.domainid where "+mywhere+" order by domainid";
            String gettables = "SELECT domain_name,avg(value) as domainvalue,section_name ,domains.section_id as secid FROM ovc_lip.domain_totals join (sites join (district join county on district.county_id=county.county_id) on sites.districtid=district.district_id) on domain_totals.site=sites.site_id join (domains join sections on domains.section_id=sections.section_id) on domain_totals.domainid=domains.domain_id  where county.county_id='"
                    + countyids.get(u) + "' and date between '" + startdate + "' and '" + enddate
                    + "' group by domain_totals.domainid,county_name order by domainid";
            //if its the first county, themn skip the county part
            if (countyids.get(u).toString().equalsIgnoreCase("1000")) {

                gettables = "SELECT domain_name,avg(value) as domainvalue,section_name ,domains.section_id as secid FROM ovc_lip.domain_totals  join (domains join sections on domains.section_id=sections.section_id) on domain_totals.domainid=domains.domain_id  where  date between '"
                        + startdate + "' and '" + enddate
                        + "' group by domain_totals.domainid order by domainid";

            }
            System.out.println(gettables);
            conn.rs = conn.st.executeQuery(gettables);
            int rwcount = 8;
            HSSFRow rwx = null;
            HSSFCell celx = null;
            String sectioncopy = "";
            while (conn.rs.next()) {
                if (sectioncopy.equals("")) {
                    sectioncopy = conn.rs.getString("section_name");
                }
                //if the section has changed
                if (!sectioncopy.equals(conn.rs.getString("section_name"))) {
                    //create a section header
                    //``````````````````````````````INNER SECTION HEADERS``````````````````            
                    //``````````````````````````````INNER SECTION HEADERS``````````````````            
                    //``````````````````````````````INNER SECTION HEADERS``````````````````            
                    HSSFRow secb = shet2.createRow(rwcount);
                    HSSFCell t = secb.createCell(0);
                    t.setCellValue("Section " + conn.rs.getString("section_name"));
                    t.setCellStyle(style);
                    //for purpose of merging
                    for (int b = 1; b <= 5; b++) {
                        cel1 = secb.createCell(b);
                        cel1.setCellValue("");
                        cel1.setCellStyle(style);
                    }
                    //equalize copy and current value       
                    sectioncopy = conn.rs.getString("section_name");
                    shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

                    //increment rowcount to skip the current row 
                    rwcount++;
                }

                String valu[] = { conn.rs.getString("domain_name"), "", "", "", "", "" };

                rwx = shet2.createRow(rwcount);
                for (int t = 0; t < valu.length; t++) {
                    celx = rwx.createCell(t);
                    celx.setCellValue("" + valu[t]);
                    celx.setCellStyle(dnamestyle);
                }
                shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 4, 5));
                //get the value of percentange achievement per domian
                //multiply by 100
                //round off
                float domainvalue = conn.rs.getFloat("domainvalue");

                domainvalue = domainvalue * 100;
                //BigDecimal bd=new BigDecimal(domainvalue).setScale(0,RoundingMode.HALF_EVEN);
                //domainval=bd.doubleValue();
                domainvalue = Math.round(domainvalue);

                //determine the cell to print data on
                if (domainvalue >= 75) {

                    celx = rwx.createCell(1);
                    celx.setCellValue("" + domainvalue + "%");
                    celx.setCellStyle(lg);

                } else if (domainvalue >= 60 && domainvalue < 75) {
                    celx = rwx.createCell(2);
                    celx.setCellValue("" + domainvalue + "%");
                    celx.setCellStyle(Y);

                } else if (domainvalue < 60) {

                    celx = rwx.createCell(3);
                    celx.setCellValue("" + domainvalue + "%");
                    celx.setCellStyle(R);
                }

                rwcount++;
            }

            ///=========================end of while loop 

            //====================STRENGTHS=========================== 
            HSSFRow secb = shet2.createRow(rwcount);

            //for purpose of merging
            for (int b = 1; b <= 5; b++) {
                cel1 = secb.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(style);
            }

            HSSFCell t = secb.createCell(0);
            t.setCellValue("What has worked well and key areas of strengths observed");
            t.setCellStyle(style);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

            rwcount++;

            HSSFRow str = shet2.createRow(rwcount);
            //str.setRowStyle(rowstyle);
            for (int b = 1; b <= 5; b++) {
                cel1 = str.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(dnamestyle);
            }

            HSSFCell t1 = str.createCell(0);
            t1.setCellValue("" + strengths);
            t1.setCellStyle(dnamestyle);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));
            //for purpose of merging
            gen g = new gen();
            int rwheight1 = g.countLines(strengths);
            rwheight1 = rwheight1 * 17;
            str.setHeightInPoints(rwheight1);
            rwcount++;

            //=======Contraints
            HSSFRow sec3 = shet2.createRow(rwcount);

            //for purpose of merging
            for (int b = 1; b <= 5; b++) {
                cel1 = sec3.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(style);
            }

            HSSFCell t2 = sec3.createCell(0);
            t2.setCellValue("Critical consraints affecting quality programming and data management");
            t2.setCellStyle(style);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

            rwcount++;

            HSSFRow str2 = shet2.createRow(rwcount);
            str2.setRowStyle(rowstyle);
            for (int b = 1; b <= 5; b++) {
                cel1 = str2.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(dnamestyle);
            }

            HSSFCell t4 = str2.createCell(0);
            t4.setCellValue("" + constraints);
            t4.setCellStyle(dnamestyle);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

            //count the number of lines then multiply by a certain fixed unit
            int rwheight = g.countLines(constraints);
            rwheight = rwheight * 17;
            str2.setHeightInPoints(rwheight);

            rwcount++;
            //a line of codes
            String codes[] = { "LG - Meets Expectations (>=75%); ", " Y- Needs Improvement (60%- 74%);",
                    "R - Needs Urgent Attention (<=59%);" };
            HSSFRow rwl = shet2.createRow(rwcount);
            HSSFCell ce = rwl.createCell(0);
            ce.setCellValue("CODES");
            ce.setCellStyle(dnamestyle);
            for (int b = 0; b < codes.length; b++) {
                ce = rwl.createCell(b + 1);
                ce.setCellValue("" + codes[b]);
                if (b == 0) {
                    ce.setCellStyle(lg);
                } else if (b == 1) {

                    ce.setCellStyle(Y);
                } else {
                    ce.setCellStyle(R);
                }
            }
            ce = rwl.createCell(4);
            ce.setCellValue("");
            ce.setCellStyle(dnamestyle);
            ce = rwl.createCell(5);
            ce.setCellValue("");
            ce.setCellStyle(dnamestyle);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 4, 5));

        }

        //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=OVC_LIP_COUNTY_REPORT_" + startdate + "_" + enddate + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(basicreports.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:reports.multiplesitesreport.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w  .  j av a  2s  . com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        dbConn conn = new dbConn();

        wb = new HSSFWorkbook();

        HSSFSheet shet2 = null;

        String year = "";
        String site = "";
        String period = "";
        String cbo = "";
        String startdate = "2015-01-01";
        String enddate = "2015-03-30";

        startdate = request.getParameter("startdate");
        enddate = request.getParameter("enddate");

        String getdistinctsites = "select distinct (site) as site, year,period ,cbo from backgroundinfor where ass_date between '"
                + startdate + "' and '" + enddate + "' order by site";

        ArrayList siteids = new ArrayList();
        ArrayList years = new ArrayList();
        ArrayList periods = new ArrayList();
        ArrayList cbos = new ArrayList();
        conn.rs = conn.st.executeQuery(getdistinctsites);
        while (conn.rs.next()) {

            siteids.add(conn.rs.getString(1));
            years.add(conn.rs.getString(2));
            periods.add(conn.rs.getString("period"));
            cbos.add(conn.rs.getString("cbo"));

        }
        //            year=request.getParameter("year");
        //site=request.getParameter("sitecbo");
        //period=request.getParameter("period");
        //cbo=request.getParameter("staffcbo");

        String sitename = "";
        String cboname = "";

        //begin a loop that will create as many reports as possible
        for (int u = 0; u < siteids.size(); u++) {

            conn.rs = conn.st.executeQuery("select cbo from cbo where cboid='" + cbos.get(u) + "'");
            if (conn.rs.next()) {
                cboname = conn.rs.getString(1);
            }

            conn.rs = conn.st
                    .executeQuery("select site_name from sites where site_id='" + siteids.get(u) + "'");
            if (conn.rs.next()) {
                sitename = conn.rs.getString(1);
            }

            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short) 12);
            font.setFontName("Cambria");
            //    font.setItalic(true);
            font.setBoldweight((short) 02);
            font.setColor(HSSFColor.BLACK.index);
            CellStyle style = wb.createCellStyle();
            style.setFont(font);
            style.setWrapText(true);
            style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

            style.setAlignment(style.ALIGN_CENTER);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

            //%%%%%%%%%%%%%%%%HEADER FONTS AND COLORATION%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            HSSFFont font_header = wb.createFont();
            font_header.setFontHeightInPoints((short) 10);
            font_header.setFontName("Eras Bold ITC");
            //    font.setItalic(true);
            font_header.setBoldweight((short) 05);
            font_header.setColor(HSSFColor.BLACK.index);
            CellStyle style_header = wb.createCellStyle();
            style_header.setFont(font_header);
            style_header.setWrapText(true);
            style_header.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
            style_header.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style_header.setAlignment(style_header.ALIGN_CENTER);

            //            style_header.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderLeft(HSSFCellStyle.BORDER_THIN);

            //%%%%%%%%%%%%%%%%%%%%%%%%%DATA FONT%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            //font data
            HSSFFont datafont = wb.createFont();
            datafont.setBoldweight((short) 03);
            datafont.setColor(HSSFColor.BLACK.index);
            datafont.setFontHeightInPoints((short) 10);
            datafont.setFontName("Cambria");
            datafont.setItalic(true);

            //bold font 
            HSSFFont bolfont = wb.createFont();

            bolfont.setBoldweight((short) 05);
            bolfont.setColor(HSSFColor.BLACK.index);
            bolfont.setFontHeightInPoints((short) 12);
            bolfont.setFontName("Cambria");

            //=======INNER DATA STYLING===========================

            CellStyle innerdata_style = wb.createCellStyle();
            innerdata_style.setFont(datafont);
            innerdata_style.setWrapText(true);
            innerdata_style.setAlignment(innerdata_style.ALIGN_CENTER);
            innerdata_style.setFillForegroundColor(HSSFColor.WHITE.index);
            innerdata_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            innerdata_style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle lastcellrighborder = wb.createCellStyle();
            lastcellrighborder.setFont(datafont);
            lastcellrighborder.setWrapText(true);
            lastcellrighborder.setAlignment(lastcellrighborder.ALIGN_CENTER);
            lastcellrighborder.setFillForegroundColor(HSSFColor.WHITE.index);
            lastcellrighborder.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            lastcellrighborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            lastcellrighborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
            lastcellrighborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            lastcellrighborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            lastcellrighborder.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle innerdata_style2 = wb.createCellStyle();
            innerdata_style2.setFont(bolfont);
            innerdata_style2.setWrapText(true);
            innerdata_style2.setAlignment(innerdata_style.ALIGN_LEFT);
            innerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
            innerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            innerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            //Code colors

            CellStyle lg = wb.createCellStyle();
            lg.setFont(bolfont);
            lg.setWrapText(true);
            lg.setAlignment(lg.ALIGN_CENTER);
            lg.setFillForegroundColor(HSSFColor.GREEN.index);
            lg.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            lg.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            lg.setBorderTop(HSSFCellStyle.BORDER_THIN);
            lg.setBorderRight(HSSFCellStyle.BORDER_THIN);
            lg.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            lg.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle Y = wb.createCellStyle();
            Y.setFont(bolfont);
            Y.setWrapText(true);
            Y.setAlignment(Y.ALIGN_CENTER);
            Y.setFillForegroundColor(HSSFColor.YELLOW.index);
            Y.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            Y.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            Y.setBorderTop(HSSFCellStyle.BORDER_THIN);
            Y.setBorderRight(HSSFCellStyle.BORDER_THIN);
            Y.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            Y.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle R = wb.createCellStyle();
            R.setFont(bolfont);
            R.setWrapText(true);
            R.setAlignment(R.ALIGN_CENTER);
            R.setFillForegroundColor(HSSFColor.RED.index);
            R.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            R.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            R.setBorderTop(HSSFCellStyle.BORDER_THIN);
            R.setBorderRight(HSSFCellStyle.BORDER_THIN);
            R.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            R.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            //=======INNER LEFT DATA STYLING===========================

            CellStyle binnerdata_style2 = wb.createCellStyle();
            binnerdata_style2.setFont(datafont);
            binnerdata_style2.setWrapText(true);
            binnerdata_style2.setAlignment(binnerdata_style2.ALIGN_LEFT);
            binnerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
            binnerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            binnerdata_style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            //create a header

            //=======================Domainname styles
            CellStyle dnamestyle = wb.createCellStyle();
            dnamestyle.setFont(bolfont);
            dnamestyle.setWrapText(true);
            dnamestyle.setAlignment(dnamestyle.ALIGN_LEFT);
            dnamestyle.setFillForegroundColor(HSSFColor.WHITE.index);
            dnamestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            dnamestyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            shet2 = wb.createSheet(sitename.toUpperCase());
            shet2.setColumnWidth(0, 10000);
            shet2.setColumnWidth(1, 5000);
            shet2.setColumnWidth(2, 5000);
            shet2.setColumnWidth(3, 5000);
            shet2.setColumnWidth(4, 8000);
            shet2.setColumnWidth(5, 8000);
            //create header one
            HSSFRow header = shet2.createRow(0);
            header.setHeightInPoints(30);
            HSSFCell cel1 = header.createCell(0);
            cel1.setCellValue("APHIAplus NURU YA BONDE");
            cel1.setCellStyle(style);
            for (int b = 1; b <= 5; b++) {
                cel1 = header.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(style);
            }

            shet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));

            //create header two
            HSSFRow header2 = shet2.createRow(1);
            header2.setHeightInPoints(28);
            HSSFCell cel2 = null;
            for (int b = 1; b <= 5; b++) {
                cel2 = header2.createCell(b);
                cel2.setCellValue("");
                cel2.setCellStyle(style);
            }

            cel2 = header2.createCell(0);
            cel2.setCellValue("OVC LIP SUPPORT SUPERVISION DASH BOARD");
            cel2.setCellStyle(style);

            shet2.addMergedRegion(new CellRangeAddress(1, 1, 0, 5));

            //cbo name
            //create header three
            HSSFRow header3 = shet2.createRow(2);
            HSSFCell cel3 = header3.createCell(0);
            cel3.setCellValue("Name of LIP/CBO");
            cel3.setCellStyle(innerdata_style2);

            HSSFCell cel4 = header3.createCell(1);
            cel4.setCellValue("" + cboname);
            cel4.setCellStyle(innerdata_style);
            //blank cells for purpose of clear worksheet only
            for (int x = 2; x <= 3; x++) {
                HSSFCell cel = header3.createCell(x);
                cel.setCellValue("");
                cel.setCellStyle(innerdata_style);
            }

            HSSFCell cel5 = header3.createCell(4);
            cel5.setCellValue("Site Visited:");
            cel5.setCellStyle(innerdata_style2);

            HSSFCell cel6 = header3.createCell(5);
            cel6.setCellValue("" + sitename);
            cel6.setCellStyle(lastcellrighborder);

            //add the width of this column

            //create a blank row whose last cell has a border

            HSSFRow blankrw = shet2.createRow(3);
            for (int z = 0; z < 5; z++) {

                HSSFCell cl = blankrw.createCell(z);
                cl.setCellValue("");
                cl.setCellStyle(innerdata_style);
            }
            HSSFCell cl = blankrw.createCell(5);
            cl.setCellValue("");
            cl.setCellStyle(lastcellrighborder);
            //==========DATE OF VISIT

            String mywhere = "site='" + siteids.get(u) + "' and period='" + periods.get(u) + "' and year='"
                    + years.get(u) + "' ";

            String supervisor = "";
            String dateofvisit = "";

            String strengths = "";
            String constraints = "";

            String loadbasicdetails = "select * from backgroundinfor join staff on backgroundinfor.supervisor=staff.staff_id where "
                    + mywhere + " ";
            System.out.println(loadbasicdetails);
            conn.rs = conn.st.executeQuery(loadbasicdetails);
            while (conn.rs.next()) {
                supervisor = conn.rs.getString("fname") + " " + conn.rs.getString("mname");
                dateofvisit = conn.rs.getString("ass_date");
                strengths = conn.rs.getString("strengths");
                constraints = conn.rs.getString("constraints");

            }

            //================Create the second header=================
            //create header three
            HSSFRow header4 = shet2.createRow(4);
            HSSFCell cel = header4.createCell(0);
            cel.setCellValue("Date of Visit");
            cel.setCellStyle(innerdata_style2);

            HSSFCell cell = header4.createCell(1);
            cell.setCellValue("" + dateofvisit);
            cell.setCellStyle(innerdata_style);

            //blank cells for purpose of clear worksheet only
            for (int x = 2; x <= 3; x++) {
                HSSFCell ceel = header4.createCell(x);
                ceel.setCellValue("");
                ceel.setCellStyle(innerdata_style);
            }

            HSSFCell cell5 = header4.createCell(4);
            cell5.setCellValue("Supervision Team Lead:");
            cell5.setCellStyle(innerdata_style2);

            HSSFCell cell6 = header4.createCell(5);
            cell6.setCellValue("" + supervisor);
            cell6.setCellStyle(lastcellrighborder);

            //another blank row
            HSSFRow blankrw2 = shet2.createRow(5);
            for (int z = 0; z < 5; z++) {

                HSSFCell cl2 = blankrw2.createCell(z);
                cl2.setCellValue("");
                cl2.setCellStyle(innerdata_style);
            }
            HSSFCell cl2 = blankrw2.createCell(5);
            cl2.setCellValue("");
            cl2.setCellStyle(lastcellrighborder);

            //create a header

            String theaderar[] = { "Assesment Domain", "LG", "Y", "R", "Comments/Action", "" };

            HSSFRow theader = shet2.createRow(6);

            for (int x = 0; x < theaderar.length; x++) {
                HSSFCell tcel = theader.createCell(x);
                tcel.setCellValue(theaderar[x]);
                if (theaderar[x].equalsIgnoreCase("LG")) {
                    tcel.setCellStyle(lg);
                } else if (theaderar[x].equalsIgnoreCase("Y")) {
                    tcel.setCellStyle(Y);
                } else if (theaderar[x].equalsIgnoreCase("R")) {
                    tcel.setCellStyle(R);
                } else {
                    tcel.setCellStyle(style);
                }

            }
            shet2.addMergedRegion(new CellRangeAddress(6, 6, 4, 5));
            //SECTION A HEADER
            HSSFRow seca = shet2.createRow(7);
            HSSFCell tcel1 = seca.createCell(0);
            tcel1.setCellValue("Section A: Data management and Reporting Systems");
            tcel1.setCellStyle(style);
            for (int b = 1; b <= 5; b++) {
                cel1 = seca.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(style);
            }

            shet2.addMergedRegion(new CellRangeAddress(7, 7, 0, 5));

            String gettables = "SELECT domain_name,domains.domain_id as domainid,section_name,domains.section_id as secid,value as domainvalue,aggregate_sum,period,year,site FROM domains join sections on domains.section_id=sections.section_id join domain_totals on domains.domain_id=domain_totals.domainid where "
                    + mywhere + " order by domainid";
            System.out.println(gettables);
            conn.rs = conn.st.executeQuery(gettables);
            int rwcount = 8;
            HSSFRow rwx = null;
            HSSFCell celx = null;
            String sectioncopy = "";
            while (conn.rs.next()) {
                if (sectioncopy.equals("")) {
                    sectioncopy = conn.rs.getString("section_name");
                }
                //if the section has changed
                if (!sectioncopy.equals(conn.rs.getString("section_name"))) {
                    //create a section header
                    //``````````````````````````````INNER SECTION HEADERS``````````````````            
                    //``````````````````````````````INNER SECTION HEADERS``````````````````            
                    //``````````````````````````````INNER SECTION HEADERS``````````````````            
                    HSSFRow secb = shet2.createRow(rwcount);
                    HSSFCell t = secb.createCell(0);
                    t.setCellValue("Section " + conn.rs.getString("section_name"));
                    t.setCellStyle(style);
                    //for purpose of merging
                    for (int b = 1; b <= 5; b++) {
                        cel1 = secb.createCell(b);
                        cel1.setCellValue("");
                        cel1.setCellStyle(style);
                    }
                    //equalize copy and current value       
                    sectioncopy = conn.rs.getString("section_name");
                    shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

                    //increment rowcount to skip the current row 
                    rwcount++;
                }

                String valu[] = { conn.rs.getString("domain_name"), "", "", "", "", "" };

                rwx = shet2.createRow(rwcount);
                for (int t = 0; t < valu.length; t++) {
                    celx = rwx.createCell(t);
                    celx.setCellValue("" + valu[t]);
                    celx.setCellStyle(dnamestyle);
                }
                shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 4, 5));
                //get the value of percentange achievement per domian
                //multiply by 100
                //round off
                float domainvalue = conn.rs.getFloat("domainvalue");

                domainvalue = domainvalue * 100;
                //BigDecimal bd=new BigDecimal(domainvalue).setScale(0,RoundingMode.HALF_EVEN);
                //domainval=bd.doubleValue();
                domainvalue = Math.round(domainvalue);

                //determine the cell to print data on
                if (domainvalue >= 75) {

                    celx = rwx.createCell(1);
                    celx.setCellValue("" + domainvalue + "%");
                    celx.setCellStyle(lg);

                } else if (domainvalue >= 60 && domainvalue < 75) {
                    celx = rwx.createCell(2);
                    celx.setCellValue("" + domainvalue + "%");
                    celx.setCellStyle(Y);

                } else if (domainvalue < 60) {

                    celx = rwx.createCell(3);
                    celx.setCellValue("" + domainvalue + "%");
                    celx.setCellStyle(R);
                }

                rwcount++;
            }

            ///=========================end of while loop 

            //====================STRENGTHS=========================== 
            HSSFRow secb = shet2.createRow(rwcount);

            //for purpose of merging
            for (int b = 1; b <= 5; b++) {
                cel1 = secb.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(style);
            }

            HSSFCell t = secb.createCell(0);
            t.setCellValue("What has worked well and key areas of strengths observed");
            t.setCellStyle(style);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

            rwcount++;

            HSSFRow str = shet2.createRow(rwcount);

            for (int b = 1; b <= 5; b++) {
                cel1 = str.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(dnamestyle);
            }

            HSSFCell t1 = str.createCell(0);
            t1.setCellValue("" + strengths);
            t1.setCellStyle(dnamestyle);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));
            //for purpose of merging

            str.setHeightInPoints(60);
            rwcount++;

            //=======Contraints
            HSSFRow sec3 = shet2.createRow(rwcount);

            //for purpose of merging
            for (int b = 1; b <= 5; b++) {
                cel1 = sec3.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(style);
            }

            HSSFCell t2 = sec3.createCell(0);
            t2.setCellValue("Critical consraints affecting quality programming and data management");
            t2.setCellStyle(style);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));

            rwcount++;

            HSSFRow str2 = shet2.createRow(rwcount);

            for (int b = 1; b <= 5; b++) {
                cel1 = str2.createCell(b);
                cel1.setCellValue("");
                cel1.setCellStyle(dnamestyle);
            }

            HSSFCell t4 = str2.createCell(0);
            t4.setCellValue("" + constraints);
            t4.setCellStyle(dnamestyle);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, 5));
            str2.setHeightInPoints(50);

            rwcount++;
            //a line of codes
            String codes[] = { "LG - Meets Expectations (>=75%); ", " Y- Needs Improvement (60%- 74%);",
                    "R - Needs Urgent Attention (<=59%);" };
            HSSFRow rwl = shet2.createRow(rwcount);
            HSSFCell ce = rwl.createCell(0);
            ce.setCellValue("CODES");
            ce.setCellStyle(dnamestyle);
            for (int b = 0; b < codes.length; b++) {
                ce = rwl.createCell(b + 1);
                ce.setCellValue("" + codes[b]);
                if (b == 0) {
                    ce.setCellStyle(lg);
                } else if (b == 1) {

                    ce.setCellStyle(Y);
                } else {
                    ce.setCellStyle(R);
                }
            }
            ce = rwl.createCell(4);
            ce.setCellValue("");
            ce.setCellStyle(dnamestyle);
            ce = rwl.createCell(5);
            ce.setCellValue("");
            ce.setCellStyle(dnamestyle);
            shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 4, 5));

        }

        //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=OVC_LIP_REPORT_Multiple_SITES_" + startdate + "_" + enddate + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(basicreports.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:reports.notReached.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, InvalidFormatException {
    session = request.getSession();//w  w w  .j a  v a 2  s  .com
    dbConn conn = new dbConn();

    position = 1;

    String reportHeader[] = ("COUNTY NAME ,PARTNER NAME,DISTRICT NAME, DIC NAME, GROUP NAME,CLIENT FULL NAME ,"
            + " CCC NO. , MOBILE NUMBER , GENDER , DATE OF BIRTH , MARITAL STATUS , EMPLOYMENT STATUS ,"
            + "EDUCATION LEVEL , ART STATUS , SERVICE PROVIDER NAME , HEALTH FACILITY, LESSONS ATTENDED,AGE BRACKET, Knowledge of HIV Status,"
            + "Partner HIV Testing,Child HIV Testing,Discordance,HIV Disclosure,Risk Factor/Reduction,Condom Use,"
            + "Alcohol and Substance Abuse,Adherence,STIs,Family Planning,PMTCT,TB").split(",");

    //    COPY FILE TO BE WRITTEN TO 
    Path original = Paths.get(getServletContext().getRealPath("/NOT_ACHIEVED_TEMPLATE.xlsm")); //original file
    Path destination = Paths.get(getServletContext().getRealPath("/NOT_ACHIEVED_TEMPLATE_1.xlsm")); //new file
    System.out.println("origin :  " + original + " destination    :  " + destination);
    try {
        Files.copy(original, destination, StandardCopyOption.REPLACE_EXISTING);
        System.out.println("file copied----------------");
    } catch (IOException x) {
        //catch all for IO problems
        System.out.println("fine not copied");
    }

    String allpath = getServletContext().getRealPath("/NOT_ACHIEVED_TEMPLATE_1.xlsm");

    //            ^^^^^^^^^^^^^CREATE STATIC AND WRITE STATIC DATA TO THE EXCELL^^^^^^^^^^^^
    XSSFWorkbook wb1;
    OPCPackage pkg = OPCPackage.open(allpath);

    wb1 = new XSSFWorkbook(pkg);

    SXSSFWorkbook wb = new SXSSFWorkbook(wb1, 100);

    //            ^^^^^^^^^^^^^CREATE STATIC AND WRITE STATIC DATA TO THE EXCELL^^^^^^^^^^^^
    //   HSSFWorkbook wb=new HSSFWorkbook();
    Sheet shet1 = wb.getSheet("Sheet1");
    Font 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);
    Font font2 = wb.createFont();
    font2.setFontName("Arial Black");
    font2.setColor((short) 0000);
    CellStyle style2 = wb.createCellStyle();
    style2.setFont(font2);

    CellStyle 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);

    for (int i = 0; i <= reportHeader.length; i++) {
        shet1.setColumnWidth(i, 4000);
    }

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

    CellStyle stylex = wb.createCellStyle();
    stylex.setFillForegroundColor(HSSFColor.LIME.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);

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

    Cell cell;
    Row rw0 = shet1.createRow(0);
    rw0.setHeightInPoints(30);
    rw0.setRowStyle(style2);

    for (int i = 0; i <= (reportHeader.length - 1); i++) {
        cell = rw0.createCell(i);
        cell.setCellValue(reportHeader[i]);
        cell.setCellStyle(stylex);
    }

    String getClients = "SELECT county.county_name,partner.partner_name,district.district_name,dic.dic_name,"
            + "groups.group_name,personal_information.fname,personal_information.mname,personal_information.lname,"
            + "personal_information.ccc_no,personal_information.mobile_no, personal_information.gender,"
            + "personal_information.dob,marital_status.name,employment_status.name,education_levels.name,"
            + "art_status.name,"
            + "service_provider.fname,service_provider.mname,service_provider.lname,health_facility.hf_name, "
            + "personal_information.lessons_attended," + "CASE"
            + "      WHEN (DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( personal_information.dob, '%Y' )-( DATE_FORMAT( NOW( ),'YYYY-%mm-%dd' )< DATE_FORMAT( personal_information.dob, 'YYYY-%mm-%dd' ) )) BETWEEN 0 AND 9 THEN '0-9'"
            + "      WHEN (DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( personal_information.dob, '%Y' )-( DATE_FORMAT( NOW( ),'YYYY-%mm-%dd' )< DATE_FORMAT( personal_information.dob, 'YYYY-%mm-%dd' ) )) BETWEEN 10 AND 14 THEN '10-14'"
            + "      WHEN (DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( personal_information.dob, '%Y' )-( DATE_FORMAT( NOW( ),'YYYY-%mm-%dd' )< DATE_FORMAT( personal_information.dob, 'YYYY-%mm-%dd' ) )) BETWEEN 15 AND 19 THEN '15-19'"
            + "      WHEN (DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( personal_information.dob, '%Y' )-( DATE_FORMAT( NOW( ),'YYYY-%mm-%dd' )< DATE_FORMAT( personal_information.dob, 'YYYY-%mm-%dd' ) )) BETWEEN 20 AND 24 THEN '20-24'"
            + "      WHEN (DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( personal_information.dob, '%Y' )-( DATE_FORMAT( NOW( ),'YYYY-%mm-%dd' )< DATE_FORMAT( personal_information.dob, 'YYYY-%mm-%dd' ) )) BETWEEN 25 AND 49 THEN '25-49'"
            + "      WHEN (DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( personal_information.dob, '%Y' )-( DATE_FORMAT( NOW( ),'YYYY-%mm-%dd' )< DATE_FORMAT( personal_information.dob, 'YYYY-%mm-%dd' ) )) >49 THEN '50 and above'"
            + " ELSE 'NO DATE OF BIRTH'" + "   END AS AGEBRACKET," + "CASE "
            + "when personal_information.gender LIKE 'Female' THEN 'F' "
            + "when personal_information.gender LIKE 'Male' THEN 'M' " + "ELSE 'NO SEX' "
            + "END AS SEX,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13 " + " FROM personal_information "
            + " LEFT JOIN groups ON personal_information.group_id=groups.group_id "
            + " LEFT JOIN dic ON personal_information.dic_id=dic.dic_id "
            + " LEFT JOIN service_provider ON personal_information.provider_id=service_provider.provider_id "
            + " LEFT JOIN health_facility ON personal_information.hf_id=health_facility.hf_id "
            + " LEFT JOIN district ON personal_information.district_id=district.district_id "

            + " LEFT JOIN marital_status ON personal_information.marital_status=marital_status.id "
            + " LEFT JOIN employment_status ON personal_information.employment_status=employment_status.id "
            + " LEFT JOIN education_levels ON personal_information.education_level=education_levels.id "
            + " LEFT JOIN art_status ON personal_information.art_status=art_status.id "
            + " LEFT JOIN register ON personal_information.client_id=register.client_id "

            + " LEFT JOIN partner ON personal_information.partner_id=partner.partner_id "
            + " LEFT JOIN county ON district.county_id=county.county_id "

            + " WHERE (personal_information.completionmonth=0 || personal_information.completionyear=0) "
            + " ORDER BY partner.partner_name,county.county_name,district.district_name,dic.dic_name,"
            + "groups.group_name";
    System.out.println("query is : " + getClients);
    conn.rs = conn.st.executeQuery(getClients);
    while (conn.rs.next()) {
        //     ADD THE DATA TO EXCEL HERE 
        groupName = DICName = districtName = partnerName = countyName = agebracket = lessons_attended = year = "";
        clientFname = clientMname = clientLname = ccc_no = mobile_no = gender = dob = marital_status = "";
        location = employment_status = education_level = under_18 = ovc_children = hiv_year = art_status = "";
        registration_date = approved_by = designation = approval_date = "";
        SPFname = SPMname = SPLname = SPFullName = healthFacility = "";
        s1 = s2 = s3 = s4 = s5 = s6 = s7 = s8 = s9 = s10 = s11 = s12 = s13 = "";
        if (conn.rs.getString(1) != null) {
            countyName = conn.rs.getString(1);
        }
        if (conn.rs.getString(2) != null) {
            partnerName = conn.rs.getString(2);
        }
        if (conn.rs.getString(3) != null) {
            districtName = conn.rs.getString(3);
        }
        if (conn.rs.getString(4) != null) {
            DICName = conn.rs.getString(4);
        } else {
            DICName = "NO DIC";
        }

        if (conn.rs.getString(5) != null) {
            groupName = conn.rs.getString(5);
        } else {
            groupName = "Individual";
        }

        if (conn.rs.getString(6) != null) {
            clientFname = conn.rs.getString(6);
        }
        if (conn.rs.getString(7) != null) {
            clientMname = conn.rs.getString(7);
        }
        if (conn.rs.getString(8) != null) {
            clientLname = conn.rs.getString(8);
        }
        if (conn.rs.getString(9) != null) {
            ccc_no = conn.rs.getString(9);
        }
        if (conn.rs.getString(10) != null) {
            mobile_no = conn.rs.getString(10);
        }
        if (conn.rs.getString(11) != null) {
            gender = conn.rs.getString(11);
        }
        if (conn.rs.getString(12) != null) {
            dob = conn.rs.getString(12);
        }
        if (conn.rs.getString(13) != null) {
            marital_status = conn.rs.getString(13);
        }
        if (conn.rs.getString(14) != null) {
            employment_status = conn.rs.getString(14);
        }
        if (conn.rs.getString(15) != null) {
            education_level = conn.rs.getString(15);
        }
        if (conn.rs.getString(16) != null) {
            art_status = conn.rs.getString(16);
        }
        if (conn.rs.getString(17) != null) {
            SPFname = conn.rs.getString(17);
        }
        if (conn.rs.getString(18) != null) {
            SPMname = conn.rs.getString(18);
        }
        if (conn.rs.getString(19) != null) {
            SPLname = conn.rs.getString(19);
        }
        if (conn.rs.getString(20) != null) {
            healthFacility = conn.rs.getString(20);
        }
        if (conn.rs.getString(21) != null) {
            lessons_attended = conn.rs.getString(21);
        }
        if (conn.rs.getString(22) != null) {
            agebracket = conn.rs.getString(22);
        }
        if (conn.rs.getString(23) != null) {
            gender = conn.rs.getString(23);
        }

        if (conn.rs.getString(24) != null) {
            s1 = conn.rs.getString(24);
        }
        if (conn.rs.getString(25) != null) {
            s2 = conn.rs.getString(25);
        }
        if (conn.rs.getString(26) != null) {
            s3 = conn.rs.getString(26);
        }
        if (conn.rs.getString(27) != null) {
            s4 = conn.rs.getString(27);
        }
        if (conn.rs.getString(28) != null) {
            s5 = conn.rs.getString(28);
        }
        if (conn.rs.getString(29) != null) {
            s6 = conn.rs.getString(29);
        }
        if (conn.rs.getString(30) != null) {
            s7 = conn.rs.getString(30);
        }
        if (conn.rs.getString(31) != null) {
            s8 = conn.rs.getString(31);
        }
        if (conn.rs.getString(32) != null) {
            s9 = conn.rs.getString(32);
        }
        if (conn.rs.getString(33) != null) {
            s10 = conn.rs.getString(33);
        }
        if (conn.rs.getString(34) != null) {
            s11 = conn.rs.getString(34);
        }
        if (conn.rs.getString(35) != null) {
            s12 = conn.rs.getString(35);
        }
        if (conn.rs.getString(36) != null) {
            s13 = conn.rs.getString(36);
        }

        if (s1.equals("5")) {
            s1 = "";
        }
        if (s1.equals("2")) {
            s1 = "0";
        }
        if (s2.equals("5")) {
            s2 = "";
        }
        if (s2.equals("2")) {
            s2 = "0";
        }
        if (s3.equals("5")) {
            s3 = "";
        }
        if (s3.equals("2")) {
            s3 = "0";
        }
        if (s4.equals("5")) {
            s4 = "";
        }
        if (s4.equals("2")) {
            s4 = "0";
        }
        if (s5.equals("5")) {
            s5 = "";
        }
        if (s5.equals("2")) {
            s5 = "0";
        }
        if (s6.equals("5")) {
            s6 = "";
        }
        if (s6.equals("2")) {
            s6 = "0";
        }
        if (s7.equals("5")) {
            s7 = "";
        }
        if (s7.equals("2")) {
            s7 = "0";
        }
        if (s8.equals("5")) {
            s8 = "";
        }
        if (s8.equals("2")) {
            s8 = "0";
        }
        if (s9.equals("5")) {
            s9 = "";
        }
        if (s9.equals("2")) {
            s9 = "0";
        }
        if (s10.equals("5")) {
            s10 = "";
        }
        if (s10.equals("2")) {
            s10 = "0";
        }
        if (s11.equals("5")) {
            s11 = "";
        }
        if (s11.equals("2")) {
            s11 = "0";
        }
        if (s12.equals("5")) {
            s12 = "";
        }
        if (s12.equals("2")) {
            s12 = "0";
        }
        if (s13.equals("5")) {
            s13 = "";
        }
        if (s13.equals("2")) {
            s13 = "0";
        }

        if (clientMname.equals(clientLname)) {
            clientMname = "";
        }

        if (SPMname.equals(SPLname)) {
            SPMname = "";
        }

        SPFullName = SPFname + " " + SPMname + " " + SPLname;
        clientFullName = clientFname + " " + clientMname + " " + clientLname;

        String rawData[] = (countyName + "," + partnerName + "," + districtName + "," + DICName + ","
                + groupName + "," + clientFullName + "," + ccc_no + "," + mobile_no + "," + gender + "," + dob
                + "," + marital_status + "," + employment_status + "," + education_level + "," + art_status
                + "," + SPFullName + "," + healthFacility + "," + lessons_attended + "," + agebracket + "," + s1
                + "," + s2 + "," + s3 + "," + s4 + "," + s5 + "," + s6 + "," + s7 + "," + s8 + "," + s9 + ","
                + s10 + "," + s11 + "," + s12 + "," + s13).split(",");

        Row rw1 = shet1.createRow(position);
        rw1.setHeightInPoints(25);
        rw1.setRowStyle(style2);

        for (int i = 0; i <= (reportHeader.length - 1); i++) {
            cell = rw1.createCell(i);
            cell.setCellStyle(styleBorder);
        }

        for (int i = 0; i <= (rawData.length - 1); i++) {
            cell = rw1.getCell(i);
            cell.setCellValue(rawData[i]);
        }

        position++;
        System.out.println("at position : " + position);
    }

    IdGenerator CRT = new IdGenerator();
    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=PWP_CLIENTS_NOT_REACHED_REPORT_CREATED_ON_" + CRT.timestamp() + ".xlsm");
    OutputStream outStream = response.getOutputStream();
    outStream.write(outArray);
    outStream.flush();

    pkg.close();
}

From source file:reports.OverallCharts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  ww .  ja  v  a2  s.c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        dbConn conn = new dbConn();

        wb = new HSSFWorkbook();

        HSSFSheet shet2 = null;

        String year = "";
        String site = "";
        String period = "";
        String cbo = "";
        String startdate = "2015-01-01";
        String enddate = "2015-03-30";

        // startdate=request.getParameter("startdate");
        //enddate=request.getParameter("enddate");

        String getdistinctsites = "SELECT county.county_id as countyid,county_name FROM ovc_lip.backgroundinfor join (sites join (district join county on district.county_id=county.county_id) on sites.districtid=district.district_id) on backgroundinfor.site=sites.site_id where ass_date between '"
                + startdate + "' and '" + enddate + "' group by county_name ";

        ArrayList countyids = new ArrayList();
        ArrayList countynames = new ArrayList();
        countyids.add("1000");
        countynames.add("OVERALL COUNTIES REPORT");
        //ArrayList years=new ArrayList();
        //ArrayList periods=new ArrayList();
        //ArrayList cbos=new ArrayList();
        conn.rs = conn.st.executeQuery(getdistinctsites);
        while (conn.rs.next()) {

            countyids.add(conn.rs.getString(1));
            countynames.add(conn.rs.getString(2).toUpperCase() + " COUNTY");

        }
        String sitename = "";
        String cboname = "";

        //begin a loop that will create as many reports as possible

        for (int u = 0; u < countyids.size(); u++) {

            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short) 12);
            font.setFontName("Cambria");
            //    font.setItalic(true);
            font.setBoldweight((short) 02);
            font.setColor(HSSFColor.BLACK.index);
            CellStyle style = wb.createCellStyle();
            style.setFont(font);
            style.setWrapText(true);
            style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

            style.setAlignment(style.ALIGN_CENTER);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

            //%%%%%%%%%%%%%%%%HEADER FONTS AND COLORATION%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            HSSFFont font_header = wb.createFont();
            font_header.setFontHeightInPoints((short) 10);
            font_header.setFontName("Eras Bold ITC");
            //    font.setItalic(true);
            font_header.setBoldweight((short) 05);
            font_header.setColor(HSSFColor.BLACK.index);
            CellStyle style_header = wb.createCellStyle();
            style_header.setFont(font_header);
            style_header.setWrapText(true);
            style_header.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
            style_header.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style_header.setAlignment(style_header.ALIGN_CENTER);

            //            style_header.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            style_header.setBorderLeft(HSSFCellStyle.BORDER_THIN);

            //%%%%%%%%%%%%%%%%%%%%%%%%%DATA FONT%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            //font data
            HSSFFont datafont = wb.createFont();
            datafont.setBoldweight((short) 03);
            datafont.setColor(HSSFColor.BLACK.index);
            datafont.setFontHeightInPoints((short) 10);
            datafont.setFontName("Cambria");
            datafont.setItalic(true);

            //bold font 
            HSSFFont bolfont = wb.createFont();

            bolfont.setBoldweight((short) 05);
            bolfont.setColor(HSSFColor.BLACK.index);
            bolfont.setFontHeightInPoints((short) 12);
            bolfont.setFontName("Cambria");

            //=========================ROW STYLE===============================

            HSSFCellStyle rowstyle = wb.createCellStyle();
            rowstyle.setWrapText(true);

            //=======INNER DATA STYLING===========================

            CellStyle innerdata_style = wb.createCellStyle();
            innerdata_style.setFont(datafont);
            innerdata_style.setWrapText(true);
            innerdata_style.setAlignment(innerdata_style.ALIGN_CENTER);
            innerdata_style.setFillForegroundColor(HSSFColor.WHITE.index);
            innerdata_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            innerdata_style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle lastcellrighborder = wb.createCellStyle();
            lastcellrighborder.setFont(datafont);
            lastcellrighborder.setWrapText(true);
            lastcellrighborder.setAlignment(lastcellrighborder.ALIGN_CENTER);
            lastcellrighborder.setFillForegroundColor(HSSFColor.WHITE.index);
            lastcellrighborder.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            lastcellrighborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            lastcellrighborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
            lastcellrighborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            lastcellrighborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            lastcellrighborder.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle innerdata_style2 = wb.createCellStyle();
            innerdata_style2.setFont(bolfont);
            innerdata_style2.setWrapText(true);
            innerdata_style2.setAlignment(innerdata_style.ALIGN_LEFT);
            innerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
            innerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //            innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //            innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            innerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle orangestyle = wb.createCellStyle();
            orangestyle.setFont(bolfont);
            orangestyle.setWrapText(true);
            orangestyle.setAlignment(orangestyle.ALIGN_CENTER);
            orangestyle.setFillForegroundColor(HSSFColor.ORANGE.index);
            orangestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //          innerdata_style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            //          innerdata_style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            //          innerdata_style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            //          innerdata_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            orangestyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            //Code colors

            CellStyle lg = wb.createCellStyle();
            lg.setFont(bolfont);
            lg.setWrapText(true);
            lg.setAlignment(lg.ALIGN_CENTER);
            lg.setFillForegroundColor(HSSFColor.GREEN.index);
            lg.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            lg.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            lg.setBorderTop(HSSFCellStyle.BORDER_THIN);
            lg.setBorderRight(HSSFCellStyle.BORDER_THIN);
            lg.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            lg.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle Y = wb.createCellStyle();
            Y.setFont(bolfont);
            Y.setWrapText(true);
            Y.setAlignment(Y.ALIGN_CENTER);
            Y.setFillForegroundColor(HSSFColor.WHITE.index);
            Y.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            Y.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            Y.setBorderTop(HSSFCellStyle.BORDER_THIN);
            Y.setBorderRight(HSSFCellStyle.BORDER_THIN);
            Y.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            Y.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            CellStyle R = wb.createCellStyle();
            R.setFont(bolfont);
            R.setWrapText(true);
            R.setAlignment(R.ALIGN_CENTER);
            R.setFillForegroundColor(HSSFColor.RED.index);
            R.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            R.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            R.setBorderTop(HSSFCellStyle.BORDER_THIN);
            R.setBorderRight(HSSFCellStyle.BORDER_THIN);
            R.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            R.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            //=======INNER LEFT DATA STYLING===========================

            CellStyle binnerdata_style2 = wb.createCellStyle();
            binnerdata_style2.setFont(datafont);
            binnerdata_style2.setWrapText(true);
            binnerdata_style2.setAlignment(binnerdata_style2.ALIGN_LEFT);
            binnerdata_style2.setFillForegroundColor(HSSFColor.WHITE.index);
            binnerdata_style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            binnerdata_style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            binnerdata_style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            //create a header

            //=======================Domainname styles
            CellStyle dnamestyle = wb.createCellStyle();
            dnamestyle.setFont(bolfont);
            dnamestyle.setWrapText(true);
            dnamestyle.setAlignment(dnamestyle.ALIGN_LEFT);
            dnamestyle.setFillForegroundColor(HSSFColor.WHITE.index);
            dnamestyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            dnamestyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            dnamestyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            shet2 = wb.createSheet(countynames.get(u).toString().toUpperCase());
            shet2.setColumnWidth(0, 12000);
            shet2.setColumnWidth(1, 12000);
            shet2.setColumnWidth(2, 4000);
            shet2.setColumnWidth(3, 10000);
            shet2.setColumnWidth(4, 5000);
            shet2.setColumnWidth(5, 5000);
            shet2.setColumnWidth(6, 5000);
            shet2.setColumnWidth(7, 5000);
            shet2.setColumnWidth(8, 5000);
            shet2.setColumnWidth(9, 5000);
            shet2.setColumnWidth(10, 5000);
            shet2.setColumnWidth(11, 5000);
            shet2.setColumnWidth(12, 5000);
            shet2.setColumnWidth(13, 5000);

            //11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111           
            //11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111           
            //11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111           
            //11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111  

            //String gettables= "SELECT  avg(aggregate_sum) as aggregate_sum FROM ovc_lip.domain_totals join (sites join cbo on sites.cbo_id=cbo.cboid) on domain_totals.site=sites.site_id join ( domains join sections on domains.section_id=sections.section_id ) on domain_totals.domainid=domains.domain_id "+mywhere+" group by cbo.cboid,domainid order by cbo,domainid";
            // String gettables= "SELECT avg(value) as domainvalue,domain_totals.domainid as domainid,domain_name, section_name,cbo,avg(aggregate_sum) as aggregate_sum FROM ovc_lip.domain_totals join (sites join cbo on sites.cbo_id=cbo.cboid) on domain_totals.site=sites.site_id join ( domains join sections on domains.section_id=sections.section_id ) on domain_totals.domainid=domains.domain_id "+mywhere+" group by cbo.cboid,domainid order by cbo,domainid";

            String gettables = "SELECT avg(value) as domainvalue,domain_totals.domainid as domainid,domain_name,section_name ,avg(aggregate_sum) as aggregate_sum , domains.section_id as secid FROM ovc_lip.domain_totals join (sites join (district join county on district.county_id=county.county_id) on sites.districtid=district.district_id) on domain_totals.site=sites.site_id join (domains join sections on domains.section_id=sections.section_id) on domain_totals.domainid=domains.domain_id  where county.county_id='"
                    + countyids.get(u) + "' and date between '" + startdate + "' and '" + enddate
                    + "' group by domain_totals.domainid,county_name order by domainid";
            //if its the first county, themn skip the county part
            if (countyids.get(u).toString().equalsIgnoreCase("1000")) {

                gettables = "SELECT avg(value) as domainvalue,domain_totals.domainid as domainid,domain_name,section_name ,avg(aggregate_sum) as aggregate_sum , domains.section_id as secid FROM ovc_lip.domain_totals  join (domains join sections on domains.section_id=sections.section_id) on domain_totals.domainid=domains.domain_id  where  date between '"
                        + startdate + "' and '" + enddate
                        + "' group by domain_totals.domainid order by domainid";

            }

            System.out.println(gettables);
            conn.rs = conn.st.executeQuery(gettables);
            int rwcount = 0;
            int rowcountcopy = 0;
            String tableheaders[] = { "Section", "Domain", "% Overall Achievement", "Column chart" };

            HSSFRow rwx = null;
            int monitorrows = 0;
            int secAcopy = 0;
            int secBcopy = 0;

            HSSFCell celx = null;
            int noofcols = 3;
            boolean isrow1 = true;
            while (conn.rs.next()) {
                //if the section has changed
                monitorrows++;
                String domainid = conn.rs.getString("domainid");
                float domainvalue = conn.rs.getFloat("domainvalue");
                domainvalue = domainvalue * 100;
                domainvalue = Math.round(domainvalue);
                float totalsum = conn.rs.getFloat("aggregate_sum");
                int dmn = (int) domainvalue;
                totalsum = Math.round(totalsum);
                //determine the cell to print data on
                int ttlsm = (int) totalsum;
                int hearderheight = 40;
                //if its the first row in each 
                if (isrow1) {
                    isrow1 = false;
                    rwx = shet2.createRow(rwcount);

                    HSSFCell headercel = rwx.createCell(0);
                    headercel.setCellValue(countynames.get(u).toString().toUpperCase());
                    headercel.setCellStyle(style);
                    rwx.setHeightInPoints(hearderheight);

                    //create a blank
                    HSSFCell cel = null;

                    for (int b = 1; b < tableheaders.length; b++) {
                        cel = rwx.createCell(b);
                        cel.setCellValue("");
                        cel.setCellStyle(style);
                    }
                    //now merge the header cell
                    shet2.addMergedRegion(new CellRangeAddress(rwcount, rwcount, 0, tableheaders.length - 1));
                    rwcount++;

                    //now create the header part

                    HSSFRow headerrw = shet2.createRow(rwcount);
                    rwx.setHeightInPoints(hearderheight);
                    for (int b = 0; b < tableheaders.length; b++) {
                        HSSFCell cel1 = headerrw.createCell(b);
                        cel1.setCellValue(tableheaders[b]);
                        cel1.setCellStyle(style);
                    }

                    rwcount++;
                }

                //create the section part

                HSSFRow rw = shet2.createRow(rwcount);

                rw.setHeightInPoints(25);
                //column one --- section

                HSSFCell seccell = rw.createCell(0);
                seccell.setCellValue(conn.rs.getString("section_name"));
                seccell.setCellStyle(dnamestyle);

                HSSFCell domcell = rw.createCell(1);
                domcell.setCellValue(conn.rs.getString("domain_name"));
                domcell.setCellStyle(dnamestyle);

                //values only
                HSSFCell domval = rw.createCell(2);
                domval.setCellValue(dmn);
                domval.setCellStyle(dnamestyle);

                HSSFCell blank = rw.createCell(3);
                blank.setCellValue("");
                blank.setCellStyle(dnamestyle);

                //now, draw the chart
                HSSFPatriarch patriarch = shet2.createDrawingPatriarch();
                HSSFTextbox textbox1 = patriarch.createTextbox(
                        new HSSFClientAnchor(0, 0, (dmn * 10), 255, (short) 3, rwcount, (short) 3, rwcount));
                textbox1.setString(new HSSFRichTextString("" + dmn));
                textbox1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                //green 18,174,55
                //red 250 32 32
                //yellow 248 255 9
                if (dmn >= 75) {
                    textbox1.setFillColor(18, 174, 55);
                } else if (dmn > 59 && dmn < 75) {

                    textbox1.setFillColor(248, 255, 9);

                }

                else {

                    textbox1.setFillColor(250, 32, 32);

                }
                rwcount++;

                if (monitorrows == 4) {
                    shet2.addMergedRegion(new CellRangeAddress(rwcount - 4, rwcount - 1, 0, 0));
                }

                if (monitorrows == 12) {

                    shet2.addMergedRegion(new CellRangeAddress(rwcount - 8, rwcount - 1, 0, 0));

                    HSSFRow lastrw = shet2.createRow(rwcount);
                    lastrw.setHeightInPoints(25);
                    //now create a row with average
                    HSSFCell avcell0 = lastrw.createCell(0);
                    avcell0.setCellValue("Average");
                    avcell0.setCellStyle(dnamestyle);

                    HSSFCell avcell = lastrw.createCell(1);
                    avcell.setCellValue("Average");
                    avcell.setCellStyle(dnamestyle);

                    HSSFCell avcell1 = lastrw.createCell(2);
                    avcell1.setCellValue(ttlsm);
                    avcell1.setCellStyle(dnamestyle);

                    HSSFCell blank1 = lastrw.createCell(3);
                    blank1.setCellValue("");
                    blank1.setCellStyle(dnamestyle);
                    HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor(0, 0, (dmn * (10)), 255,
                            (short) 3, rwcount, (short) 3, rwcount));
                    textbox.setString(new HSSFRichTextString("" + ttlsm));
                    if (dmn >= 75) {

                        textbox.setFillColor(18, 174, 55);

                    } else if (dmn > 59 && dmn < 75) {

                        textbox.setFillColor(248, 255, 9);

                    }

                    else {

                        textbox.setFillColor(250, 32, 32);

                    }
                    textbox.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

                    isrow1 = true;
                    monitorrows = 0;
                    //dont print anything 
                    rwcount++;

                    //last blank cell

                    HSSFRow blankrow = shet2.createRow(rwcount);
                    blankrow.setHeightInPoints(30);
                    for (int b = 0; b < tableheaders.length; b++) {
                        HSSFCell cel1 = blankrow.createCell(b);
                        cel1.setCellValue("");
                        cel1.setCellStyle(innerdata_style);
                    }

                    rwcount++;
                }

            }

            ///=========================end of while loop 

        } //end of each loop

        //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=OVC_COUNTY_CHARTS_FROM_" + startdate + "_TO_" + enddate + ".xls");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(resultspercbo.class.getName()).log(Level.SEVERE, null, ex);
    }

}