Example usage for org.apache.poi.hssf.usermodel HSSFSheet autoSizeColumn

List of usage examples for org.apache.poi.hssf.usermodel HSSFSheet autoSizeColumn

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFSheet autoSizeColumn.

Prototype

@Override
public void autoSizeColumn(int column) 

Source Link

Document

Adjusts the column width to fit the contents.

This process can be relatively slow on large sheets, so this should normally only be called once per column, at the end of your processing.

Usage

From source file:Adicionales.Abrir_xml.java

private void ExportarEtiquetasXml(HSSFWorkbook workbook, Document document, String nombre) {
    System.out.println("Exportando : " + nombre);
    try {/*from w w w .  j  av  a 2s  .c om*/
        HSSFSheet sheet = workbook.createSheet(tipo_comprobante + " " + (nombres.indexOf(nombre) + 1));
        System.out.println("Primera vez creada");
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFRow rowTag = sheet.createRow(0);
        HSSFRow RowData = sheet.createRow(1);
        NodeList nodeList = document.getElementsByTagName("*");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            if (element.getChildNodes().getLength() == 1 && !element.getNodeName().contains(":")) {
                if (element.getFirstChild().getNodeType() == Node.TEXT_NODE
                        && !element.getNodeName().equals("comprobante")) {
                    HSSFCell cellTag = rowTag.createCell(i);
                    cellTag.setCellValue(element.getNodeName());
                    HSSFCell cellData = RowData.createCell(i);
                    cellData.setCellValue(element.getFirstChild().getNodeValue());
                    sheet.autoSizeColumn((short) i);
                    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                    cellTag.setCellStyle(cellStyle);
                } else {
                    DocumentBuilderFactory sub_factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder sub_builder = sub_factory.newDocumentBuilder();
                    Document sub_document = sub_builder
                            .parse(new InputSource(new StringReader(element.getFirstChild().getNodeValue())));
                    NodeList sub_nodeList = sub_document.getElementsByTagName("*");
                    for (int j = 0; j < sub_nodeList.getLength(); j++) {
                        Element sub_element = (Element) sub_nodeList.item(j);
                        if (sub_element.getNodeName().equals("Signature"))
                            break;
                        if (sub_element.getChildNodes().getLength() == 1
                                && !sub_element.getNodeName().contains(":")) {
                            if (sub_element.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                                HSSFCell cellTag = rowTag.createCell(j);
                                cellTag.setCellValue(sub_element.getNodeName());
                                HSSFCell cellData = RowData.createCell(j);
                                cellData.setCellValue(sub_element.getFirstChild().getNodeValue());
                                sheet.autoSizeColumn((short) j);
                                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                                cellTag.setCellStyle(cellStyle);
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (IllegalArgumentException e) {
        JOptionPane.showMessageDialog(null, "<html>Error al exportar archivo " + nombre
                + "<br>Verificar maximo de etiquetas soportadas [255]</html>");
    } catch (ParserConfigurationException e) {
        System.out.println("ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
        System.out.println("SAXException " + e.getMessage());
    }
}

From source file:android_connector.ConfigWindowController.java

/**
 * Speichert die Ergebnisse der Lufe als Excel-Tabelle.
 *
 * @author Quelle:/* ww  w  .  jav a2 s .  com*/
 * http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/
 * @param programmende True, wenn das Programm beendet werden soll, sonst
 * false.
 *
 */
public void printResults(boolean programmende) {
    /**
     * Zahl der Messtore.
     */
    int tore = Integer.parseInt(messtore.getText());
    /**
     * Gibt die gespeicherten Werte der DB an. Jedes Unterarray
     * reprsentiert einen Datensatz. Der zweite Index ist bei 0 die
     * Startnummer, 1 der Name, 2 die Kategorie, 3 Lauf 1, 4 Lauf 2.
     */
    String[][] werte = (new MySQLConnection(host.getText(), port.getText(), db.getText(), user.getText(),
            pw.getText(), null)).getAuswertung(starter, tore);
    //FileChooser einsetzen, um Speicherort zu ermitteln
    FileChooser fc = new FileChooser();
    //Titel anzeigen
    fc.setTitle("Speicherort fr die Auswertung:");
    //standardmig im Home-Verzeichnis starten
    fc.setInitialDirectory(new File(System.getProperty("user.home")));
    //Alle-Dateien-Filter entfernen
    fc.setSelectedExtensionFilter(null);
    //FileFilter fr Exceldateien hinzufgen
    //nur "alte" Excel-Dateien knnen geschrieben werden!
    fc.getExtensionFilters()
            .addAll(new FileChooser.ExtensionFilter("Microsoft Excel 1997-2003 Dokument (.xls)", "*.xls"));
    //Dateien einlesen
    File returnVal = fc.showSaveDialog(primaryStage);
    //prfen, ob Datei zurckgegeben --> eine gewhlt; muss aber nicht existieren
    if (returnVal != null) {
        /**
         * Reprsentation der Excel-Datei.
         */
        HSSFWorkbook workbook = new HSSFWorkbook();
        /**
         * Alle Kategorien, die angegeben sind.
         */
        List<String> kategorien = getKategorien();
        //alle Kategorien durchgehen, fr alle eine Mappe der DB fllen.
        for (String kategorie : kategorien) {
            /**
             * Reprsentiert die Mappe, in der die Daten landen.
             */
            HSSFSheet sheet;
            //Prfen, ob die Lnge des Kategorienamens zwischen 1 und 31 liegt --> sonst ungltig
            if (!kategorie.isEmpty() && kategorie.length() < 31) {
                //wenn ja: Kategoriename ist Mappenname
                sheet = workbook.createSheet(kategorie);
                //sonst: Standardname
            } else {
                sheet = workbook.createSheet("namenlose Kategorie");
            }

            Map<String, List<String>> data = new HashMap<String, List<String>>();
            List<String> label = new ArrayList<>();
            label.add("Startnummer");
            label.add("Name");
            label.add("Kategorie");
            label.add("reine Laufzeit- Lauf 1");
            label.add("Gesamtstrafen- Lauf 1");
            label.add("Laufzeit insgesamt- Lauf 1");
            for (int i = 0; i < tore; i++) {
                label.add("Strafe Tor " + (i + 1));
            }
            label.add("reine Laufzeit- Lauf 2");
            label.add("Gesamtstrafen- Lauf 2");
            label.add("Laufzeit insgesamt- Lauf 2");
            for (int i = 0; i < tore; i++) {
                label.add("Strafe Tor " + (i + 1));
            }
            data.put("0", label);

            for (int i = 0; i < werte.length; i++) {
                //data.put(""+(i+2), werte[i]);
                if (werte[i][2] != null) {
                    if (werte[i][2].equals(kategorie)) {
                        List<String> angaben = new ArrayList<>();
                        angaben.add(werte[i][0]);
                        angaben.add(werte[i][1]);
                        angaben.add(werte[i][2]);
                        String lauf1 = werte[i][3];
                        if (werte[i][3] != null && !werte[i][3].isEmpty()) {
                            angaben.addAll(extractList(lauf1));
                        }
                        if (werte[i][4] != null && !werte[i][4].isEmpty()) {
                            angaben.addAll(extractList(werte[i][4]));
                        }
                        data.put("" + (i + 1), angaben);
                    }
                }
            }
            Set<String> keyset = data.keySet();
            int rownum = 0;
            for (String key : keyset) {
                Row row = sheet.createRow(rownum++);
                List<String> objArr = data.get(key);
                int cellnum = 0;
                for (Object obj : objArr) {
                    Cell cell = row.createCell(cellnum++);
                    if (obj instanceof Date) {
                        cell.setCellValue((Date) obj);
                    } else if (obj instanceof Boolean) {
                        cell.setCellValue((Boolean) obj);
                    } else if (obj instanceof String) {
                        cell.setCellValue((String) obj);
                    } else if (obj instanceof Double) {
                        cell.setCellValue((Double) obj);
                    }
                }
            }
            for (int i = 0; i < 9 + 2 * tore; i++) {
                sheet.autoSizeColumn(i);
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(returnVal);
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully..");
            out = new FileOutputStream(System.getProperty("user.home") + "/Kanu-s.a.M.-Notfall.xls");
            workbook.write(out);
            out.close();

        } catch (FileNotFoundException e) {
            MySQLConnection.staticExceptionDialog(e, "Schreibfehler",
                    "Auswertung konnte nicht geschrieben werden",
                    "Die Excel-Datei mit der Auswertung konnte nicht geschrieben werden. Bitte versuchen Sie es erneut!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (programmende) {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Programmende");
        alert.setHeaderText("Der Programmablauf ist beendet.");
        alert.setContentText(
                "Das Programm hat seine Aufgabe erfllt und wird nun beendet. Vielen Dank fr die Benutzung des Softwaresystems!");
        alert.showAndWait();
        Platform.exit();
    }
}

From source file:at.htlpinkafeld.beans.AlleAbwesenheitenBean.java

/**
 * xls post processing/* w w  w  .ja v  a2s  .  co m*/
 *
 * @param document xls document
 */
public void postProcessXLS(Object document) {
    HSSFWorkbook wb = (HSSFWorkbook) document;
    HSSFSheet sheet = wb.getSheetAt(0);

    HSSFRow header = sheet.getRow(0);

    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        HSSFCell cell = header.getCell(i);
        cell.setCellStyle(cellStyle);

        sheet.autoSizeColumn(i);
    }

    HSSFRow bottomRow = sheet.createRow(sheet.getLastRowNum() + 2);
    bottomRow.createCell(0)
            .setCellValue("Stand: " + LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));

}

From source file:at.htlpinkafeld.beans.JahresuebersichtBean.java

/**
 * post processes the XLS for creating//from w w w  .  j  a v a2s.  c  o m
 *
 * @param document xls-doc
 */
public void postProcessXLS(Object document) {
    HSSFWorkbook wb = (HSSFWorkbook) document;
    HSSFSheet sheet = wb.getSheetAt(0);

    sheet.shiftRows(0, sheet.getLastRowNum(), 2);

    HSSFRow topRow = sheet.createRow(0);

    topRow.createCell(0).setCellValue("Jahresbersicht - " + selectedYear.getYear());
    topRow.createCell(3).setCellValue("von " + selectedUser.getPersName());
    sheet.createRow(1).createCell(0).setCellValue(" ");

    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));

    HSSFRow header = sheet.getRow(2);
    HSSFRow footer = sheet.getRow(sheet.getLastRowNum());

    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        HSSFCell cell = header.getCell(i);
        cell.setCellStyle(cellStyle);

        cell = footer.getCell(i);
        cell.setCellStyle(cellStyle);

        sheet.autoSizeColumn(i);
    }

    HSSFRow bottomRow = sheet.createRow(sheet.getLastRowNum() + 2);
    bottomRow.createCell(0)
            .setCellValue("Stand: " + LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));

}

From source file:at.htlpinkafeld.beans.UserDetailsBean.java

public void postProcessXLS(Object document) {
        HSSFWorkbook wb = (HSSFWorkbook) document;
        HSSFSheet sheet = wb.getSheetAt(0);

        sheet.shiftRows(0, sheet.getLastRowNum(), 2);

        HSSFRow topRow = sheet.createRow(0);

        topRow.createCell(0)/*from  w  ww  .  ja  v a  2 s.c  o  m*/
                .setCellValue("Monatsbersicht - " + selectedDate.format(DateTimeFormatter.ofPattern("MM.yyyy")));
        topRow.createCell(7).setCellValue("von " + selectedUser);
        sheet.createRow(1).createCell(0).setCellValue(" ");

        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));

        HSSFRow header = sheet.getRow(2);
        HSSFRow footer = sheet.getRow(sheet.getLastRowNum());

        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
            HSSFCell cell = header.getCell(i);
            cell.setCellStyle(cellStyle);

            cell = footer.getCell(i);
            cell.setCellStyle(cellStyle);

            sheet.autoSizeColumn(i);
        }

        HSSFRow bottomRow = sheet.createRow(sheet.getLastRowNum() + 2);
        bottomRow.createCell(0)
                .setCellValue("Stand: " + LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));

    }

From source file:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileExcelParser.java

License:Open Source License

public void export(Date date, DiveProfile diveProfile, File file) throws IOException {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(UIAgent.getInstance().getExportFormatDateHoursFull().format(date));

    HSSFCellStyle cellStyle = wb.createCellStyle();
    HSSFFont font = wb.createFont();/*  w w w  . j  a  va  2s  . c om*/
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    cellStyle.setFont(font);

    int rowIndex = 0;
    int colIndex = 0;
    HSSFRow row = sheet.createRow(rowIndex++);
    HSSFCell cell = row.createCell(colIndex++);
    cell.setCellValue("Time (s)");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Depth (m)");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Ascent Warning");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Bottom Time Warning");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Deco Ceiling Warning");
    cell.setCellStyle(cellStyle);

    cell = row.createCell(colIndex++);
    cell.setCellValue("Deco Entry");
    cell.setCellStyle(cellStyle);

    Map<Double, Double> entries = diveProfile.getDepthEntries();
    List<Double> seconds = new ArrayList<Double>(entries.keySet());
    Collections.sort(seconds);
    for (Double time : seconds) {
        colIndex = 0;
        row = sheet.createRow(rowIndex++);
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_NUMERIC).setCellValue(time);
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_NUMERIC).setCellValue(entries.get(time));
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_BOOLEAN)
                .setCellValue(diveProfile.getAscentWarnings().contains(time));
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_BOOLEAN)
                .setCellValue(diveProfile.getRemainingBottomTimeWarnings().contains(time));
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_BOOLEAN)
                .setCellValue(diveProfile.getDecoCeilingWarnings().contains(time));
        row.createCell(colIndex++, HSSFCell.CELL_TYPE_BOOLEAN)
                .setCellValue(diveProfile.getDecoEntries().contains(time));
    }

    for (int i = 0; i <= colIndex; i++) {
        sheet.autoSizeColumn(i);
    }

    FileOutputStream fileOut = new FileOutputStream(file);
    wb.write(fileOut);
    fileOut.close();
}

From source file:br.com.pontocontrol.controleponto.controller.impl.ExportadorXLSController.java

@Override
public boolean extrair(FolhaMensalPonto folhaMensal, String outputFileDir) {
    Calendar data = Calendar.getInstance();
    data.set(Calendar.MONTH, folhaMensal.getMes());
    data.set(Calendar.YEAR, folhaMensal.getAno());
    final String nomeArquivo = format("%s-%s_%s.xls",
            SessaoManager.getInstance().getUsuarioAutenticado().getLogin(),
            formatDate("yyyy-MMMM", data.getTime()), formatDate("yyyyMMddHHmmssSSS", new Date()));
    final String filePath = format("%s/%s", outputFileDir, nomeArquivo);
    File arquivoXLS = new File(filePath);
    FileOutputStream fos = null;/*  ww w.j a  va  2 s  .co m*/
    try {
        arquivoXLS.createNewFile();

        fos = new FileOutputStream(arquivoXLS);

        HSSFWorkbook workbook = HSSFWorkbook.create(InternalWorkbook.createWorkbook());

        final String nomePlanilha = formatDate("MMM-yy", data.getTime());
        HSSFSheet planilha = workbook.createSheet(nomePlanilha);

        //TOTAL ROW
        HSSFRow totalRow = planilha.createRow(0);
        totalRow.createCell(CELL_INDEX.TOTAL_ROW.TOTAL_TXT).setCellValue("Total:");
        totalRow.createCell(CELL_INDEX.TOTAL_ROW.TOTAL_VALUE).setCellValue(folhaMensal.calcularTotalMensal());
        totalRow.createCell(CELL_INDEX.TOTAL_ROW.VAR_TXT).setCellValue("Variao:");
        totalRow.createCell(CELL_INDEX.TOTAL_ROW.VAR_VALUE).setCellValue(folhaMensal.calcularVariacaoMensal());

        //HEADER
        HSSFRow headerRow = planilha.createRow(1);
        headerRow.createCell(CELL_INDEX.DIA).setCellValue("Dia");
        headerRow.createCell(CELL_INDEX.ENTRADA).setCellValue("Entrada");
        headerRow.createCell(CELL_INDEX.ALMOCO).setCellValue("Almoo");
        headerRow.createCell(CELL_INDEX.RETORNO).setCellValue("Retorno");
        headerRow.createCell(CELL_INDEX.SAIDA).setCellValue("Sada");
        headerRow.createCell(CELL_INDEX.TOTAL_EXP).setCellValue("Expediente");
        headerRow.createCell(CELL_INDEX.VARIACAO).setCellValue("Variao");

        formatHeaderRow(workbook, headerRow);
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, folhaMensal.getAno());
        cal.set(Calendar.MONTH, folhaMensal.getMes());

        for (int dia = 1; dia <= cal.getActualMaximum(Calendar.DAY_OF_MONTH); dia++) {
            int i = planilha.getPhysicalNumberOfRows();
            HSSFRow row = planilha.createRow(i);
            cal.set(Calendar.DAY_OF_MONTH, dia);
            row.createCell(CELL_INDEX.DIA).setCellValue(formatDate("MMM dd, EEE", cal.getTime()));

            RegistroDiarioPonto reg = folhaMensal.getRegistros().get(dia);
            if (reg != null) {
                row.createCell(CELL_INDEX.ENTRADA)
                        .setCellValue(reg.getEntrada() != null ? reg.getEntrada().format(TIME_FORMATTER) : "");
                row.createCell(CELL_INDEX.ALMOCO)
                        .setCellValue(reg.getAlmoco() != null ? reg.getAlmoco().format(TIME_FORMATTER) : "");
                row.createCell(CELL_INDEX.RETORNO)
                        .setCellValue(reg.getRetorno() != null ? reg.getRetorno().format(TIME_FORMATTER) : "");
                row.createCell(CELL_INDEX.SAIDA)
                        .setCellValue(reg.getSaida() != null ? reg.getSaida().format(TIME_FORMATTER) : "");
                row.createCell(CELL_INDEX.TOTAL_EXP).setCellValue(
                        reg.isRegistroDiarioCompleto() ? reg.calcularTotalExpedienteAsNumber() : 0);
                row.createCell(CELL_INDEX.VARIACAO)
                        .setCellValue(reg.isRegistroDiarioCompleto() ? reg.calcularVariacaoExpediente() : 0);
            } else {
                row.createCell(CELL_INDEX.ENTRADA).setCellValue("");
                row.createCell(CELL_INDEX.ALMOCO).setCellValue("");
                row.createCell(CELL_INDEX.RETORNO).setCellValue("");
                row.createCell(CELL_INDEX.SAIDA).setCellValue("");
                row.createCell(CELL_INDEX.TOTAL_EXP).setCellValue("");
                row.createCell(CELL_INDEX.VARIACAO).setCellValue("");
            }
            if (SessaoManager.getInstance().getUsuarioAutenticado().checarSeDiaExpediente(cal)) {
                formatRow(workbook, row);
            } else {
                formatHeaderRow(workbook, row);
            }
        }
        for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
            planilha.autoSizeColumn(i);
        }
        workbook.write(fos);
        fos.flush();
        return true;
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, "Erro ao criar arquivo XLS de sada", ex);
        return false;
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:br.solutio.licita.controlador.ControladorPregao.java

public void editandoXlsParaExportar(Object document) {
    HSSFWorkbook wb = (HSSFWorkbook) document;
    HSSFSheet planilha = wb.getSheetAt(0);

    //Move as celulas selecionadas para baixo de acordo com o valor informado
    planilha.shiftRows(planilha.getFirstRowNum(), planilha.getLastRowNum(), 5);

    HSSFRow linha0 = planilha.createRow(0);
    linha0.createCell(0).setCellValue("Instituio Licitadora:");
    planilha.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
    linha0.createCell(2)//from   w  w  w .  j a va  2  s  . c  o  m
            .setCellValue(" " + getEntidade().getInstituicaoLicitadora().getPessoaJuridica().getNomeFantasia());
    planilha.addMergedRegion(new CellRangeAddress(0, 0, 2, 6));

    HSSFRow linha1 = planilha.createRow(1);
    linha1.createCell(0).setCellValue("Numero do Pregao:");
    planilha.addMergedRegion(new CellRangeAddress(1, 1, 0, 1));
    linha1.createCell(2).setCellValue(" " + getEntidade().getNumeroPregao());
    planilha.addMergedRegion(new CellRangeAddress(1, 1, 2, 6));

    HSSFRow linha2 = planilha.createRow(2);
    linha2.createCell(0).setCellValue("Numero do Processo:");
    planilha.addMergedRegion(new CellRangeAddress(2, 2, 0, 1));
    linha2.createCell(2).setCellValue(" " + getEntidade().getNumeroProcesso());
    planilha.addMergedRegion(new CellRangeAddress(2, 2, 2, 6));

    HSSFRow linha3 = planilha.createRow(3);
    linha3.createCell(0).setCellValue("Empresa Licitante:");
    planilha.addMergedRegion(new CellRangeAddress(3, 3, 0, 1));
    linha3.createCell(2).setCellValue("Preencha com o nome de sua Empresa");
    planilha.addMergedRegion(new CellRangeAddress(3, 3, 2, 6));

    HSSFRow linha4 = planilha.createRow(4);

    //Nova coluna para a empresas adicionarem seus valores
    HSSFRow linha5 = planilha.getRow(5);
    HSSFCell celula5 = linha5.createCell(5);
    celula5.setCellValue("Valor do Licitante");

    //for para ajustar automaticamente o tamnho das colunas
    for (int i = 0; i < 6; i++) {
        planilha.autoSizeColumn(i);
    }

    //Cor da linha de titulos da tabela
    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    for (int i = 0; i < linha5.getPhysicalNumberOfCells(); i++) {
        HSSFCell cell = linha5.getCell(i);

        cell.setCellStyle(cellStyle);
    }

    CellStyle unlockedCellStyle = wb.createCellStyle();
    unlockedCellStyle.setLocked(false);

    HSSFCell celula2 = linha3.getCell(2);
    celula2.setCellStyle(unlockedCellStyle);

}

From source file:br.sp.telesul.service.ExportServiceImpl.java

public void writeExcel(String templateHead, String[] columns, HSSFWorkbook workbook) {
    try {//  w ww .ja  v  a2 s  .c  om
        List<Funcionario> funcionarios = funcionarioService.search();

        HSSFSheet sheet = workbook.createSheet(templateHead);

        Row rowHeading = sheet.createRow(0);
        for (int i = 0; i < columns.length; i++) {
            rowHeading.createCell(i).setCellValue(columns[i]);
        }

        for (int i = 0; i < columns.length; i++) {
            CellStyle stylerowHeading = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            font.setFontName(HSSFFont.FONT_ARIAL);
            font.setFontHeightInPoints((short) 11);
            font.setColor(HSSFColor.WHITE.index);
            stylerowHeading.setFont(font);
            stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            stylerowHeading.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index);
            stylerowHeading.setFillPattern(CellStyle.SOLID_FOREGROUND);
            rowHeading.getCell(i).setCellStyle(stylerowHeading);
        }

        int r = 1;
        for (Funcionario f : funcionarios) {
            Row row = sheet.createRow(r);

            Cell Nome = row.createCell(0);
            Nome.setCellValue(f.getNome());
            Cell cargo = row.createCell(1);
            cargo.setCellValue(f.getCargo());

            Cell dtAdmissao = row.createCell(2);
            dtAdmissao.setCellValue(f.getDtAdmissao());

            CellStyle styleDate = workbook.createCellStyle();
            HSSFDataFormat dfAdmissao = workbook.createDataFormat();
            styleDate.setDataFormat(dfAdmissao.getFormat("dd/mm/yyyy"));
            dtAdmissao.setCellStyle(styleDate);

            Cell area = row.createCell(3);
            area.setCellValue(f.getArea());

            Cell gestor = row.createCell(4);
            gestor.setCellValue(f.getGestor());

            try {
                Cell email = row.createCell(5);
                email.setCellValue(f.getEmail());
            } catch (NullPointerException ne) {

            }
            try {
                Cell telefone = row.createCell(6);
                telefone.setCellValue(f.getTelefone());

            } catch (NullPointerException e) {

            }
            try {
                Cell celular = row.createCell(7);
                celular.setCellValue(f.getCelular());
            } catch (NullPointerException e) {

            }

            r++;
        }

        for (int i = 0; i < columns.length; i++) {
            sheet.autoSizeColumn(i);
        }

    } catch (Exception e) {
        logger.error("Error gerate Report: " + e);
        System.out.println("Error" + e);
    }
}

From source file:br.sp.telesul.service.ExportServiceImpl.java

public void writeExcelFormacao(String templateHead, String[] columns, HSSFWorkbook workbook) {
    try {/*from   w  w  w. ja v  a  2s  .c  om*/
        List<Funcionario> funcionarios = funcionarioService.search();

        HSSFSheet sheet = workbook.createSheet(templateHead);

        Row rowHeading = sheet.createRow(0);
        for (int i = 0; i < columns.length; i++) {
            rowHeading.createCell(i).setCellValue(columns[i]);
        }
        //Estilizar o Cabealho - Stylesheet the heading
        for (int i = 0; i < columns.length; i++) {
            CellStyle stylerowHeading = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            font.setFontName(HSSFFont.FONT_ARIAL);
            font.setFontHeightInPoints((short) 11);
            font.setColor(HSSFColor.WHITE.index);
            stylerowHeading.setFont(font);
            stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            stylerowHeading.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index);
            stylerowHeading.setFillPattern(CellStyle.SOLID_FOREGROUND);
            rowHeading.getCell(i).setCellStyle(stylerowHeading);
        }
        //Preencher linhas
        int r = 1;
        for (Funcionario f : funcionarios) {

            if (!f.getFormacoes().isEmpty()) {

                for (Formacao fmc : f.getFormacoes()) {
                    if (!fmc.getInstituicao().isEmpty() || !fmc.getCurso().isEmpty()
                            || !fmc.getNivel().isEmpty()) {
                        Row row = sheet.createRow(r);

                        try {
                            Cell Nome = row.createCell(0);
                            Nome.setCellValue(f.getNome());
                        } catch (NullPointerException e) {

                        }

                        try {
                            Cell curso = row.createCell(1);
                            curso.setCellValue(fmc.getCurso());
                        } catch (NullPointerException e) {

                        }
                        try {
                            Cell instituicao = row.createCell(2);
                            instituicao.setCellValue(fmc.getInstituicao());
                        } catch (NullPointerException e) {

                        }
                        try {
                            Cell nivel = row.createCell(3);
                            nivel.setCellValue(fmc.getNivel());
                        } catch (NullPointerException e) {

                        }
                        try {
                            Cell copia = row.createCell(4);
                            copia.setCellValue(fmc.getCopiaCertificado());
                        } catch (NullPointerException e) {

                        }

                        r++;
                    }
                }

            }

        }

        for (int i = 0; i < columns.length; i++) {
            sheet.autoSizeColumn(i);
        }

    } catch (Exception e) {
        System.out.println("Error " + e);
    }
}