Example usage for org.apache.poi.ss.usermodel Workbook createSheet

List of usage examples for org.apache.poi.ss.usermodel Workbook createSheet

Introduction

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

Prototype

Sheet createSheet(String sheetname);

Source Link

Document

Create a new sheet for this Workbook and return the high level representation.

Usage

From source file:nc.noumea.mairie.appock.services.impl.ExportExcelServiceImpl.java

License:Open Source License

private File createExcelTempFile(Map<AbstractEntity, Map<Service, List<ArticleDemande>>> map,
        AbstractEntity abstractEntity, String nomFichierSansExtension) throws IOException {
    Workbook wb = new XSSFWorkbook();
    Map<Service, List<ArticleDemande>> mapServiceListeArticleDemande = map.get(abstractEntity);

    for (Service service : mapServiceListeArticleDemande.keySet()) {
        Sheet sheet = wb
                .createSheet(service.getDirection().getLibelleCourt() + "-" + service.getLibelleCourt());
        sheet.protectSheet(configService.getMotDePasseVerrouExcel());

        construitEntete(wb, mapServiceListeArticleDemande, abstractEntity, service, sheet);
        remplitLigneArticle(wb, mapServiceListeArticleDemande.get(service), sheet);

        // Taille automatique des colonnes selon le contenu
        for (int i = 0; i < 20; i++) {
            sheet.autoSizeColumn(i);//w ww.  ja va  2s  .c o  m
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 768);
        }
    }
    // Ecriture dans le fichier
    File result = File.createTempFile(nomFichierSansExtension, ".xlsx");
    FileOutputStream fileStream = new FileOutputStream(result);
    wb.write(fileStream);
    return result;
}

From source file:nc.noumea.mairie.appock.services.impl.ExportExcelServiceImpl.java

License:Open Source License

@Override
public void exportCatalogue(Catalogue catalogue) throws IOException {
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("Feuil1");

    construitEnteteExportCatalogue(wb, sheet);
    int i = 1;/* w  w  w . j a  va2  s  .c om*/
    for (Famille famille : catalogue.getListeFamille()) {
        for (SousFamille sousFamille : famille.getListeSousFamille()) {
            for (ArticleCatalogue articleCatalogue : sousFamille.getListeArticleCatalogue()) {
                remplitLigneArticleExportCatalogue(wb, sheet, articleCatalogue, i++);
            }
        }
    }

    // Taille automatique des colonnes selon le contenu
    for (int colonne = 0; colonne <= 12; colonne++) {
        sheet.autoSizeColumn(colonne);
        sheet.setColumnWidth(colonne, sheet.getColumnWidth(colonne) + 768);
    }

    // Ecriture dans le fichier
    File result = File.createTempFile("Export Catalogue", ".xlsx");
    FileOutputStream fileStream = new FileOutputStream(result);
    wb.write(fileStream);

    downloadService.downloadToUser(result,
            "Export Catalogue " + AppockUtil.replaceAllSpecialCharacter(catalogue.getLibelle()) + ".xlsx");
    result.delete();
}

From source file:nc.noumea.mairie.organigramme.utils.ExportExcelUtil.java

License:Open Source License

@GlobalCommand
public static void genereExportExcel(EntiteDto entiteDto, boolean afficheFdpInactive,
        ISirhWSConsumer sirhWSConsumer) throws IOException {
    Workbook wb = new HSSFWorkbook();
    Sheet feuillePrincipale = wb.createSheet("Fiches de postes");
    creerEntete(feuillePrincipale);// ww w  .ja v  a  2s.  com

    String listIdStatutFDP = StatutFichePoste.getListIdStatutActif();

    if (afficheFdpInactive) {
        listIdStatutFDP += "," + StatutFichePoste.INACTIVE.getId();
    }

    int numeroLigne = 1;
    for (FichePosteDto fichePosteDto : sirhWSConsumer.getFichePosteByIdEntite(entiteDto.getIdEntite(),
            listIdStatutFDP, true)) {
        Row row = feuillePrincipale.createRow((short) numeroLigne);
        row.createCell(NUM_COL_SIGLE).setCellValue(fichePosteDto.getSigle());
        row.createCell(NUM_COL_NUMERO).setCellValue(fichePosteDto.getNumero());
        row.createCell(NUM_COL_TITRE).setCellValue(fichePosteDto.getTitre());
        row.createCell(NUM_COL_STATUT).setCellValue(fichePosteDto.getStatutFDP());
        row.createCell(NUM_COL_CATEGORIE).setCellValue(fichePosteDto.getLibelleGradeCategorie());
        row.createCell(NUM_COL_AGENT).setCellValue(fichePosteDto.getAgent());
        row.createCell(NUM_COL_REGLEMENTAIRE).setCellValue(fichePosteDto.getReglementaire());
        row.createCell(NUM_COL_COMMENTAIRE).setCellValue(fichePosteDto.getCommentaire());

        numeroLigne++;
    }

    // Aucolumns
    for (int i = NUM_COL_SIGLE; i <= NUM_COL_COMMENTAIRE; i++) {
        feuillePrincipale.autoSizeColumn(i);
    }

    File tempFile = File.createTempFile("tempFile", ".xls");
    FileOutputStream fileStream = new FileOutputStream(tempFile);
    wb.write(fileStream);
    FileInputStream fileInputStream = new FileInputStream(tempFile);

    // Cration et sauvegarde du fichier
    String nomFichier = "Organigramme - Impression Fiche Poste - " + entiteDto.getSigle() + "-"
            + DateUtil.formatDateForFile(new Date()) + ".xls";
    Filedownload.save(IOUtils.toByteArray(fileInputStream), null, nomFichier);
}

From source file:net.ceos.project.poi.annotated.core.Engine.java

License:Apache License

/**
 * Initialize Sheet./*w ww . j a  va 2s .  c  om*/
 * 
 * @param wb
 *            the {@link Workbook} to use
 * @param sheetName
 *            the name of the sheet
 * @return the {@link Sheet} created
 * @throws SheetException
 *             given when problem at the initialization of the sheet.
 */
private Sheet initializeSheet(final Workbook wb, final String sheetName) throws SheetException {
    Sheet s = null;
    try {
        s = wb.createSheet(sheetName);
    } catch (Exception e) {
        throw new SheetException(ExceptionMessage.SHEET_CREATION_SHEET.getMessage(), e);
    }
    return s;
}

From source file:no.imr.sea2data.stox.components.table.OutputTopComponent.java

private void jExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jExcelActionPerformed
    FileOutputStream out = null;//from   w  ww .java  2s.c  om
    try {
        Workbook wb = new HSSFWorkbook();
        for (int iPage = 0; iPage < jTabbedPane1.getTabCount(); iPage++) {
            OutputPanel panel = (OutputPanel) jTabbedPane1.getComponentAt(iPage);
            String text = panel.getText();
            String[] lines = text.split("\n");
            if (lines.length < 60000) {
                Sheet sh = wb.createSheet(panel.getTabName());
                for (int i = 0; i < lines.length; i++) {
                    String line = lines[i];
                    String[] cells = line.split("\t");
                    for (int j = 0; j < cells.length; j++) {
                        Cell c = safeCell(sh, i, j);
                        String cell = cells[j];
                        Double d = Conversion.safeStringtoDoubleNULL(cell);
                        if (d != null) {
                            c.setCellValue(d);
                        } else {
                            if (cell.length() > 1000) {
                                cell = cell.substring(0, 1000);
                            }
                            c.setCellValue(cell);
                        }
                    } // for
                } // for
            }
        } // for
        String outFile = System.getProperty("java.io.tmpdir") + "/stox_output_"
                + IMRdate.formatDate(new Date(), "dd-MM-yyyy HH-mm-ss", false) + ".xls";
        out = new FileOutputStream(new File(outFile));
        wb.write(out);
        out.close();
        Desktop.getDesktop().open(new File(outFile));
    } catch (FileNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

}

From source file:NoCongruential.LinealAlgorithm.java

public void calcNumbers(String x0, String a, String c, String m, String cantidad) {
    int y = 0;//from w  w w  .  ja  v a 2s .  c o m
    double random;

    try {
        if (archivoXLS.exists()) {
            archivoXLS.delete();
        }
        archivoXLS.createNewFile();
        Workbook libro = new HSSFWorkbook();

        FileOutputStream archivo = new FileOutputStream(archivoXLS);
        Sheet hoja = libro.createSheet("Mi hoja de trabajo 1");

        HSSFRow fila = (HSSFRow) hoja.createRow(0);
        Cell celda = fila.createCell(0);
        celda.setCellValue("X");
        celda = fila.createCell(1);
        celda.setCellValue("r");

        for (int i = 0; i < Integer.parseInt(cantidad); i++) {
            fila = (HSSFRow) hoja.createRow(i + 1);
            celda = fila.createCell(0);
            celda.setCellValue(x0);
            x0 = String.valueOf(
                    ((Integer.parseInt(a) * Float.parseFloat(x0)) + Integer.parseInt(c)) % Integer.parseInt(m));
            random = (Float.parseFloat(x0) / (Integer.parseInt(m) - 1));
            System.out.println("rando " + random);
            celda = fila.createCell(1);
            celda.setCellValue(random);
        }

        libro.write(archivo);
        archivo.close();
    } catch (IOException e) {
    }

}

From source file:nz.ac.auckland.abi.formatting.poi.ModelJSONToExcel.java

License:LGPL

public void createXLS(Hashtable<String, String> models, String filename) throws Exception {
    List<FEMModelMeasure> measures = new ArrayList<FEMModelMeasure>();
    int maxTimePoints = 0;
    for (String model : models.keySet()) {
        String json = models.get(model);
        FEMModelMeasure mMeasure = new FEMModelMeasure(json, model);
        if (mMeasure.getTimePoints() > maxTimePoints) {
            maxTimePoints = mMeasure.getTimePoints();
        }//from w ww  .j a v  a 2s  . co  m
        measures.add(mMeasure);
    }
    File xlFile = new File(filename);
    if (xlFile.exists()) {
        xlFile.delete();
    }

    Workbook wb = new HSSFWorkbook();
    Map<String, CellStyle> styles = createStyles(wb);
    // Create an Aggregate sheet to collate the data across models/measures
    // Create here, so that it is the first sheet
    Sheet dashboard = wb.createSheet("Dashboard");

    // Create a worksheet for each measure type
    String[] names = getMeasureNames(measures);
    for (String name : names) {
        addWorkSheet(wb, name, measures, maxTimePoints, styles);
    }
    // Populate the dashboard
    createDashBoard(dashboard, names, measures, styles);
    createMetaData(wb, styles);
    FileOutputStream out = new FileOutputStream(filename);
    wb.write(out);
    out.close();
}

From source file:nz.ac.auckland.abi.formatting.poi.ModelJSONToExcel.java

License:LGPL

private void createMetaData(Workbook wb, Map<String, CellStyle> styles) {
    Sheet sheet = wb.createSheet("Metadata");
    int rowCounter = 0;
    int colCtr = 0;
    Row headerRow1 = sheet.createRow(rowCounter++);
    Cell headerCell = headerRow1.createCell(colCtr);
    headerRow1.getCell(0).setCellStyle(styles.get("header"));
    headerCell.setCellValue("Series formula");
    for (String series : userSeries) {
        Row row = sheet.createRow(rowCounter++);
        colCtr = 0;/*from ww w . j  a  va2s. c om*/
        Cell cell = row.createCell(colCtr++);
        cell.setCellValue(series);
    }
    headerRow1 = sheet.createRow(rowCounter++);
    headerRow1 = sheet.createRow(rowCounter++);
    headerCell = headerRow1.createCell(0);
    headerRow1.getCell(0).setCellStyle(styles.get("header"));
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy:HH:mm:SS Z");
    Calendar cal = Calendar.getInstance();
    headerCell.setCellValue("File created by ABI ICMA v 1.0 at " + format.format(cal.getTime()));
}

From source file:nz.ac.auckland.abi.formatting.poi.ModelJSONToExcel.java

License:LGPL

private void addWorkSheet(Workbook wb, String measure, List<FEMModelMeasure> measures, int maxTimePoints,
        Map<String, CellStyle> styles) {
    Sheet sheet = wb.createSheet(measure);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);//from  w ww.  j a va2s.co m
    sheet.setHorizontallyCenter(true);

    final int leadingHeaders = 4;
    int rowCounter = 0;
    // Create header row
    Row headerRow = sheet.createRow(rowCounter++);
    headerRow.setHeightInPoints(40);
    Cell headerCell;
    int colCtr = 0;
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("ModelName");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("StartTime");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("EndTime");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("MetaData");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("ID");
        headerCell.setCellStyle(styles.get("header"));
    }
    // Insert Time points
    for (int i = 0; i < maxTimePoints; i++) {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("" + i);
        headerCell.setCellStyle(styles.get("header"));
    }
    // Insert composite variables
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("MAX");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("MIN");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("MEAN");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("SD");
        headerCell.setCellStyle(styles.get("header"));
    }
    // Output the values for each measure

    for (FEMModelMeasure mes : measures) {
        double[][] strains = mes.getMeasure(measure);
        if (strains == null)
            continue;
        int numRows = strains.length + 1; // 1 for Avg
        int rowStarts = rowCounter;
        int colCounter = 0;
        for (int rctr = 0; rctr < numRows - 1; rctr++) {
            colCounter = 0;
            int myRowID = rowCounter + 1;
            Row row = sheet.createRow(rowCounter++);
            for (int colc = 0; colc < leadingHeaders; colc++) { // Common
                // Elements
                row.createCell(colCounter++);
            }
            // Create ROW ID
            {
                Cell cell = row.createCell(colCounter++);
                cell.setCellValue("S" + (rctr + 1));
            }
            String strainStartXLColName = getColumnPrefix(colCounter);
            int strainLength = strains[rctr].length;
            for (int stc = 0; stc < strainLength; stc++) {
                Cell cell = row.createCell(colCounter++);
                cell.setCellValue(strains[rctr][stc]);
            }
            String strainEndXLColName = getColumnPrefix(colCounter - 1);
            while (strainLength < maxTimePoints) { // Create dummy cells to
                // fill up space
                row.createCell(colCounter++);
                strainLength++;
            }
            // Add formulas and create names
            {
                //String modelName = mes.getModelName();
                //String sname = "";
                // MAX
                Cell cell = row.createCell(colCounter++);
                String ref = strainStartXLColName + "" + myRowID + ":" + strainEndXLColName + "" + myRowID;
                cell.setCellFormula("MAX(" + ref + ")");
                cell.setCellStyle(styles.get("MAX"));
                /*
                 * sname =
                 * (modelName+"_"+measure+"_"+"MAX_S"+(rctr+1)..replaceAll
                 * (" ", "_").trim(); Name namedCel = wb.createName();
                 * namedCel.setNameName(sname); String reference =
                 * measure+"!"+getColumnPrefix(colCounter-1)+myRowID; //
                 * cell reference namedCel.setRefersToFormula(reference);
                 */
                // MIN
                cell = row.createCell(colCounter++);
                cell.setCellFormula("MIN(" + ref + ")");
                cell.setCellStyle(styles.get("MIN"));
                /*
                 * sname = modelName+"_"+measure+"_"+"MIN_S"+(rctr+1);
                 * namedCel = wb.createName(); namedCel.setNameName(sname);
                 * reference =
                 * measure+"!"+getColumnPrefix(colCounter-1)+myRowID; //
                 * cell reference namedCel.setRefersToFormula(reference);
                 */
                // MEAN
                cell = row.createCell(colCounter++);
                cell.setCellFormula("AVERAGE(" + ref + ")");
                cell.setCellStyle(styles.get("AVERAGE"));
                /*
                 * sname = modelName+"_"+measure+"_"+"AVERAGE_S"+(rctr+1);
                 * namedCel = wb.createName(); namedCel.setNameName(sname);
                 * reference =
                 * measure+"!"+getColumnPrefix(colCounter-1)+myRowID; //
                 * cell reference namedCel.setRefersToFormula(reference);
                 */
                // STANDARD DEVIATION
                cell = row.createCell(colCounter++);
                cell.setCellFormula("STDEV(" + ref + ")");
                cell.setCellStyle(styles.get("STDEV"));
                /*
                 * sname = modelName+"_"+measure+"_"+"STDEV_S"+(rctr+1);
                 * namedCel = wb.createName(); namedCel.setNameName(sname);
                 * reference =
                 * measure+"!"+getColumnPrefix(colCounter-1)+""+myRowID; //
                 * cell reference namedCel.setRefersToFormula(reference);
                 */
            }
        }

        // Add user defined series
        Hashtable<String, String> formulaMap = new Hashtable<String, String>();
        for (String exp : userSeries) {

            // Replace all S[0-9]*, and D[0-9]* with appropriate column
            // values
            String toks[] = exp.split("=");
            int myRowID = rowCounter;
            colCounter = 0;
            Row row = sheet.createRow(rowCounter++);
            for (int colc = 0; colc < leadingHeaders; colc++) { // Common
                // Elements
                row.createCell(colCounter++);
            }
            // Create ROW ID
            {
                Cell cell = row.createCell(colCounter++);
                cell.setCellValue(toks[0]);
            }
            String strainStartXLColName = getColumnPrefix(colCounter);
            int strainLength = strains[numRows - 2].length;
            for (int stc = 0; stc < strainLength; stc++) {
                Cell cell = row.createCell(colCounter++);
                // Get the expression
                String expression = toks[1].toLowerCase();// Regex is case
                // senstive,
                // since th
                // COLUMN
                // PREFIXs are
                // CAPS,
                // replaceAll
                // will work as
                // expected else
                // S17 will
                // mathc for S1
                // (but not s1)
                for (int sCtr = mes.numSegments; sCtr > 0; sCtr--) {
                    String XLColName = (char) ('A' + stc + leadingHeaders + 1) + "" + (rowStarts + sCtr); // Note
                    // excel
                    // formulas
                    // need
                    // base
                    // 1
                    expression = expression.replaceAll("s" + sCtr + "{1}", XLColName);
                }
                cell.setCellFormula(expression);
                cell.setCellStyle(styles.get("AVGSERIES"));
            }
            String strainEndXLColName = getColumnPrefix(colCounter - 1);
            while (strainLength < maxTimePoints) { // Create dummy cells to
                // fill up space
                row.createCell(colCounter++);
                strainLength++;
            }
            // Add formulas and create names
            {
                StringBuffer formulas = new StringBuffer();

                String modelName = mes.getModelName();
                char c = modelName.charAt(0);
                if (c >= '0' && c <= '9') {
                    modelName = "_" + modelName;
                }
                String measureName = measure.replaceAll("\\(", "_").replaceAll("\\)", "_").replaceAll(" ", "");
                String sname = "";
                // MAX
                Cell cell = row.createCell(colCounter++);
                String ref = strainStartXLColName + myRowID + ":" + strainEndXLColName + myRowID;
                cell.setCellFormula("MAX(" + ref + ")");
                cell.setCellStyle(styles.get("MAX"));
                sname = (modelName + "_" + measureName + "_" + "MAX_" + toks[0]).replaceAll(" ", "_").trim();
                Name namedCel = wb.createName();
                namedCel.setNameName(sname);
                String reference = measureName + "!" + getColumnPrefix(colCounter - 1) + (myRowID + 1); // cell
                // reference
                // in
                // xl
                // base
                try {
                    namedCel.setRefersToFormula(reference);
                    formulas.append(reference + "#");
                    // MIN
                    cell = row.createCell(colCounter++);
                    cell.setCellFormula("MIN(" + ref + ")");
                    cell.setCellStyle(styles.get("MIN"));
                    sname = (modelName + "_" + measureName + "_" + "MIN_" + toks[0]).replaceAll(" ", "_")
                            .trim();
                    namedCel = wb.createName();
                    namedCel.setNameName(sname);
                    reference = measureName + "!" + getColumnPrefix(colCounter - 1) + (myRowID + 1); // cell
                    // reference
                    // in
                    // xl
                    // base
                    namedCel.setRefersToFormula(reference);
                    formulas.append(reference + "#");
                    // MEAN
                    cell = row.createCell(colCounter++);
                    cell.setCellFormula("AVERAGE(" + ref + ")");
                    cell.setCellStyle(styles.get("AVERAGE"));
                    sname = (modelName + "_" + measureName + "_" + "AVERAGE_" + toks[0]).replaceAll(" ", "_")
                            .trim();
                    namedCel = wb.createName();
                    namedCel.setNameName(sname);
                    reference = measureName + "!" + getColumnPrefix(colCounter - 1) + (myRowID + 1); // cell
                    // reference
                    // in
                    // xl
                    // base
                    namedCel.setRefersToFormula(reference);
                    formulas.append(reference + "#");
                    // STANDARD DEVIATION
                    cell = row.createCell(colCounter++);
                    cell.setCellFormula("STDEV(" + ref + ")");
                    cell.setCellStyle(styles.get("STDEV"));
                    sname = (modelName + "_" + measureName + "_" + "STDEV_" + toks[0]).replaceAll(" ", "_")
                            .trim();
                    namedCel = wb.createName();
                    namedCel.setNameName(sname);
                    reference = measureName + "!" + getColumnPrefix(colCounter - 1) + (myRowID + 1); // cell
                    // reference
                    // in
                    // xl
                    // base
                    namedCel.setRefersToFormula(reference);
                    formulas.append(reference);
                    formulaMap.put(toks[0], formulas.toString());
                } catch (Exception exx) {
                    //exx.printStackTrace();
                    System.out.println(exx + " occured for formula " + reference);
                }
            }
        }
        mes.addToFormulaMap(measure, formulaMap);
        // Set the commom columns
        Row row;
        Cell cell;
        row = sheet.getRow(rowStarts);
        cell = row.getCell(0);
        cell.setCellValue(mes.getModelName());
        cell = row.getCell(1);
        cell.setCellValue(mes.getStartTime());
        cell = row.getCell(2);
        cell.setCellValue(mes.getEndTime());
        cell = row.getCell(3);
        cell.setCellValue(mes.getMetaData());
        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$" + (rowStarts + 1) + ":$A$" + (rowCounter))); // Since
        // excel
        // number
        // starts
        // from
        // 1
        // but
        // api
        // is
        // 0
        sheet.addMergedRegion(CellRangeAddress.valueOf("$B$" + (rowStarts + 1) + ":$B$" + (rowCounter)));
        sheet.addMergedRegion(CellRangeAddress.valueOf("$C$" + (rowStarts + 1) + ":$C$" + (rowCounter)));
        sheet.addMergedRegion(CellRangeAddress.valueOf("$D$" + (rowStarts + 1) + ":$D$" + (rowCounter)));
        sheet.createRow(rowCounter++);// Create Empty row for model break
    }

}

From source file:om.edu.squ.squportal.portlet.tsurvey.dao.excel.TeachingSurveyExcelImpl.java

License:Open Source License

/**
 * // www.j  a v  a2 s. co  m
 * method name  : getExcelSurveyReport
 * @param object
 * @param response
 * @param params
 * @param locale
 * @return
 * @throws DocumentException
 * @throws IOException
 * TeachingSurveyExcelImpl
 * return type  : OutputStream
 * 
 * purpose      : Get Streaming excel object for valid/invalid survey report
 *
 * Date          :   Mar 16, 2016 1:23:57 PM
 */
public OutputStream getExcelSurveyReport(String templateName, Object object, ResourceResponse response,
        Map<String, String> params, Locale locale) throws DocumentException, IOException {
    int colHead = 0;
    int rowNum = 0;
    String paramStaffRole = params.get(Constants.CONST_ROLE_STAFF);
    String paramTypeSurvey = params.get(Constants.CONST_PARAM_TYPE_SURVEY);
    String paramSemesterCode = params.get(Constants.CONST_PARAM_SEMESTER_CODE);
    String titleRegion = null;

    Workbook workbook = new HSSFWorkbook();
    CreationHelper creationHelper = workbook.getCreationHelper();
    Map<String, CellStyle> styles = createStyles(workbook);
    Sheet sheet = null;
    Cell cellSH = null;
    List<ReportSummary> reportSummaries = (List<ReportSummary>) object;

    if (templateName.equals(Constants.CONST_VALID_SURVEY_REPORT)) {
        sheet = workbook.createSheet(
                UtilProperty.getMessage("prop.course.teaching.survey.report.survey.valid", null, locale));
    }
    if (templateName.equals(Constants.CONST_INVALID_SURVEY_REPORT)) {
        sheet = workbook.createSheet(
                UtilProperty.getMessage("prop.course.teaching.survey.report.survey.invalid", null, locale));
    }

    sheet.getPrintSetup().setLandscape(true);
    sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);

    /**  Header Footer **/
    Footer footer = sheet.getFooter();
    Header header = sheet.getHeader();
    footer.setRight("Page &P of &N");
    footer.setLeft("&D");
    header.setLeft(UtilProperty.getMessage("prop.course.teaching.survey.heading", null, locale));
    header.setCenter(UtilProperty.getMessage("prop.course.teaching.survey.title", null, locale));
    header.setRight(paramTypeSurvey + " - " + paramSemesterCode);

    sheet.setRepeatingRows(CellRangeAddress.valueOf("2:2"));
    sheet.setDisplayGridlines(true);
    sheet.setPrintGridlines(true);

    /**  Title **/
    Row titleRow = sheet.createRow(rowNum);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue(paramTypeSurvey + " - " + paramSemesterCode);
    titleCell.setCellStyle(styles.get(TITLE));

    ++rowNum;
    titleRegion = "$A$" + rowNum + ":$O$" + rowNum;
    sheet.addMergedRegion(CellRangeAddress.valueOf(titleRegion));

    /**  Header Row **/
    Row rowSubHeader = sheet.createRow(rowNum++);

    if (!paramStaffRole.equals(Constants.CONST_ROLE_STAFF_HOD)
            && !templateName.equals(Constants.CONST_INVALID_SURVEY_REPORT)) {

        cellSH = rowSubHeader.createCell(colHead++);
        cellSH.setCellValue(creationHelper.createRichTextString(
                UtilProperty.getMessage("prop.course.teaching.survey.rank.university", null, locale)));
        cellSH.setCellStyle(styles.get(SUB_HEADER));
        cellSH = rowSubHeader.createCell(colHead++);
        cellSH.setCellValue(creationHelper.createRichTextString(
                UtilProperty.getMessage("prop.course.teaching.survey.rank.college", null, locale)));
        cellSH.setCellStyle(styles.get(SUB_HEADER));
        cellSH = rowSubHeader.createCell(colHead++);
        cellSH.setCellValue(creationHelper.createRichTextString(
                UtilProperty.getMessage("prop.course.teaching.survey.rank.department", null, locale)));
        cellSH.setCellStyle(styles.get(SUB_HEADER));
    }
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.instructor.id", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.instructor.name", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.college", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    if (!paramStaffRole.equals(Constants.CONST_ROLE_STAFF_HOD)) {
        cellSH = rowSubHeader.createCell(colHead++);
        cellSH.setCellValue(creationHelper.createRichTextString(
                UtilProperty.getMessage("prop.course.teaching.survey.department", null, locale)));
        cellSH.setCellStyle(styles.get(SUB_HEADER));
    }
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.course.code", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.section", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.student.registered", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.response.number", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.mean", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.percentage", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.mean", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));
    cellSH = rowSubHeader.createCell(colHead++);
    cellSH.setCellValue(creationHelper.createRichTextString(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.percentage", null, locale)));
    cellSH.setCellStyle(styles.get(SUB_HEADER));

    /**  Report details **/
    for (ReportSummary reportSummary : reportSummaries) {
        int colNum = 0;
        Row row = sheet.createRow((short) rowNum);

        if (!paramStaffRole.equals(Constants.CONST_ROLE_STAFF_HOD)
                && !templateName.equals(Constants.CONST_INVALID_SURVEY_REPORT)) {
            row.createCell(colNum++).setCellValue(reportSummary.getUniversityRank());
            row.createCell(colNum++).setCellValue(reportSummary.getCollegeRank());
            row.createCell(colNum++).setCellValue(reportSummary.getDepartmentRank());
        }
        row.createCell(colNum++).setCellValue(Double.parseDouble(reportSummary.getEmpNumber()));
        row.createCell(colNum++).setCellValue(creationHelper.createRichTextString(reportSummary.getEmpName()));
        row.createCell(colNum++)
                .setCellValue(creationHelper.createRichTextString(reportSummary.getCollegeCode()));
        if (!paramStaffRole.equals(Constants.CONST_ROLE_STAFF_HOD)) {
            row.createCell(colNum++)
                    .setCellValue(creationHelper.createRichTextString(reportSummary.getDepartmentName()));
        }
        row.createCell(colNum++).setCellValue(reportSummary.getCourseCode());
        row.createCell(colNum++).setCellValue(Integer.parseInt(reportSummary.getSectionNo()));
        row.createCell(colNum++).setCellValue(reportSummary.getRegisteredStudent());

        Cell cellStudentNoResponse = row.createCell(colNum++);
        cellStudentNoResponse.setCellValue(reportSummary.getStudentNoResponse());
        cellStudentNoResponse.setCellStyle(styles.get(FORMULA_1));

        Cell cellTeachingMean = row.createCell(colNum++);
        cellTeachingMean.setCellValue(reportSummary.getTeachingMean());
        cellTeachingMean.setCellStyle(styles.get(FORMULA_1));

        Cell cellTeachingPercentageFavor = row.createCell(colNum++);
        cellTeachingPercentageFavor.setCellValue(reportSummary.getTeachingPercentageFavor());
        cellTeachingPercentageFavor.setCellStyle(styles.get(FORMULA_1));

        Cell cellQuestionMean = row.createCell(colNum++);
        cellQuestionMean.setCellValue(reportSummary.getQuestionMean());
        cellQuestionMean.setCellStyle(styles.get(FORMULA_1));

        Cell cellQuestionPercentageFavor = row.createCell(colNum++);
        cellQuestionPercentageFavor.setCellValue(reportSummary.getQuestionPercentageFavor());
        cellQuestionPercentageFavor.setCellStyle(styles.get(FORMULA_1));

        rowNum++;

    }

    response.setContentType("application/vnd.ms-excel");
    OutputStream outputStream = response.getPortletOutputStream();
    workbook.write(outputStream);
    outputStream.flush();
    outputStream.close();

    return null;
}