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

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

Introduction

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

Prototype

void autoSizeColumn(int column);

Source Link

Document

Adjusts the column width to fit the contents.

Usage

From source file:output.ExcelM3Upgrad.java

private void recalculate() {
    FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
        Sheet sheet = workbook.getSheetAt(sheetNum);
        for (Row r : sheet) {
            for (Cell c : r) {
                if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
                    evaluator.evaluateFormulaCell(c);
                }/*from   w  w  w .  j  a v a 2s  . c om*/
                sheet.autoSizeColumn(c.getColumnIndex());
            }
        }
    }

}

From source file:output.ExcelM3Upgrad.java

private void writeMigration() {
    Sheet sheet = workbook.getSheetAt(0);
    workbook.setSheetName(0, "Migration");
    sheet.setDisplayGridlines(false);//from  w  ww  .  j  a  va 2s  . c  o m
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    styles = createStyles(workbook);

    int rownum = beginROW;
    int cellnum = beginCOL;
    Row row = sheet.createRow(rownum++);
    for (int k = 0; k < model.getListColumn().length; k++) {
        Cell cell = row.createCell(cellnum++);
        cell.setCellValue(i18n.Language.getLabel(model.getListColumn()[k].getIdLng()));
        cell.setCellStyle(styles.get("header"));
        sheet.setColumnHidden(cell.getColumnIndex(), model.getListColumn()[k].isHidden());
        sheet.autoSizeColumn(k);
        dialStatus();
    }
    ArrayList<Integer> listHeader = new ArrayList<>();
    for (int i = 0; i < M3UpdObjModel.header.length; i++) {
        listHeader.add(M3UpdObjModel.header[i]);
    }

    String[] listLevel = i18n.Language.traduce(Ressource.listLevel)
            .toArray(new String[Ressource.listLevel.length]);

    data = model.getData();
    for (int i = 0; i < data.length; i++) {
        busyDial.setText("Alimentation de la ligne " + (i + 1) + " sur " + data.length);
        row = sheet.createRow(rownum++);
        Object[] objArr = data[i];
        cellnum = beginCOL;
        boolean first = true;
        int j = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof Date) {
                cell.setCellValue((Date) obj);
            } else if (obj instanceof Boolean) {
                if (first) {
                    first = false;
                    if ((Boolean) obj) {
                        cell.setCellValue("Oui");
                    } else {
                        cell.setCellValue("Non");
                    }
                } else {
                    if ((Boolean) obj) {
                        cell.setCellValue("OK");
                    } else {
                        cell.setCellValue("KO");
                    }
                }
            } else if (obj instanceof String) {
                cell.setCellValue((String) obj);
            } else if (obj instanceof Double) {
                cell.setCellValue((Double) obj);
            }
            if (listHeader.indexOf(218) == j) {
                try {
                    int n = Integer.parseInt(obj.toString().trim());
                    if (n == -1) {
                        cell.setCellValue("ERROR");
                    } else {
                        cell.setCellValue(listLevel[n]);
                    }
                } catch (NumberFormatException ex) {
                    cell.setCellValue("");
                }

            }

            if (j < objArr.length - 3) {
                cell.setCellStyle(styles.get("cell_b_centered_locked"));
            } else {
                cell.setCellStyle(styles.get("cell_b_centered"));
            }
            j++;
            dialStatus();
        }
        dialStatus();
    }

    dialStatus();
    busyDial.setText("Formatage du document");
    CellRangeAddressList userList = new CellRangeAddressList(beginROW + 1, beginROW + data.length,
            beginCOL + data[0].length - 1, beginCOL + data[0].length - 1);
    DataValidationConstraint userConstraint;
    DataValidation userValidation;

    if (type == 0) {
        userConstraint = DVConstraint.createExplicitListConstraint((String[]) model.getM3UserModel()
                .getListUserSelect().toArray(new String[model.getM3UserModel().getListUserSelect().size()]));
        userValidation = new HSSFDataValidation(userList, userConstraint);
    } else {
        XSSFDataValidationHelper userHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
        userConstraint = (XSSFDataValidationConstraint) userHelper
                .createExplicitListConstraint((String[]) model.getM3UserModel().getListUserSelect()
                        .toArray(new String[model.getM3UserModel().getListUserSelect().size()]));
        userValidation = (XSSFDataValidation) userHelper.createValidation(userConstraint, userList);
    }
    sheet.addValidationData(userValidation);

    CellRangeAddressList migList = new CellRangeAddressList(beginROW + 1, beginROW + data.length,
            beginCOL + data[0].length - 2, beginCOL + data[0].length - 2);
    DataValidationConstraint migConstraint;
    DataValidation migValidation;

    if (type == 0) {
        migConstraint = DVConstraint.createExplicitListConstraint(new String[] { "OK", "KO" });
        migValidation = new HSSFDataValidation(migList, migConstraint);
    } else {
        XSSFDataValidationHelper migHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
        migConstraint = (XSSFDataValidationConstraint) migHelper
                .createExplicitListConstraint(new String[] { "OK", "KO" });
        migValidation = (XSSFDataValidation) migHelper.createValidation(migConstraint, migList);
    }
    sheet.addValidationData(migValidation);

    CellRangeAddressList levelList = new CellRangeAddressList(beginROW + 1, beginROW + data.length,
            beginCOL + data[0].length - 3, beginCOL + data[0].length - 3);
    DataValidationConstraint levelConstraint;
    DataValidation levelValidation;

    ArrayList<String> listNameLevel = new ArrayList<>();
    listNameLevel.add("ERROR");
    listNameLevel.addAll(i18n.Language.traduce(Ressource.listLevel));//.toArray(new String[Ressource.listLevel.length])
    if (type == 0) {
        levelConstraint = DVConstraint
                .createExplicitListConstraint(listNameLevel.toArray(new String[listNameLevel.size()]));
        levelValidation = new HSSFDataValidation(levelList, levelConstraint);
    } else {
        XSSFDataValidationHelper levelHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
        levelConstraint = (XSSFDataValidationConstraint) levelHelper.createExplicitListConstraint(
                i18n.Language.traduce(Ressource.listLevel).toArray(new String[Ressource.listLevel.length]));
        levelValidation = (XSSFDataValidation) levelHelper.createValidation(levelConstraint, levelList);
    }
    sheet.addValidationData(levelValidation);

    int irow = beginROW;
    int icol = beginCOL + model.getListColumn().length + 2;
    row = sheet.getRow(irow);
    Cell cell = row.createCell(icol);
    sheet.addMergedRegion(new CellRangeAddress(irow, irow, icol, icol + 1));
    cell.setCellValue("Estimation de la charge");
    cell.setCellStyle(styles.get("header"));

    irow++;
    row = sheet.getRow(irow);

    int cpt = 0;
    ArrayList<String> listStringLevel = i18n.Language.traduce(Ressource.listLevel);
    for (String s : listStringLevel) {
        cell = row.createCell(icol);
        cell.setCellValue(s);
        cell.setCellStyle(styles.get("cell_b_centered_locked"));
        cell = row.createCell(icol + 1);
        cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
        String columnLetter = CellReference.convertNumToColString(listHeader.indexOf(218) + beginCOL);
        cell.setCellFormula(
                "COUNTIF(" + workbook.getSheetName(0) + "!" + columnLetter + (beginROW + 2) + ":" + columnLetter
                        + (beginROW + data.length + 1) + ",\"" + s + "\")*" + Ressource.listWeightLevel[cpt]);
        cell.setCellStyle(styles.get("cell_b_centered_locked"));
        irow++;
        row = sheet.getRow(irow);
        cpt++;
    }
    row = sheet.getRow(irow);
    cell = row.createCell(icol);
    cell.setCellValue("Total des charges");
    cell.setCellStyle(styles.get("cell_b_centered_locked"));
    cell = row.createCell(icol + 1);
    cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
    String columnLetter = CellReference.convertNumToColString(listHeader.indexOf(icol + 1));
    cell.setCellFormula("SUM(" + workbook.getSheetName(0) + "!" + columnLetter + (beginROW + 2) + ":"
            + columnLetter + (beginROW + Ressource.listLevel.length + 1) + ")");
    cell.setCellStyle(styles.get("cell_b_centered_locked"));

    for (int k = 0; k < model.getListColumn().length + 3; k++) {
        sheet.autoSizeColumn(k);
    }

    sheet.protectSheet("3kles2014");
}

From source file:packtest.ConditionalFormats.java

License:Apache License

/**
 * Multiple conditional formatting rules can apply to
 *  one cell, some combining, some beating others.
 * Done in order of the rules added to the 
 *  SheetConditionalFormatting object// w  w  w.j  a v  a 2  s .  c  o  m
 */
static void overlapping(Sheet sheet) {
    for (int i = 0; i < 40; i++) {
        int rn = i + 1;
        Row r = sheet.createRow(i);
        r.createCell(0).setCellValue("This is row " + rn + " (" + i + ")");
        String str = "";
        if (rn % 2 == 0)
            str = str + "even ";
        if (rn % 3 == 0)
            str = str + "x3 ";
        if (rn % 5 == 0)
            str = str + "x5 ";
        if (rn % 10 == 0)
            str = str + "x10 ";
        if (str.length() == 0)
            str = "nothing special...";
        r.createCell(1).setCellValue("It is " + str);
    }
    sheet.autoSizeColumn(0);
    sheet.autoSizeColumn(1);

    sheet.getRow(1).createCell(3).setCellValue("Even rows are blue");
    sheet.getRow(2).createCell(3).setCellValue("Multiples of 3 have a grey background");
    sheet.getRow(4).createCell(3).setCellValue("Multiples of 5 are bold");
    sheet.getRow(9).createCell(3).setCellValue("Multiples of 10 are red (beats even)");

    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

    // Condition 1: Row divides by 10, red (will beat #1)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),10)=0");
    FontFormatting font1 = rule1.createFontFormatting();
    font1.setFontColorIndex(IndexedColors.RED.index);

    // Condition 2: Row is even, blue
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)=0");
    FontFormatting font2 = rule2.createFontFormatting();
    font2.setFontColorIndex(IndexedColors.BLUE.index);

    // Condition 3: Row divides by 5, bold
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("MOD(ROW(),5)=0");
    FontFormatting font3 = rule3.createFontFormatting();
    font3.setFontStyle(false, true);

    // Condition 4: Row divides by 3, grey background
    ConditionalFormattingRule rule4 = sheetCF.createConditionalFormattingRule("MOD(ROW(),3)=0");
    PatternFormatting fill4 = rule4.createPatternFormatting();
    fill4.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index);
    fill4.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    // Apply
    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A1:F41") };

    sheetCF.addConditionalFormatting(regions, rule1);
    sheetCF.addConditionalFormatting(regions, rule2);
    sheetCF.addConditionalFormatting(regions, rule3);
    sheetCF.addConditionalFormatting(regions, rule4);
}

From source file:packtest.NewLinesInCells.java

License:Apache License

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

    Row row = sheet.createRow(2);//from   w  w w.  j a  v a 2s.c  o m
    Cell cell = row.createCell(2);
    cell.setCellValue("Use \n with word wrap on to create a new line");

    //to enable newlines you need set a cell styles with wrap=true
    CellStyle cs = wb.createCellStyle();
    cs.setWrapText(true);
    cell.setCellStyle(cs);

    //increase row height to accomodate two lines of text
    row.setHeightInPoints((2 * sheet.getDefaultRowHeightInPoints()));

    //adjust column width to fit the content
    sheet.autoSizeColumn(2);

    FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
    wb.write(fileOut);
    fileOut.close();
}

From source file:payrol.Documento.java

public void generarDocumento() throws IOException {
    pago.actualizarPagos();/*from  w w w  . j  a  v  a  2s  . c o m*/
    pago.asignaPropinaDiaria();
    ArrayList<Empleados> empleados = pago.getEmpleados();
    try {
        /**  pago.actualizarPagos();
         * pago.asignaPropinaDiaria();
         * ArrayList<Empleados> empleados = pago.getEmpleados();
         * 
         * System.out.println("Nombre                                    Id                   Horas trabajadas      Valor a pagar");
         * for(Empleados empleado : empleados)
         * {
         * System.out.println(empleado.toString());
         * }
         * 
         * pago.muestraPropinasDiarias();
         * System.out.println("El valor correspondiente para cada empleado es: "+pago.getPropinaPorTrabajador());
         */
        Workbook wb = new HSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
        CreationHelper createHelper = wb.getCreationHelper();
        Sheet sheet1 = wb.createSheet("Nomina");
        Row row = sheet1.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("Nombre         -");
        cell = row.createCell(1);
        cell.setCellValue("Id");
        cell = row.createCell(2);
        cell.setCellValue("Horas Trabajadas");
        cell = row.createCell(3);
        cell.setCellValue("Cantidad Pago");
        int i = 2;
        row = sheet1.createRow(1);
        for (Empleados empleado : empleados) {
            cell = row.createCell(0);
            cell.setCellValue(empleado.getNombre());
            cell = row.createCell(1);
            cell.setCellValue(empleado.getId());
            cell = row.createCell(2);
            cell.setCellValue(empleado.getHorasTrabajadas());
            cell = row.createCell(3);
            cell.setCellValue(empleado.getCantidadPago());
            row = sheet1.createRow(i);
            i++;
        }
        sheet1.autoSizeColumn(0);
        sheet1.autoSizeColumn(1);
        sheet1.autoSizeColumn(3);
        sheet1.autoSizeColumn(2);

        fileOut = new FileOutputStream("workbook.xls");
        wb.write(fileOut);
        fileOut.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Documento.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Principal.reportesLubricantes.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    //variable para comparacion

    if (tablaReporte.getRowCount() == 0) {//compara si en el JTextArea hay texto sino muestrtra un mensaje en pantalla
        JOptionPane.showMessageDialog(null, "LA TABLA ESTA VACIA", "Oops! Error", JOptionPane.ERROR_MESSAGE);
    } else {/*from   w w  w . j  a va 2s .co  m*/

        JFileChooser fileChooser = new JFileChooser();
        fileChooser
                .addChoosableFileFilter(new FileNameExtensionFilter("todos los archivos *.xls", "xls", "xls"));//filtro para ver solo archivos .edu
        int seleccion = fileChooser.showSaveDialog(null);
        try {
            if (seleccion == JFileChooser.APPROVE_OPTION) {//comprueba si ha presionado el boton de aceptar
                File JFC = fileChooser.getSelectedFile();
                String PATH = JFC.getAbsolutePath();
                //obtenemos el path del archivo a guardar
                File JFC2 = new File(PATH + ".xls");
                if (JFC.exists() | JFC2.exists()) {
                    JOptionPane.showMessageDialog(this, "el archivo ya existe guarde con otro nombre");
                } else {
                    Workbook libro = new HSSFWorkbook();

                    FileOutputStream archivo = new FileOutputStream(JFC);
                    Sheet hoja = libro.createSheet("Reporte ");

                    for (int f = 0; f < model.getRowCount() + 4; f++) {
                        /*La clase Row nos permitir crear las filas*/
                        Row fila = hoja.createRow(f);

                        /*Cada fila tendr 5 celdas de datos*/
                        for (int c = 0; c < model.getColumnCount(); c++) {
                            hoja.autoSizeColumn(c);
                            /*Creamos la celda a partir de la fila actual*/
                            Cell celda = fila.createCell(c);

                            /*Si la fila es la nmero 0, estableceremos los encabezados*/
                            if (f == 0) {
                                celda.setCellValue(model.getColumnName(c));

                            } else {
                                /*Si no es la primera fila establecemos un valor*/
                                if (f == model.getRowCount() + 1) {
                                    celda.setCellValue("");

                                } else {
                                    if (f == model.getRowCount() + 2) {
                                        if (c == model.getColumnCount() - 2) {
                                            celda.setCellValue("TOTAL");
                                        }
                                        if (c == model.getColumnCount() - 1) {
                                            celda.setCellValue(total.getText());
                                        }

                                    } else {
                                        if (model.getValueAt(f - 1, c).equals(null)) {
                                            celda.setCellValue("");
                                        } else {
                                            celda.setCellValue(model.getValueAt(f - 1, c).toString());
                                        }
                                    }
                                }
                            }
                        }
                    }

                    /*Escribimos en el libro*/
                    libro.write(archivo);
                    /*Cerramos el flujo de datos*/

                    archivo.close();
                    /*Y abrimos el archivo con la clase Desktop*/

                    if (!(PATH.endsWith(".xls"))) {
                        File temp = new File(PATH + ".xls");
                        boolean a = JFC.renameTo(temp);//renombramos el archivo
                        System.out.println("NO TERMINA");
                        System.out.println("cambiado" + a);
                    }

                    System.out.println("cmd /c start " + JFC.getPath() + ".xls");

                    try {
                        Runtime.getRuntime().exec("cmd /c start " + JFC.getPath() + ".xls");
                    } catch (IOException e) {
                        JOptionPane.showMessageDialog(null, "No se pudo abrir el archivo!", "Oops! Error",
                                JOptionPane.ERROR_MESSAGE);

                        e.printStackTrace();
                    }

                    JOptionPane.showMessageDialog(null, "Guardado exitoso!", "Guardado exitoso!",
                            JOptionPane.INFORMATION_MESSAGE);

                }

                //comprobamos si a la hora de guardar obtuvo la extension y si no se la asignamos
            }
        } catch (Exception e) {//por alguna excepcion salta un mensaje de error

            JOptionPane.showMessageDialog(null, "Error al guardar el archivo!", "Oops! Error",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    } // TODO add your handling code here:
}

From source file:ro.fortsoft.wicket.pivot.exporter.PivotXlsExporter.java

License:Apache License

private void autoSizeColumns(Sheet sheetData, int maxColNum) {
    try {/*from   w w  w  . j a  v a2 s. c  o  m*/
        // Autosize columns
        int width = 0;
        for (int col = 0; col < maxColNum; col++) {
            sheetData.autoSizeColumn(col);
            int cwidth = sheetData.getColumnWidth(col);
            cwidth += 500;
            sheetData.setColumnWidth(col, cwidth);
            width += cwidth;
        }

        // calculate zoom factor
        int nominator = 45000 * 100 / width;
        if (nominator < 100)
            sheetData.setZoom(nominator, 100);

    } catch (HeadlessException he) {
        // No UI, no autosize :(
    }
}

From source file:ru.wmbdiff.ExportIntoExcel.java

License:Apache License

public void export(File file, WMBDiffNoRootTreeTableModel model) {
    logger.info("export begin");
    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet("WMBDiff");
    int rowNum = 0;
    //Create Header
    CellStyle style;//w  w  w  .j  a  va 2 s.  c om
    Font headerFont = workbook.createFont();
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    headerFont.setColor(IndexedColors.WHITE.getIndex());
    headerFont.setFontHeightInPoints((short) 10);
    style = workbook.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.WHITE.getIndex());
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.WHITE.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.WHITE.getIndex());
    style.setBorderTop(CellStyle.BORDER_THIN);
    style.setTopBorderColor(IndexedColors.WHITE.getIndex());
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFillForegroundColor(IndexedColors.AQUA.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFont(headerFont);

    Row row = sheet.createRow(rowNum++);
    Cell cell;
    cell = row.createCell(0);
    cell.setCellValue("Result");
    cell.setCellStyle(style);
    cell = row.createCell(1);
    cell.setCellValue("Broker");
    cell.setCellStyle(style);
    cell = row.createCell(2);
    cell.setCellValue("Execution Group");
    cell.setCellStyle(style);
    cell = row.createCell(3);
    cell.setCellValue("Name");
    cell.setCellStyle(style);
    cell = row.createCell(4);
    cell.setCellValue("Type");
    cell.setCellStyle(style);
    cell = row.createCell(5);
    cell.setCellValue("Last Modification");
    cell.setCellStyle(style);
    cell = row.createCell(6);
    cell.setCellValue("Deployment Date");
    cell.setCellStyle(style);
    cell = row.createCell(7);
    cell.setCellValue("Bar File");
    cell.setCellStyle(style);
    cell = row.createCell(8);
    cell.setCellValue("Result Description");
    cell.setCellStyle(style);
    sheet.createFreezePane(0, 1);

    List<DiffExecutionGroup> dEG = model.getDiffExecutionGroupList();
    ListIterator<DiffExecutionGroup> litr = dEG.listIterator();
    while (litr.hasNext()) {
        DiffExecutionGroup element = litr.next();
        element.getDiffResultList();
        ListIterator<DiffDeployedObjectResult> litr2 = element.getDiffResultList().listIterator();
        while (litr2.hasNext()) {
            DiffDeployedObjectResult res = litr2.next();
            switch (res.getResult()) {
            case ONLY_IN_A:
                createRow(rowNum++, sheet, res.getAObject(), "A", res.getResultDesc());
                break;
            case ONLY_IN_B:
                createRow(rowNum++, sheet, res.getBObject(), "B", res.getResultDesc());
                break;
            case EQUAL:
                createRow(rowNum++, sheet, res.getAObject(), "=", res.getResultDesc());
                createRow(rowNum++, sheet, res.getBObject(), "=", res.getResultDesc());
                sheet.groupRow(rowNum - 2, rowNum - 2);
                break;
            case DIFF:
                createRow(rowNum++, sheet, res.getAObject(), "!=", res.getResultDesc());
                createRow(rowNum++, sheet, res.getBObject(), "!=", res.getResultDesc());
                sheet.groupRow(rowNum - 2, rowNum - 2);
                break;
            }
            ;

        }
        ;
    }
    ;
    //Adjust column width to fit the contents
    for (int i = 0; i < 9; i++)
        sheet.autoSizeColumn(i);
    //set Filter
    sheet.setAutoFilter(new CellRangeAddress(0, rowNum - 1, 0, 8));
    try {
        FileOutputStream out = new FileOutputStream(file);
        workbook.write(out);
        workbook.close();
        out.close();
    } catch (Exception e) {
        logger.error("export", e);
    }
    logger.info("export end");
}

From source file:se.mithlond.services.content.impl.ejb.report.ExcelReportServiceBean.java

License:Apache License

/**
 * {@inheritDoc}//w  w  w .  j a v  a2 s . co  m
 */
@Override
public Sheet createStandardExcelSheet(@NotNull final Workbook workbook, @NotNull final String sheetName,
        @NotNull final String sheetTitle, @NotNull final List<String> columnTitles) {

    // Check sanity
    Validate.notEmpty(sheetName, "sheetName");
    Validate.notEmpty(sheetTitle, "sheetTitle");
    Validate.notEmpty(columnTitles, "columnTitles");
    Validate.notNull(workbook, "workbook");

    // Create a new Workbook if required.
    final LocalDateTime timestamp = LocalDateTime.now();
    final String now = TimeFormat.YEAR_MONTH_DATE_HOURS_MINUTES.print(timestamp).replace(":", " ");

    // Create the Sheet to return
    final Sheet toReturn = workbook.createSheet(sheetName + "_" + now);
    toReturn.setFitToPage(true);
    toReturn.setHorizontallyCenter(true);

    // Create a "Title" row containing a single cell (i.e. merged cells)
    // and where the sheet title is presented and centered.
    final Row titleRow = toReturn.createRow(0);
    titleRow.setHeightInPoints(45);
    final Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue(sheetTitle + " " + now);
    titleCell.setCellStyle(getCellStyle(ExcelElement.TITLE, workbook));
    // toReturn.addMergedRegion(CellRangeAddress.valueOf("$A$1:$E$1"));
    toReturn.addMergedRegion(CellRangeAddress
            .valueOf("$A$1:$" + CellReference.convertNumToColString(columnTitles.size() - 1) + "1"));

    // Create a header Row with the column names defined above.
    final Row headerRow = toReturn.createRow(1);

    // headerRow.setHeightInPoints(40);
    // This *could* adjust the header row to fit its internal height.
    titleRow.setHeight((short) -1);

    Cell headerCell;

    for (int i = 0; i < columnTitles.size(); i++) {
        headerCell = headerRow.createCell(i);
        headerCell.setCellValue(columnTitles.get(i));
        headerCell.setCellStyle(getCellStyle(ExcelElement.HEADER, workbook));
        toReturn.setDefaultColumnStyle(i, getCellStyle(ExcelElement.NON_WRAPPING, workbook));
        toReturn.autoSizeColumn(i);
    }

    // All done
    return toReturn;
}

From source file:se.nrm.dina.dina.inventory.logic.ExcelWriter.java

public void writeCSVFile(List<Taxon> speciesList) throws IOException {
    try (Workbook workbook = new XSSFWorkbook()) {
        CreationHelper createHelper = workbook.getCreationHelper();
        Sheet sheet = workbook.createSheet("Species List");
        // Create a Row
        Row headerRow = sheet.createRow(0);
        // Creating cells
        for (int i = 0; i < columns.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(columns[i]);
        }//from   w  w  w.j a v a2 s  . c  om

        // Create Other rows and cells with employees data
        int rowNum = 1;
        for (Taxon taxon : speciesList) {
            Row row = sheet.createRow(rowNum++);

            row.createCell(0).setCellValue(taxon.getFullName());
            row.createCell(1).setCellValue(taxon.getName());
            row.createCell(2).setCellValue(taxon.getAuthor());
            row.createCell(3).setCellValue(taxon.getGuid());
            row.createCell(4).setCellValue(taxon.getRemarks());
            row.createCell(5).setCellValue(taxon.getSource());

        }

        // Resize all columns to fit the content size
        for (int i = 0; i < columns.length; i++) {
            sheet.autoSizeColumn(i);
        } // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream(EXCEL_FILE_PATH);
        workbook.write(fileOut);
        fileOut.close();
        // Closing the workbook
    }
}