Example usage for org.apache.poi.ss.usermodel Sheet setColumnWidth

List of usage examples for org.apache.poi.ss.usermodel Sheet setColumnWidth

Introduction

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

Prototype

void setColumnWidth(int columnIndex, int width);

Source Link

Document

Set the width (in units of 1/256th of a character width)

The maximum column width for an individual cell is 255 characters.

Usage

From source file:excel.PoiWriteExcelFile.java

public static int generarReporte() {

    //Calendar cal=Calendar.getInstance();
    Calendar cal = WorkMonitorUI.instante;

    try {//from ww  w .j a v a 2 s  .  com
        FileOutputStream fileOut = new FileOutputStream("HH_"
                + instante.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault())
                        .toUpperCase()
                + "_" + persona.getNombre().toUpperCase().charAt(0) + "." + persona.getApellido().toUpperCase()
                + "_" + instante.get(Calendar.YEAR) + ".xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet worksheet = workbook.createSheet(
                cal.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault()).toUpperCase()
                        + "-" + cal.get(Calendar.YEAR));

        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setFontName("Calibri");
        font.setItalic(false);
        font.setBold(true);
        font.setColor(HSSFColor.BLACK.index);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle diasStyle = workbook.createCellStyle();
        diasStyle.setFillForegroundColor(HSSFColor.SEA_GREEN.index);
        diasStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        font.setFontName("Calibri");
        font.setItalic(false);
        font.setBold(true);
        font.setColor(HSSFColor.WHITE.index);
        diasStyle.setFont(font);
        diasStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        diasStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        diasStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle schedStyle = workbook.createCellStyle();
        schedStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        schedStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont font3 = workbook.createFont();
        font3.setFontHeightInPoints((short) 11);
        font3.setFontName("Calibri");
        font3.setItalic(false);
        font3.setColor(HSSFColor.BLACK.index);
        schedStyle.setFont(font3);
        schedStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        schedStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        schedStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle workdayStyle = workbook.createCellStyle();
        //workdayStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);                        
        workdayStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        workdayStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setWrapText(true);
        HSSFFont font2 = workbook.createFont();
        font2.setFontHeightInPoints((short) 8);
        font2.setFontName("Serif");
        font2.setItalic(false);
        //font2.setColor(HSSFColor.YELLOW.index);
        workdayStyle.setFont(font2);
        workdayStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

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

        HSSFCellStyle horarioStyle = workbook.createCellStyle();
        horarioStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        horarioStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        horarioStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        horarioStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont font4 = workbook.createFont();
        font4.setFontHeightInPoints((short) 10);
        font4.setFontName("Serif");
        font4.setItalic(false);
        font4.setBold(true);
        //font2.setColor(HSSFColor.YELLOW.index);
        horarioStyle.setFont(font4);

        // index from 0,0... cell A1 is cell(0,0)
        HSSFRow row1 = worksheet.createRow((short) 0);
        row1.setHeight((short) 500);

        //System.out.println("cal.get(Calendar.YEAR)="+cal.get(Calendar.YEAR));

        HSSFCell cellA1 = row1.createCell((short) 0);
        cellA1.setCellValue(
                cal.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault()).toUpperCase()
                        + "-" + cal.get(Calendar.YEAR));
        cellA1.setCellStyle(cellStyle);

        HSSFRow row2 = worksheet.createRow((short) 1);
        HSSFCell cellA4 = row2.createCell((short) 0);
        cellA4.setCellValue("Horario");
        cellA4.setCellStyle(horarioStyle);
        //row2.setHeight((short)500);

        HSSFRow row3 = worksheet.createRow((short) 2);
        HSSFCell cellA3 = row3.createCell((short) 0);
        cellA3.setCellValue("Inicio - Trmino");
        cellA3.setCellStyle(diasStyle);

        Calendar hora = Calendar.getInstance();

        hora.set(Calendar.HOUR_OF_DAY, 9);
        hora.set(Calendar.MINUTE, 0);
        hora.set(Calendar.SECOND, 0);

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

        HSSFCell cellXn;

        for (int i = 0; i < 29; ++i) {
            HSSFRow row = worksheet.createRow((short) i + 3);
            row.setHeight((short) 500);

            cellXn = row.createCell((short) 0);
            String horaIni = sdf.format(hora.getTime());
            hora.add(Calendar.MINUTE, 30);
            String horaFin = sdf.format(hora.getTime());
            cellXn.setCellValue(horaIni + " - " + horaFin);
            cellXn.setCellStyle(schedStyle);
        }

        System.out.println("cal.get(Calendar.MONTH)1=" + cal.get(Calendar.MONTH));

        cal.add(Calendar.DAY_OF_MONTH, -cal.get(Calendar.DAY_OF_MONTH) + 1);

        int diasMes = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        System.out.println("cal.get(Calendar.MONTH)2=" + cal.get(Calendar.MONTH));

        sdf = new SimpleDateFormat("EEEE d");

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)1=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        for (int i = 0; i < diasMes; ++i) {
            cellXn = row2.createCell((short) i + 1);
            String dia = sdf.format(cal.getTime());
            dia = Character.toUpperCase(dia.charAt(0)) + dia.substring(1);
            cellXn.setCellValue(dia);
            cellXn.setCellStyle(horarioStyle);
            //System.out.println("cal.get(Calendar.DAY_OF_MONTH)="+cal.get(Calendar.DAY_OF_MONTH));
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }

        for (int i = 0; i < diasMes; ++i) {
            cellXn = row3.createCell((short) i + 1);
            cellXn.setCellValue("Descripcin");
            cellXn.setCellStyle(diasStyle);
        }

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)2=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        // Retroceder mes para que quede como estaba
        cal.add(Calendar.MONTH, -1);
        //cal.add(Calendar.DAY_OF_MONTH, -1);    

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)3=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        HhDao hhDao = new HhDao();
        Object[][] hh = new Object[29][cal.getActualMaximum(Calendar.DAY_OF_MONTH)];

        hh = hhDao.getByMes(WorkMonitorUI.persona.getId(), cal.getTime());

        cal.set(Calendar.DAY_OF_MONTH, 1);

        Sheet sheet = workbook.getSheetAt(0);

        sdf = new SimpleDateFormat("EEEE");

        HSSFPatriarch _drawing = (HSSFPatriarch) sheet.createDrawingPatriarch();
        CreationHelper factory = workbook.getCreationHelper();

        for (int i = 0; i < 29; ++i) {
            Row r = sheet.getRow(i + 3);
            for (int j = 0; j < diasMes; ++j) {
                if (hh[i][j].toString() != "") {
                    cellXn = (HSSFCell) r.createCell((short) j + 1);
                    Hh _hh = (Hh) hh[i][j];
                    cellXn.setCellValue(
                            _hh.getTarea().getNombre().trim() + ": " + _hh.getActividad().getNombre().trim());

                    HSSFAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5);
                    org.apache.poi.ss.usermodel.Comment comment = _drawing.createComment(anchor);
                    String comentario = _hh.getTarea().getComentario().toLowerCase();
                    if (_hh.getComentario() != null)
                        comentario = comentario + _hh.getComentario().toLowerCase();
                    RichTextString str = factory.createRichTextString(comentario);

                    comment.setString(str);

                    cellXn.setCellComment(comment);
                } else {
                    cellXn = (HSSFCell) r.createCell((short) j + 1);
                    cellXn.setCellValue("");
                }
                //System.out.println("sdf.format(cal.getTime())="+sdf.format(cal.getTime()));
                if (Arrays.asList("sbado", "domingo").contains(sdf.format(cal.getTime())))
                    cellXn.setCellStyle(weekendStyle);
                else
                    cellXn.setCellStyle(workdayStyle);
                sheet.setColumnWidth(j, 5000);

                cal.add(Calendar.DAY_OF_MONTH, 1);
                //sheet.autoSizeColumn(j);
            }
            // Retroceder mes para que quede como estaba                
            cal.add(Calendar.MONTH, -1);
            System.out.println("cal.get(Calendar.MONTH)3=" + cal.get(Calendar.MONTH));
            cal.set(Calendar.DAY_OF_MONTH, 1);
        }
        sheet.setColumnWidth(diasMes, 5000);

        WorkMonitorUI.instante = Calendar.getInstance();
        sheet.setColumnWidth(0, 5000);
        sheet.createFreezePane(1, 3);
        // Freeze just one row
        //sheet.createFreezePane( 0, 1, 0, 1 );

        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return -1;
    } catch (IOException e) {
        e.printStackTrace();
        return -2;
    }
    return 1;
}

From source file:Export.GenericExcel.java

public static void createCell(Cell c, Row r, Sheet s, CellStyle cs, int colinaI, int colinaF, String valorS,
        int linhaI, int linhaF) {

    c = r.createCell(linhaI);/*w w  w. j  av  a2s  . c  o  m*/
    c.setCellStyle(cs);
    c.setCellValue(valorS);
    s.setColumnWidth(linhaI, linhaF * 1000);
}

From source file:Export.ListaVeiculo.java

public static void CreateCell(Cell c, Row r, Sheet s, CellStyle cs, int colinaI, int colinaF, Object valorS,
        int linhaI, int linhaF) {
    c = r.createCell(linhaI);/*from  w  w  w .  ja  v a 2 s  .  co m*/
    c.setCellStyle(cs);
    if (valorS instanceof Integer)
        c.setCellValue((Integer) valorS);
    else
        c.setCellValue((String) valorS);
    s.setColumnWidth(linhaI, linhaF * 500);
}

From source file:fr.openwide.core.export.excel.AbstractExcelTableExport.java

License:Apache License

/**
 * Finalise la cration de la feuille de calcul, notamment en demandant le
 * redimensionnement automatique des colonnes.
 * /*from  www. j  a va 2s  .  c o m*/
 * @param sheet feuilles de calcul
 * @param headers en-ttes
 * @param landscapePrintSetup dfinit si la feuille est imprime en paysage ou non
 */
protected void finalizeSheet(Sheet sheet, List<String> headers, boolean landscapePrintSetup) {
    int nbColumns = headers.size();
    for (int i = 0; i < nbColumns; i++) {
        sheet.autoSizeColumn(i);
        int columnWidth = (int) (sheet.getColumnWidth(i) * COLUMN_RESIZE_RATIO);
        sheet.setColumnWidth(i,
                columnWidth < ABSOLUTE_MAX_COLUMN_WIDTH ? columnWidth : ABSOLUTE_MAX_COLUMN_WIDTH);
    }

    finalizeSheet(sheet, landscapePrintSetup);
}

From source file:fr.openwide.core.export.excel.AbstractExcelTableExport.java

License:Apache License

/**
 * Finalise la cration de la feuille de calcul, notamment en demandant le
 * redimensionnement automatique des colonnes.
 * //ww w .j  a v a  2  s .  c  om
 * @param sheet feuilles de calcul
 * @param columnInfos map contenant l'en-tte et les informations d'une colonne
 * @param landscapePrintSetup dfinit si la feuille est imprime en paysage ou non
 */
protected void finalizeSheet(Sheet sheet, RangeMap<Integer, ColumnInformation> columnInfos,
        boolean landscapePrintSetup) {
    for (Map.Entry<Range<Integer>, ColumnInformation> entry : columnInfos.asMapOfRanges().entrySet()) {
        ColumnInformation columnInformation = entry.getValue();
        Range<Integer> range = entry.getKey();
        int beginIndex = range.lowerEndpoint();
        int endIndex = range.upperEndpoint();

        // Dtermination de la taille maximum de cette colonne
        int maxColumnWidth;
        if (columnInformation.getColumnMaxWidth() != -1) {
            maxColumnWidth = columnInformation.getColumnMaxWidth();
        } else {
            maxColumnWidth = ABSOLUTE_MAX_COLUMN_WIDTH;
        }

        // Dtermination de la taille souhaite pour la colonne
        if (columnInformation.getColumnWidth() != -1) {
            // On force la taille des colonnes en fonction de la columnInformation

            int columnWidth = columnInformation.getColumnWidth();
            columnWidth = Math.min(columnWidth, maxColumnWidth);

            // On prend en compte le fait que la "colonne" peut s'tendre en fait sur plusieurs colonnes (fusion de cellules au niveau du header)
            int columnSpan = endIndex - beginIndex + 1;
            columnWidth = columnWidth / columnSpan;

            // On redimmensionne les colonnes
            for (int columnIndex = beginIndex; columnIndex <= endIndex; ++columnIndex) {
                sheet.setColumnWidth(columnIndex, columnWidth);
            }
        } else {
            // On redimmensionne les colonnes une  une en prennant leur taille actuelle et en les augmentant un petit peu
            for (int columnIndex = beginIndex; columnIndex <= endIndex; ++columnIndex) {
                sheet.autoSizeColumn(columnIndex);
                int columnWidth = (int) (sheet.getColumnWidth(beginIndex) * COLUMN_RESIZE_RATIO);
                columnWidth = Math.min(columnWidth, maxColumnWidth);
                sheet.setColumnWidth(columnIndex, columnWidth);
            }
        }
    }

    finalizeSheet(sheet, landscapePrintSetup);
}

From source file:fr.openwide.core.export.excel.AbstractExcelTableExport.java

License:Apache License

/**
 * Redimensionne les colonnes qui contiennent des rgions fusionnes.
 * // w ww  . ja  v  a  2 s  .  c  o m
 * Dans POI, les rgions fusionnes ne sont pas prises en compte dans le autoSizeColumn.
 * Quand on fusionne des cellules sur une mme colonne, on corrige la taille de cette colonne si ncessaire.
 * 
 * @param sheet feuille de calcul
 * @param columns map contenant l'en-tte et les informations d'une colonne
 */
protected void resizeMergedColumns(Sheet sheet, Collection<ColumnInformation> columns) {
    if (sheet.getNumMergedRegions() > 0) {
        List<ColumnInformation> columnsInfo = new ArrayList<ColumnInformation>(columns);

        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
            CellRangeAddress mergedRegion = sheet.getMergedRegion(i);

            if (mergedRegion.getFirstColumn() == mergedRegion.getLastColumn()) {
                int columnIndex = mergedRegion.getFirstColumn();

                String headerText = getColumnLabel(columnsInfo.get(columnIndex).getHeaderKey());

                int headerSize = (int) (headerText.length() * 300 * COLUMN_RESIZE_RATIO);
                if (sheet.getColumnWidth(columnIndex) < headerSize) {
                    sheet.setColumnWidth(columnIndex, headerSize);
                }
            }
        }
    }
}

From source file:fr.unice.i3s.rockflows.experiments.automatictest.ExcelUtils.java

/**
* Given a sheet, this method deletes a column from a sheet and moves
* all the columns to the right of it to the left one cell.
*
* Note, this method will not update any formula references.
*
* @param sheet// ww w. j  av a 2 s  .c om
* @param column
*/
private static void deleteColumn(Sheet sheet, int columnToDelete) {
    int maxColumn = 0;
    for (int iii = 0; iii < sheet.getLastRowNum() + 1; iii++) {
        Row row = sheet.getRow(iii);
        // if no row exists here; then nothing to do; next!
        if (row == null) {
            continue;
        }

        // if the row doesn't have this many columns then we are good; next!
        int lastColumn = row.getLastCellNum();
        if (lastColumn > maxColumn) {
            maxColumn = lastColumn;
        }

        if (lastColumn < columnToDelete) {
            continue;
        }

        for (int x = columnToDelete + 1; x < lastColumn + 1; x++) {
            Cell oldCell = row.getCell(x - 1);
            if (oldCell != null) {
                row.removeCell(oldCell);
            }
            Cell nextCell = row.getCell(x);
            if (nextCell != null) {
                Cell newCell = row.createCell(x - 1, nextCell.getCellType());
                cloneCell(newCell, nextCell);
            }
        }
    }

    // Adjust the column widths
    for (int ccc = 0; ccc < maxColumn; ccc++) {
        sheet.setColumnWidth(ccc, sheet.getColumnWidth(ccc + 1));
    }
}

From source file:functions.excels.exports.TemoinsParPeriodeExcel.java

License:Apache License

public TemoinsParPeriodeExcel(Map<String, String> info, List<TemoinsParPeriode> temoins) throws IOException {
    super();//from   ww w  .  j  av  a 2s .c o m
    Sheet sheet = wb.createSheet("Tmoins par priode");
    Espece espece = Espece.find.byId(Integer.parseInt(info.get("espece")));
    SousGroupe sous_groupe = SousGroupe.find.byId(Integer.parseInt(info.get("sous_groupe")));
    Groupe groupe = Groupe.find.byId(Integer.parseInt(info.get("groupe")));
    StadeSexe stade_sexe = StadeSexe.find.byId(Integer.parseInt(info.get("stade")));
    String maille = info.get("maille");
    String date1 = info.get("jour1") + "/" + info.get("mois1") + "/" + info.get("annee1");
    String date2 = info.get("jour2") + "/" + info.get("mois2") + "/" + info.get("annee2");
    String titre = "Liste des tmoins ayant fait une observation" + crLf;
    if (espece != null)
        titre += "de " + espece.espece_nom;
    else if (sous_groupe != null)
        titre += "de " + sous_groupe;
    else if (groupe != null)
        titre += "de " + groupe;
    if (stade_sexe != null)
        titre += " au stade " + stade_sexe;
    if (!maille.equals(""))
        titre += " dans la maille " + maille;
    titre += " du " + date1 + " au " + date2;
    titre += crLf + " (" + temoins.size() + " tmoin(s) pour " + TemoinsParPeriode.getSomme(temoins)
            + " tmoignage(s))";

    int page = 0;
    int ligne = 7;
    this.collerLogoEtTitre(page, titre);
    Row rowHead = sheet.createRow(ligne);
    rowHead.createCell(0).setCellValue("Tmoin");
    rowHead.createCell(1).setCellValue("Nbre tm.");
    ligne++;
    boolean ecritAGauche = true;
    for (TemoinsParPeriode temoin : temoins) {
        if (ecritAGauche) {
            Row row = sheet.createRow(ligne);
            row.createCell(0).setCellValue(temoin.temoin.toString());
            row.createCell(1).setCellValue(temoin.nombreDeTemoignages);
            ligne++;
        } else {
            Row row = sheet.getRow(ligne);
            row.createCell(3).setCellValue(temoin.temoin.toString());
            row.createCell(4).setCellValue(temoin.nombreDeTemoignages);
            ligne++;
        }
        if (ligne % LIGNES == (LIGNES - 2)) {
            if (ecritAGauche) {
                ecritAGauche = !ecritAGauche;
                ligne -= (LIGNES - 9);
                Row row = sheet.getRow(ligne);
                row.createCell(3).setCellValue("Tmoin");
                row.createCell(4).setCellValue("Nbre tm.");
                ligne++;
            } else {
                ecritAGauche = !ecritAGauche;
                //On crit le pied de page
                this.piedDePage(page);
                //On fait une nouvelle page
                ligne += 9;
                page++;
                this.collerLogoEtTitre(page, titre);
                Row row = sheet.createRow(ligne);
                row.createCell(0).setCellValue("Tmoin");
                row.createCell(1).setCellValue("Nbre tm.");
                ligne++;
            }
        }
    }
    this.piedDePage(page);
    sheet.setColumnWidth(0, 7937);
    sheet.autoSizeColumn(1);
    sheet.setColumnWidth(2, 256);
    sheet.setColumnWidth(3, 7937);
    sheet.autoSizeColumn(4);
}

From source file:GapAnalysis.gapAnalysis.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //PrintWriter out = response.getWriter();
    try {//from w w  w.  jav a  2 s . co  m

        ArrayList keyal = new ArrayList();
        ArrayList countyal = new ArrayList();
        ArrayList scountyal = new ArrayList();
        ArrayList facilal = new ArrayList();
        ArrayList yearmonthal = new ArrayList();
        ArrayList monthal = new ArrayList();
        ArrayList sectional = new ArrayList();

        XSSFWorkbook wb;

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

        System.out.println(allpath);

        XSSFWorkbook workbook;
        String mydrive = allpath.substring(0, 1);
        // wb = new XSSFWorkbook( OPCPackage.open(allpath) );

        Date da = new Date();
        String dat2 = da.toString().replace(" ", "_");
        dat2 = dat2.toString().replace(":", "_");

        String np = mydrive + ":\\APHIAPLUS\\InternalSystem\\Gapanalysis" + dat2 + ".xlsm";
        System.out.println("path:: " + np);
        // String desteepath1 = getServletContext().getRealPath("/Females 15to24.xlsm");
        String sr = getServletContext().getRealPath("/Gapanalysis.xlsm");
        //check if file exists

        //first time , it should create those folders that host the macro file
        File f = new File(np);
        if (!f.exists() && !f.isDirectory()) { /* do something */
            copytemplates ct = new copytemplates();
            ct.transfermacros(sr, np);
            //rem np is the destination file name  

            System.out.println("Copying macro template first time ..");

        } else
        //copy the file alone  
        {
            copytemplates ct = new copytemplates();
            //copy the agebased file only
            ct.copymacros(sr, np);

        }
        String filepth = np;

        File allpathfile = new File(filepth);

        OPCPackage pkg = OPCPackage.open(allpathfile);

        pathtodelete = filepth;
        wb = new XSSFWorkbook(pkg);

        dbConn conn = new dbConn();
        HashMap<String, String> rawdatahashmap = new HashMap<String, String>();

        int year = 0;
        String yearval = "";
        int prevyear = 0;

        String quarter = "";

        String yearmonth = "";
        String startyearmonth = "";
        String endyearmonth = "";

        yearval = request.getParameter("year").toString();

        System.out.println("YEARVAL" + yearval);
        year = Integer.parseInt(yearval);
        prevyear = year - 1;
        quarter = request.getParameter("quarter");
        periodname += yearval + "_";
        if (quarter.equals("1")) {
            startyearmonth = prevyear + "10";
            endyearmonth = prevyear + "12";
            periodname = prevyear + "_(Oct_Dec)";
        } else if (quarter.equals("2")) {
            startyearmonth = year + "01";
            endyearmonth = year + "03";
            periodname = yearval + "_(Jan-Mar)";
        } else if (quarter.equals("3")) {
            startyearmonth = year + "04";
            endyearmonth = year + "06";
            periodname = yearval + "_(Apr_Jun)";
        } else if (quarter.equals("4")) {
            startyearmonth = year + "07";
            endyearmonth = year + "09";
            periodname = yearval + "_(Jul_Sep)";
        }

        int colsmerging = 6;
        String Sections[] = { "ART", "HTC", "PMTCT" };
        String headers[] = { "County", "Sub-County", "Facility", "Year", "Month" };
        String headergsn[] = { "County", "Sub-County", "Facility" };
        //if one wants gaps for one service area
        if (request.getParameterValues("gapsection") != null) {

            Sections = request.getParameterValues("gapsection");

        }
        //This is the loop that well use to create worksheets for each 

        String period = " 1=1 and Annee=" + yearval + " and yearmonth between " + startyearmonth + " and "
                + endyearmonth + " ";
        String gsnperiod = " 1=1  ";

        //______________________________________________________________________________________
        //______________________________________________________________________________________

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

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

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

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

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

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

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

        stylex2.setFont(fontx);
        stylex2.setWrapText(true);

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

        for (int a = 0; a < Sections.length; a++) {
            int column = 0;
            int Row = 3;

            Sheet shet = wb.createSheet(Sections[a]);

            Row rwx = shet.createRow(2);
            Row rw1 = null;
            Row rw2 = null;
            Row rw = shet.createRow(0);
            rw.setHeightInPoints(25);
            Cell cl0 = rw.createCell(0);
            cl0.setCellValue(Sections[a] + " GAP ANALYSIS");
            cl0.setCellStyle(stylex1);

            //this will depend on the length of the number of elements being checked

            for (int b = 1; b <= colsmerging; b++) {
                Cell clx = rw.createCell(b);
                clx.setCellValue("");
                clx.setCellStyle(stylex);
            }

            //now go to the database and do a query for each section
            int determinant = 2;
            String getqueries = " Select * from gap_analysis where active=1 and section='" + Sections[a] + "' ";

            conn.rs = conn.st.executeQuery(getqueries);
            while (conn.rs.next()) {

                //if an excel sheet exists, then get the row number 1

                if (shet.getRow(1) != null) {
                    rw1 = shet.getRow(1);
                } else {
                    rw1 = shet.createRow(1);
                    rw1.setHeightInPoints(25);
                }

                //print blanks before printing real header
                //for gsns, we only print three columns and no period
                if (conn.rs.getString("id").equals("1")) {

                    for (int p = 0; p < headergsn.length; p++) {
                        Cell cl2 = rw1.createCell(column + p);
                        cl2.setCellValue("");
                        cl2.setCellStyle(stylex);
                        shet.setColumnWidth(column + p, 5000);
                    }
                } else {

                    for (int p = 0; p < headers.length; p++) {
                        Cell cl2 = rw1.createCell(column + p);
                        cl2.setCellValue("");
                        cl2.setCellStyle(stylex);
                        shet.setColumnWidth(column + p, 5000);
                    }

                }
                determinant++;
                if (determinant % 2 == 0) {

                    Cell cl1 = rw1.createCell(column);
                    cl1.setCellValue(conn.rs.getString("rule"));
                    cl1.setCellStyle(stylex3);

                } else {

                    Cell cl1 = rw1.createCell(column);
                    cl1.setCellValue(conn.rs.getString("rule"));
                    cl1.setCellStyle(stylex2);

                }

                //Create the column header  

                if (shet.getRow(2) != null) {
                    rw2 = shet.getRow(2);
                } else {
                    rw2 = shet.createRow(2);
                    rw2.setHeightInPoints(25);
                }
                if (conn.rs.getString("id").equals("1")) {

                    for (int p = 0; p < headergsn.length; p++) {
                        Cell cl2 = rw2.createCell(column + p);
                        cl2.setCellValue(headergsn[p]);
                        cl2.setCellStyle(stylex);
                    }
                } else {

                    for (int p = 0; p < headers.length; p++) {
                        Cell cl2 = rw2.createCell(column + p);
                        cl2.setCellValue(headers[p]);
                        cl2.setCellStyle(stylex);
                    }

                }

                String currentqry = conn.rs.getString("query");
                //process each query as you 
                //pass the necessary period parameters from the interface
                //rem each query ends with a 'and'
                if (conn.rs.getString("id").equals("1")) {
                    currentqry += gsnperiod;
                } else {

                    currentqry += period + " and subpartnera." + Sections[a] + "= 1 ";

                }

                System.out.println("" + currentqry);
                Row = 3;
                conn.rs1 = conn.st1.executeQuery(currentqry);

                while (conn.rs1.next()) {

                    if (shet.getRow(Row) != null) {
                        rwx = shet.getRow(Row);
                    } else {
                        rwx = shet.createRow(Row);
                        rwx.setHeightInPoints(25);
                    }
                    Cell cly = rwx.createCell(column);
                    cly.setCellValue(conn.rs1.getString("County"));
                    cly.setCellStyle(style2);

                    Cell cly2 = rwx.createCell(column + 1);
                    cly2.setCellValue(conn.rs1.getString("DistrictNom"));
                    cly2.setCellStyle(style2);//gsn sites do not have a yearmonth

                    Cell cly1 = rwx.createCell(column + 2);
                    cly1.setCellValue(conn.rs1.getString("SubPartnerNom"));
                    cly1.setCellStyle(style2);

                    //if the current list is not inclusive of GSNs

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

                        Cell cly3 = rwx.createCell(column + 3);
                        cly3.setCellValue(new Integer(conn.rs1.getString("yearmonth").substring(0, 4)));
                        cly3.setCellStyle(style2);

                        //the month section

                        Cell cly3x = rwx.createCell(column + 4);
                        cly3x.setCellValue(new Integer(conn.rs1.getString("yearmonth").substring(4)));
                        cly3x.setCellStyle(style2);

                        //my key is a 
                        String mykey = Sections[a] + conn.rs1.getString("SubPartnerNom") + "_"
                                + conn.rs1.getString("yearmonth") + "_";
                        //add all the facilities at this point
                        //ignore the sites in ART since they are static
                        if (!keyal.contains(mykey)) {
                            keyal.add(mykey);
                            countyal.add(conn.rs1.getString("County"));
                            scountyal.add(conn.rs1.getString("DistrictNom"));
                            facilal.add(conn.rs1.getString("SubPartnerNom"));
                            sectional.add(Sections[a]);
                            yearmonthal.add(conn.rs1.getString("yearmonth"));
                            monthal.add(conn.rs1.getString("yearmonth").substring(4));

                        }

                    }

                    Row++;

                }

                if (conn.rs.getString(1).equals("1")) {
                    column += 3;
                } else {
                    column += 5;
                }
                if (conn.rs.getString("id").equals("1")) {
                    shet.addMergedRegion(new CellRangeAddress(1, 1, 0, column - 1));
                } else {
                    shet.addMergedRegion(new CellRangeAddress(1, 1, column - 5, column - 1));
                }

            } //end of all queries per section

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

        } // end of sheets loop   

        //create a new sheet

        //county   subcounty   facility   yearmonth   section

        Sheet shet = wb.getSheet("Sheet1");

        Row rw = shet.createRow(0);
        Cell cl0 = rw.createCell(0);
        cl0.setCellValue("county");
        cl0.setCellStyle(stylex1);

        Cell cl1 = rw.createCell(1);
        cl1.setCellValue("subcounty");
        cl1.setCellStyle(stylex1);

        Cell cl2 = rw.createCell(2);
        cl2.setCellValue("facility");
        cl2.setCellStyle(stylex1);

        Cell cl3 = rw.createCell(3);
        cl3.setCellValue("year");
        cl3.setCellStyle(stylex1);

        Cell cl4 = rw.createCell(4);
        cl4.setCellValue("month");
        cl4.setCellStyle(stylex1);

        Cell cl5 = rw.createCell(5);
        cl5.setCellValue("section");
        cl5.setCellStyle(stylex1);

        for (int q = 0; q < keyal.size(); q++) {

            Row rwx = shet.createRow(q + 1);

            Cell cl01 = rwx.createCell(0);
            cl01.setCellValue(countyal.get(q).toString());
            cl01.setCellStyle(style2);

            Cell cl11 = rwx.createCell(1);
            cl11.setCellValue(scountyal.get(q).toString());
            cl11.setCellStyle(style2);

            Cell cl21 = rwx.createCell(2);
            cl21.setCellValue(facilal.get(q).toString());
            cl21.setCellStyle(style2);

            Cell cl31 = rwx.createCell(3);
            cl31.setCellValue(new Integer(yearmonthal.get(q).toString().substring(0, 4)));
            cl31.setCellStyle(style2);

            Cell cl41 = rwx.createCell(4);
            cl41.setCellValue(new Integer(monthal.get(q).toString()));
            cl41.setCellStyle(style2);

            Cell cl51 = rwx.createCell(5);
            cl51.setCellValue(sectional.get(q).toString());
            cl51.setCellStyle(style2);

        }

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

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

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

        File file = new File(pathtodelete);
        System.out.println("path: 2" + pathtodelete);

        if (file.delete()) {
            System.out.println(file.getName() + " is deleted!");
        } else {
            System.out.println("Delete operation  failed.");
        }

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

    }
}

From source file:it.unitn.elisco.utils.Utilities.java

public static Workbook getExcelFromQuestionList(String workbookName, List<Question> questions) {

    // Create EXCEL File (Workbook with sheets)
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet(workbookName);

    // Create styles for cells
    CellStyle questionStyle = workbook.createCellStyle();
    questionStyle.setWrapText(true);/*  w ww.  j av  a 2s  . com*/
    questionStyle.setVerticalAlignment(VerticalAlignment.CENTER);

    CellStyle othersStyle = workbook.createCellStyle();
    othersStyle.setAlignment(HorizontalAlignment.CENTER);
    othersStyle.setVerticalAlignment(VerticalAlignment.CENTER);

    // Create header row 
    Row headerRow = sheet.createRow(0);
    headerRow.createCell(0).setCellValue("ID");
    headerRow.createCell(1).setCellValue("TAG");
    headerRow.createCell(2).setCellValue("DOMANDA");
    headerRow.createCell(3).setCellValue("APRROVATA (SI/NO)");
    headerRow.getCell(0).setCellStyle(othersStyle);
    headerRow.getCell(1).setCellStyle(othersStyle);
    headerRow.getCell(2).setCellStyle(othersStyle);
    headerRow.getCell(3).setCellStyle(othersStyle);

    int rownum = 1;
    for (Question question : questions) {
        // Create a row
        Row row = sheet.createRow(rownum++);

        // Create cells for id and question and set their values
        row.createCell(0).setCellValue(question.getId());
        row.createCell(1).setCellValue(question.getTag());
        row.createCell(2).setCellValue(question.getBody());
        // Create empty cell for admin input
        row.createCell(3);

        // Set cell styles
        row.getCell(0).setCellStyle(othersStyle);
        row.getCell(1).setCellStyle(othersStyle);
        row.getCell(2).setCellStyle(questionStyle);
        row.getCell(3).setCellStyle(othersStyle);
    }

    sheet.autoSizeColumn(0);
    sheet.autoSizeColumn(1);
    sheet.setColumnWidth(2, 100 * 256); // Set questionStyle column width to 100 characters
    sheet.autoSizeColumn(3);

    return workbook;
}