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

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

Introduction

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

Prototype

void setFont(Font font);

Source Link

Document

set the font for this style

Usage

From source file:output.ExcelM3Upgrad.java

/**
 * create a library of cell styles// w w w  .  j a  va  2 s .  com
 */
private static Map<String, CellStyle> createStyles(Workbook wb) {
    Map<String, CellStyle> styles = new HashMap<>();
    DataFormat df = wb.createDataFormat();

    Font font1 = wb.createFont();

    CellStyle style;
    Font headerFont = wb.createFont();
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFont(headerFont);
    styles.put("header", style);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font1);
    style.setLocked(false);
    styles.put("cell_centered", style);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font1);
    style.setLocked(true);
    styles.put("cell_centered_locked", style);
    //        style = createBorderedStyle(wb);
    //        style.setAlignment(CellStyle.ALIGN_CENTER);
    //        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
    //        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    //        style.setFont(headerFont);
    //        style.setDataFormat(df.getFormat("d-mmm"));
    //        styles.put("header_date", style);
    font1.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font1);
    styles.put("cell_b", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font1);
    style.setLocked(false);
    styles.put("cell_b_centered", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font1);
    style.setLocked(true);
    styles.put("cell_b_centered_locked", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font1);
    style.setDataFormat(df.getFormat("d-mmm"));
    styles.put("cell_b_date", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font1);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setDataFormat(df.getFormat("d-mmm"));
    styles.put("cell_g", style);

    Font font2 = wb.createFont();
    font2.setColor(IndexedColors.BLUE.getIndex());
    font2.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font2);
    styles.put("cell_bb", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font1);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setDataFormat(df.getFormat("d-mmm"));
    styles.put("cell_bg", style);

    Font font3 = wb.createFont();
    font3.setFontHeightInPoints((short) 14);
    font3.setColor(IndexedColors.DARK_BLUE.getIndex());
    font3.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font3);
    style.setWrapText(true);
    styles.put("cell_h", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setWrapText(true);
    styles.put("cell_normal", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setWrapText(true);
    styles.put("cell_normal_centered", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setWrapText(true);
    style.setDataFormat(df.getFormat("d-mmm"));
    styles.put("cell_normal_date", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setIndention((short) 1);
    style.setWrapText(true);
    styles.put("cell_indented", style);

    style = createBorderedStyle(wb);
    style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    styles.put("cell_blue", style);

    return styles;
}

From source file:packtest.HyperlinkExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();

    //cell style for hyperlinks
    //by default hyperlinks are blue and underlined
    CellStyle hlink_style = wb.createCellStyle();
    Font hlink_font = wb.createFont();
    hlink_font.setUnderline(Font.U_SINGLE);
    hlink_font.setColor(IndexedColors.BLUE.getIndex());
    hlink_style.setFont(hlink_font);

    Cell cell;//www  . j  a va2  s  . com
    Sheet sheet = wb.createSheet("Hyperlinks");
    //URL
    cell = sheet.createRow(0).createCell((short) 0);
    cell.setCellValue("URL Link");

    Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
    link.setAddress("http://poi.apache.org/");
    cell.setHyperlink(link);
    cell.setCellStyle(hlink_style);

    //link to a file in the current directory
    cell = sheet.createRow(1).createCell((short) 0);
    cell.setCellValue("File Link");
    link = createHelper.createHyperlink(Hyperlink.LINK_FILE);
    link.setAddress("link1.xls");
    cell.setHyperlink(link);
    cell.setCellStyle(hlink_style);

    //e-mail link
    cell = sheet.createRow(2).createCell((short) 0);
    cell.setCellValue("Email Link");
    link = createHelper.createHyperlink(Hyperlink.LINK_EMAIL);
    //note, if subject contains white spaces, make sure they are url-encoded
    link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
    cell.setHyperlink(link);
    cell.setCellStyle(hlink_style);

    //link to a place in this workbook

    //create a target sheet and cell
    Sheet sheet2 = wb.createSheet("Target Sheet");
    sheet2.createRow(0).createCell((short) 0).setCellValue("Target Cell");

    cell = sheet.createRow(3).createCell((short) 0);
    cell.setCellValue("Worksheet Link");
    Hyperlink link2 = createHelper.createHyperlink(Hyperlink.LINK_DOCUMENT);
    link2.setAddress("'Target Sheet'!A1");
    cell.setHyperlink(link2);
    cell.setCellStyle(hlink_style);

    FileOutputStream out = new FileOutputStream(Utils.getPath("hyperinks.xlsx"));
    wb.write(out);
    out.close();

}

From source file:packtest.WorkingWithFonts.java

License:Apache License

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

    Font font0 = wb.createFont();
    font0.setColor(IndexedColors.BROWN.getIndex());
    CellStyle style0 = wb.createCellStyle();
    style0.setFont(font0);

    Font font1 = wb.createFont();
    font1.setFontHeightInPoints((short) 14);
    font1.setFontName("Courier New");
    font1.setColor(IndexedColors.RED.getIndex());
    CellStyle style1 = wb.createCellStyle();
    style1.setFont(font1);/* w  w  w.j a v  a2  s.  co  m*/

    Font font2 = wb.createFont();
    font2.setFontHeightInPoints((short) 16);
    font2.setFontName("Arial");
    font2.setColor(IndexedColors.GREEN.getIndex());
    CellStyle style2 = wb.createCellStyle();
    style2.setFont(font2);

    Font font3 = wb.createFont();
    font3.setFontHeightInPoints((short) 18);
    font3.setFontName("Times New Roman");
    font3.setColor(IndexedColors.LAVENDER.getIndex());
    CellStyle style3 = wb.createCellStyle();
    style3.setFont(font3);

    Font font4 = wb.createFont();
    font4.setFontHeightInPoints((short) 18);
    font4.setFontName("Wingdings");
    font4.setColor(IndexedColors.GOLD.getIndex());
    CellStyle style4 = wb.createCellStyle();
    style4.setFont(font4);

    Font font5 = wb.createFont();
    font5.setFontName("Symbol");
    CellStyle style5 = wb.createCellStyle();
    style5.setFont(font5);

    Cell cell0 = sheet.createRow(0).createCell(1);
    cell0.setCellValue("Default");
    cell0.setCellStyle(style0);

    Cell cell1 = sheet.createRow(1).createCell(1);
    cell1.setCellValue("Courier");
    cell1.setCellStyle(style1);

    Cell cell2 = sheet.createRow(2).createCell(1);
    cell2.setCellValue("Arial");
    cell2.setCellStyle(style2);

    Cell cell3 = sheet.createRow(3).createCell(1);
    cell3.setCellValue("Times New Roman");
    cell3.setCellStyle(style3);

    Cell cell4 = sheet.createRow(4).createCell(1);
    cell4.setCellValue("Wingdings");
    cell4.setCellStyle(style4);

    Cell cell5 = sheet.createRow(5).createCell(1);
    cell5.setCellValue("Symbol");
    cell5.setCellStyle(style5);

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

From source file:paysheets.PaySheetFormatter.java

public static void addTitleRow(HSSFWorkbook workbook) {
    workbook.createSheet("Sheet 1");
    // Each pay sheet only uses the first sheet
    HSSFSheet sheet = workbook.getSheetAt(0);
    setDefaultColumnWidth(sheet);/*from  ww  w . j a v  a 2 s.  com*/
    HSSFRow row;
    HSSFCell cell;

    // Create a font and set its attributes
    Font font = workbook.createFont();
    font.setFontHeightInPoints((short) 11);
    // Set the color to black (constant COLOR_NORMAL)
    font.setColor(Font.COLOR_NORMAL);
    font.setBold(true);

    // Create a cell style and set its properties
    CellStyle cs = workbook.createCellStyle();
    // Set the data format to the built in text format
    cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
    // Set the cell style to use the font created previously
    cs.setFont(font);

    // Create the first title row
    row = sheet.createRow(0);
    // Use the default row height (-1) is sheet default
    row.setHeight((short) -1);

    // Add the first title row's 6 cells
    for (int cellNum = 0; cellNum < 6; cellNum++) {
        cell = row.createCell(cellNum);
        cell.setCellStyle(cs);
    }
    // Populate first row's values
    cell = row.getCell(PaySheet.DATE_INDEX);
    cell.setCellValue("DATE");
    cell = row.getCell(PaySheet.CUST_INDEX);
    cell.setCellValue("CUSTOMER");
    cell = row.getCell(PaySheet.PAY_INDEX);
    cell.setCellValue("PAY");
    cell = row.getCell(PaySheet.NONSERIAL_INDEX);
    cell.setCellValue("EQUIPMENT");
    cell = row.getCell(PaySheet.SERIAL_INDEX);
    cell.setCellValue("SERIALIZED");
    cell = row.getCell(PaySheet.SHS_INDEX);
    cell.setCellValue("SHS");

    // Create second title row
    row = sheet.createRow(1);
    row.setHeight((short) -1);
    // Add the cells to the row
    for (int cellNum = 0; cellNum < 3; cellNum++) {
        cell = row.createCell(cellNum);
        cell.setCellStyle(cs);
    }
    // Populate the second title row's values
    cell = row.getCell(PaySheet.WO_INDEX);
    cell.setCellValue("WORK ORDER");
    cell = row.getCell(PaySheet.TYPE_INDEX);
    cell.setCellValue("TYPE");
    cell = row.getCell(PaySheet.LEP_INDEX);
    cell.setCellValue("LEP");

    // Add thick border around title row
    addJobBorder(workbook, 0);
}

From source file:paysheets.PaySheetFormatter.java

public static void addJobFormatting(HSSFWorkbook workbook, int rowIndex) {
    HSSFSheet sheet = workbook.getSheetAt(0);
    HSSFRow row;/*from   w w w.j  a va 2s  . co m*/
    HSSFCell cell;

    Font font = workbook.createFont();
    font.setBold(false);
    font.setFontHeightInPoints((short) 10);
    font.setColor(Font.COLOR_NORMAL);

    // Create a cell style for general text
    CellStyle generalStyle = workbook.createCellStyle();
    generalStyle.setFont(font);
    generalStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));

    // Create a cell style for dates
    CellStyle dateStyle = workbook.createCellStyle();
    dateStyle.setFont(font);
    // Set the cell data format to date (0xe) is the built in format
    dateStyle.setDataFormat((short) 0xe);
    dateStyle.setAlignment(CellStyle.ALIGN_LEFT);

    // Create a new row at the given index
    row = sheet.createRow(rowIndex);
    // Format the first row for the new job
    for (int cellNum = 0; cellNum < 6; cellNum++) {
        cell = row.createCell(cellNum);
        // Only the first cell uses the date style
        if (cellNum > 0) {
            cell.setCellStyle(generalStyle);
        } else {
            cell.setCellStyle(dateStyle);
        }
    }
    // Create second row for the new Job at rowIndex + 1
    row = sheet.createRow(rowIndex + 1);
    for (int cellNum = 0; cellNum < 3; cellNum++) {
        cell = row.createCell(cellNum);
        cell.setCellStyle(generalStyle);
    }
}

From source file:pl.softech.knf.ofe.opf.members.xls.export.XlsMembersWritter.java

License:Apache License

private void buildHeader(final List<Date> dates, final Sheet sheet, final int rowIdx, final int colIdx) {

    final Workbook wb = sheet.getWorkbook();
    final CreationHelper createHelper = wb.getCreationHelper();
    final CellStyle dateCellStyle = wb.createCellStyle();
    dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("mm-yyyy"));

    Row row = sheet.createRow(rowIdx);//from w  w  w . ja v  a 2  s .co  m

    Cell cell = row.createCell(colIdx);
    cell.setCellValue("Open Pension Fund");

    final CellStyle cellStyle = wb.createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    cellStyle.setFont(createHeaderFont(wb, (short) 12));
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIdx + 1);
    cell.setCellValue("Number of members");
    cell.setCellStyle(cellStyle);
    row = sheet.createRow(rowIdx + 1);
    sheet.addMergedRegion(new CellRangeAddress(// merge Open Pension Fund
            rowIdx, // first row (0-based)
            rowIdx + 1, // last row (0-based)
            colIdx, // first column (0-based)
            colIdx // last column (0-based)
    ));

    sheet.addMergedRegion(new CellRangeAddress(// merge Number of members
            rowIdx, // first row (0-based)
            rowIdx, // last row (0-based)
            colIdx + 1, // first column (0-based)
            colIdx + dates.size() // last column (0-based)
    ));

    int colIt = colIdx + 1;
    for (final Date date : dates) {
        cell = row.createCell(colIt++);
        cell.setCellValue(date);
        cell.setCellStyle(dateCellStyle);
    }

}

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

License:Apache License

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

    Font font0 = wb.createFont();
    font0.setColor(IndexedColors.BROWN.getIndex());
    CellStyle style0 = wb.createCellStyle();
    style0.setFont(font0);

    Font font1 = wb.createFont();
    font1.setFontHeightInPoints((short) 14);
    font1.setFontName("Courier New");
    font1.setColor(IndexedColors.RED.getIndex());
    CellStyle style1 = wb.createCellStyle();
    style1.setFont(font1);/*from w w w.  j a  v a2s .c  om*/

    Font font2 = wb.createFont();
    font2.setFontHeightInPoints((short) 16);
    font2.setFontName("Arial");
    font2.setColor(IndexedColors.GREEN.getIndex());
    CellStyle style2 = wb.createCellStyle();
    style2.setFont(font2);

    Font font3 = wb.createFont();
    font3.setFontHeightInPoints((short) 18);
    font3.setFontName("Times New Roman");
    font3.setColor(IndexedColors.LAVENDER.getIndex());
    CellStyle style3 = wb.createCellStyle();
    style3.setFont(font3);

    Font font4 = wb.createFont();
    font4.setFontHeightInPoints((short) 18);
    font4.setFontName("Wingdings");
    font4.setColor(IndexedColors.GOLD.getIndex());
    CellStyle style4 = wb.createCellStyle();
    style4.setFont(font4);

    Font font5 = wb.createFont();
    font5.setFontName("Symbol");
    CellStyle style5 = wb.createCellStyle();
    style5.setFont(font5);

    Cell cell0 = sheet.createRow(0).createCell(1);
    cell0.setCellValue("Default");
    cell0.setCellStyle(style0);

    Cell cell1 = sheet.createRow(1).createCell(1);
    cell1.setCellValue("Courier");
    cell1.setCellStyle(style1);

    Cell cell2 = sheet.createRow(2).createCell(1);
    cell2.setCellValue("Arial");
    cell2.setCellStyle(style2);

    Cell cell3 = sheet.createRow(3).createCell(1);
    cell3.setCellValue("Times New Roman");
    cell3.setCellStyle(style3);

    Cell cell4 = sheet.createRow(4).createCell(1);
    cell4.setCellValue("Wingdings");
    cell4.setCellStyle(style4);

    Cell cell5 = sheet.createRow(5).createCell(1);
    cell5.setCellValue("Symbol");
    cell5.setCellStyle(style5);

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

From source file:PolyGlot.ExcelExport.java

License:Open Source License

/**
 * Exports a dictionary to an excel file
 * @param fileName Filename to export to
 * @param core dictionary core//from w  w  w .j a v a  2  s .  co m
 * @throws Exception on write error
 */
private void export(String fileName, DictCore core) throws Exception {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet;
    CellStyle localStyle = workbook.createCellStyle();
    CellStyle conStyle = workbook.createCellStyle();
    Font conFont = workbook.createFont();
    conFont.setFontName(core.getPropertiesManager().getFontCon().getFontName());

    localStyle.setWrapText(true);

    conStyle.setWrapText(true);
    conStyle.setFont(conFont);

    // record words on sheet 1        
    sheet = workbook.createSheet("Lexicon");
    Iterator<ConWord> wordIt = core.getWordCollection().getNodeIterator();

    Row row = sheet.createRow(0);
    row.createCell(0).setCellValue("CON WORD");
    row.createCell(1).setCellValue("LOCAL WORD");
    row.createCell(2).setCellValue("TYPE");
    row.createCell(3).setCellValue("PRONUNCIATION");
    row.createCell(4).setCellValue("GENDER");
    row.createCell(5).setCellValue("DECLENSIONS");
    row.createCell(6).setCellValue("DEFINITIONS");

    for (Integer i = 1; wordIt.hasNext(); i++) {
        Object[] wordArray = getWordForm(wordIt.next(), core);
        row = sheet.createRow(i);
        for (Integer j = 0; j < wordArray.length; j++) {
            Cell cell = row.createCell(j);
            cell.setCellValue((String) wordArray[j]);

            if (j == 0) {
                cell.setCellStyle(conStyle);
            } else {
                cell.setCellStyle(localStyle);
            }
        }
    }

    // record types on sheet 2
    sheet = workbook.createSheet("Types");
    Iterator<TypeNode> typeIt = core.getTypes().getNodeIterator();

    row = sheet.createRow(0);
    row.createCell(0).setCellValue("TYPE");
    row.createCell(1).setCellValue("NOTES");

    for (Integer i = 1; typeIt.hasNext(); i++) {
        TypeNode curNode = typeIt.next();
        row = sheet.createRow(i);

        Cell cell = row.createCell(0);
        cell.setCellValue(curNode.getValue());
        cell = row.createCell(1);
        cell.setCellValue(curNode.getNotes());
        cell.setCellStyle(localStyle);
    }

    // record genders on sheet 3
    sheet = workbook.createSheet("Genders");
    Iterator<GenderNode> genderIt = core.getGenders().getNodeIterator();

    row = sheet.createRow(0);
    row.createCell(0).setCellValue("GENDER");
    row.createCell(1).setCellValue("NOTES");

    for (Integer i = 1; genderIt.hasNext(); i++) {
        GenderNode curNode = genderIt.next();
        row = sheet.createRow(i);

        Cell cell = row.createCell(0);
        cell.setCellValue(curNode.getValue());
        cell = row.createCell(1);
        cell.setCellValue(curNode.getNotes());
        cell.setCellStyle(localStyle);
    }

    // record pronunciations on sheet 4
    sheet = workbook.createSheet("Pronunciations");
    Iterator<PronunciationNode> procIt = core.getPronunciationMgr().getPronunciations();

    row = sheet.createRow(0);
    row.createCell(0).setCellValue("CHARACTER(S)");
    row.createCell(1).setCellValue("PRONUNCIATION");

    for (Integer i = 1; procIt.hasNext(); i++) {
        PronunciationNode curNode = procIt.next();
        row = sheet.createRow(i);

        Cell cell = row.createCell(0);
        cell.setCellStyle(conStyle);
        cell.setCellValue(curNode.getValue());

        cell = row.createCell(1);
        cell.setCellStyle(localStyle);
        cell.setCellValue(curNode.getPronunciation());
    }

    try {
        FileOutputStream out = new FileOutputStream(new File(fileName));
        workbook.write(out);
        out.close();
    } catch (IOException e) {
        throw new Exception("Unable to write file: " + fileName);
    }
}

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   w ww . j  a va 2  s  .c o m
        /* 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 {/*from ww  w .  jav  a 2s  . co  m*/
        /* 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 {

    }
}