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

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

Introduction

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

Prototype

CreationHelper getCreationHelper();

Source Link

Document

Returns an object that handles instantiating concrete classes of the various instances one needs for HSSF and XSSF.

Usage

From source file:org.structr.excel.ToExcelFunction.java

License:Open Source License

public Workbook writeExcel(final List list, final String propertyView, final List<String> properties,
        final boolean includeHeader, final boolean localizeHeader, final String headerLocalizationDomain,
        final Locale locale, final Integer maxCellLength, final String overflowMode) throws IOException {

    final Workbook workbook = new XSSFWorkbook();
    final CreationHelper factory = workbook.getCreationHelper();
    final XSSFSheet sheet = (XSSFSheet) workbook.createSheet();
    final Drawing drawing = sheet.createDrawingPatriarch();

    int rowCount = 0;
    int cellCount = 0;

    XSSFRow currentRow = null;//from  ww w . ja  v  a 2 s.  c o  m
    XSSFCell cell = null;

    if (includeHeader) {

        currentRow = (XSSFRow) sheet.createRow(rowCount++);
        cellCount = 0;

        if (propertyView != null) {

            final Object obj = list.get(0);

            if (obj instanceof GraphObject) {

                for (PropertyKey key : ((GraphObject) obj).getPropertyKeys(propertyView)) {

                    cell = (XSSFCell) currentRow.createCell(cellCount++);

                    String value = key.dbName();
                    if (localizeHeader) {
                        try {
                            value = LocalizeFunction.getLocalization(locale, value, headerLocalizationDomain);
                        } catch (FrameworkException fex) {
                            logger.warn("to_excel(): Exception", fex);
                        }
                    }

                    cell.setCellValue(value);
                }

            } else {
                cell = (XSSFCell) currentRow.createCell(cellCount++);
                cell.setCellValue(
                        "Error: Object is not of type GraphObject, can not determine properties of view for header row");
            }

        } else if (properties != null) {

            for (final String colName : properties) {

                cell = (XSSFCell) currentRow.createCell(cellCount++);
                String value = colName;
                if (localizeHeader) {
                    try {
                        value = LocalizeFunction.getLocalization(locale, value, headerLocalizationDomain);
                    } catch (FrameworkException fex) {
                        logger.warn("to_excel(): Exception", fex);
                    }
                }

                cell.setCellValue(value);
            }
        }
    }

    for (final Object obj : list) {

        currentRow = (XSSFRow) sheet.createRow(rowCount++);
        cellCount = 0;

        if (propertyView != null) {

            if (obj instanceof GraphObject) {

                for (PropertyKey key : ((GraphObject) obj).getPropertyKeys(propertyView)) {

                    final Object value = ((GraphObject) obj).getProperty(key);

                    cell = (XSSFCell) currentRow.createCell(cellCount++);

                    writeToCell(factory, drawing, cell, value, maxCellLength, overflowMode);
                }

            } else {
                cell = (XSSFCell) currentRow.createCell(cellCount++);
                cell.setCellValue(
                        "Error: Object is not of type GraphObject, can not determine properties of object");
            }

        } else if (properties != null) {

            if (obj instanceof GraphObject) {

                final GraphObject castedObj = (GraphObject) obj;

                for (final String colName : properties) {
                    final PropertyKey key = StructrApp.key(obj.getClass(), colName);
                    final Object value = castedObj.getProperty(key);
                    cell = (XSSFCell) currentRow.createCell(cellCount++);

                    writeToCell(factory, drawing, cell, value, maxCellLength, overflowMode);
                }

            } else if (obj instanceof Map) {

                final Map castedObj = (Map) obj;

                for (final String colName : properties) {
                    final Object value = castedObj.get(colName);
                    cell = (XSSFCell) currentRow.createCell(cellCount++);

                    writeToCell(factory, drawing, cell, value, maxCellLength, overflowMode);
                }
            }
        }
    }

    return workbook;
}

From source file:org.talend.dataprep.schema.xls.serialization.XlsRunnable.java

License:Open Source License

private void serializeColumns(Workbook workbook, JsonGenerator generator, Sheet sheet,
        List<ColumnMetadata> columns) throws IOException {

    for (int i = 0, size = sheet.getLastRowNum(); i <= size; i++) {
        if (limit > 0 && i > limit) {
            break;
        }/*from w  w w . j a  v a2 s. c  o m*/
        // is header line?
        Row row = sheet.getRow(i);
        if (isHeaderLine(i, columns) || row == null) {
            continue;
        }

        generator.writeStartObject();
        for (ColumnMetadata columnMetadata : columns) {

            // do not write the values if this has been detected as an header
            if (i < columnMetadata.getHeaderSize()) {
                continue;
            }

            int colId = Integer.parseInt(columnMetadata.getId());
            String cellValue = getCellValueAsString(row.getCell(colId),
                    workbook.getCreationHelper().createFormulaEvaluator());
            LOG.trace("cellValue for {}/{}: {}", i, colId, cellValue);
            generator.writeFieldName(columnMetadata.getId());
            if (cellValue != null) {
                generator.writeString(cellValue);
            } else {
                generator.writeNull();
            }
        }
        generator.writeEndObject();
    }
}

From source file:org.talend.dataprep.schema.xls.XlsSchemaParser.java

License:Open Source License

/**
 * Parse all xls sheets for old excel document type
 *
 * @param request the xls request./*ww w. j a  v  a 2s . c  o  m*/
 * @return The parsed sheets request.
 */
private List<Schema.SheetContent> parseAllSheetsOldFormat(Request request) {

    final Marker marker = Markers.dataset(request.getMetadata().getId());

    try {
        InputStream inputStream = request.getContent();
        if (!inputStream.markSupported()) {
            inputStream = new PushbackInputStream(inputStream, 8);
        }
        Workbook hssfWorkbook = WorkbookFactory.create(inputStream);

        List<Schema.SheetContent> schemas;
        try {
            if (hssfWorkbook == null) {
                throw new IOException("could not open " + request.getMetadata().getId() + " as an excel file");
            }
            int sheetNumber = hssfWorkbook.getNumberOfSheets();
            if (sheetNumber < 1) {
                LOGGER.debug(marker, "has not sheet to read");
                return Collections.emptyList();
            }
            schemas = new ArrayList<>();
            for (int i = 0; i < sheetNumber; i++) {
                Sheet sheet = hssfWorkbook.getSheetAt(i);
                if (sheet.getLastRowNum() < 1) {
                    LOGGER.debug(marker, "sheet '{}' do not have rows skip ip", sheet.getSheetName());
                    continue;
                }
                List<ColumnMetadata> columnsMetadata = parsePerSheet(sheet, //
                        request.getMetadata().getId(), //
                        hssfWorkbook.getCreationHelper().createFormulaEvaluator());
                String sheetName = sheet.getSheetName();
                // update XlsSerializer if this default sheet naming change!!!
                schemas.add(
                        new Schema.SheetContent(sheetName == null ? "sheet-" + i : sheetName, columnsMetadata));
            }
        } finally {
            hssfWorkbook.close();
        }
        return schemas;
    } catch (Exception e) {
        LOGGER.debug(marker, "Exception during parsing xls request :" + e.getMessage(), e);
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}

From source file:org.waterforpeople.mapping.dataexport.GraphicalSurveySummaryExporter.java

License:Open Source License

/**
 * Writes the report as an XLS document/*from   w  w w .j a v  a2  s.  c o m*/
 */
private void writeSummaryReport(Map<QuestionGroupDto, List<QuestionDto>> questionMap, SummaryModel summaryModel,
        String sector, Workbook wb) throws Exception {
    String title = sector == null ? SUMMARY_LABEL.get(locale) : sector;
    Sheet sheet = null;
    int sheetCount = 2;
    String curTitle = WorkbookUtil.createSafeSheetName(title);
    while (sheet == null) {
        sheet = wb.getSheet(curTitle);
        if (sheet == null) {
            sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(curTitle));
        } else {
            sheet = null;
            curTitle = title + " " + sheetCount;
            sheetCount++;
        }
    }
    CreationHelper creationHelper = wb.getCreationHelper();
    Drawing patriarch = sheet.createDrawingPatriarch();
    int curRow = 0;
    Row row = getRow(curRow++, sheet);
    if (sector == null) {
        createCell(row, 0, REPORT_HEADER.get(locale), headerStyle);
    } else {
        createCell(row, 0, sector + " " + REPORT_HEADER.get(locale), headerStyle);
    }
    for (QuestionGroupDto group : orderedGroupList) {
        if (questionMap.get(group) != null) {
            for (QuestionDto question : questionMap.get(group)) {
                if (!(QuestionType.OPTION == question.getType() || QuestionType.NUMBER == question.getType())) {
                    continue;
                } else {
                    if (summaryModel.getResponseCountsForQuestion(question.getKeyId(), sector).size() == 0) {
                        // if there is no data, skip the question
                        continue;
                    }
                }
                // for both options and numeric, we want a pie chart and
                // data table for numeric, we also want descriptive
                // statistics
                int tableTopRow = curRow++;
                int tableBottomRow = curRow;
                row = getRow(tableTopRow, sheet);
                // span the question heading over the data table
                sheet.addMergedRegion(new CellRangeAddress(curRow - 1, curRow - 1, 0, 2));
                createCell(row, 0, getLocalizedText(question.getText(), question.getTranslationMap()),
                        headerStyle);
                DescriptiveStats stats = summaryModel.getDescriptiveStatsForQuestion(question.getKeyId(),
                        sector);
                if (stats != null && stats.getSampleCount() > 0) {
                    sheet.addMergedRegion(new CellRangeAddress(curRow - 1, curRow - 1, 4, 5));
                    createCell(row, 4, getLocalizedText(question.getText(), question.getTranslationMap()),
                            headerStyle);
                }
                row = getRow(curRow++, sheet);
                createCell(row, 1, FREQ_LABEL.get(locale), headerStyle);
                createCell(row, 2, PCT_LABEL.get(locale), headerStyle);

                // now create the data table for the option count
                Map<String, Long> counts = summaryModel.getResponseCountsForQuestion(question.getKeyId(),
                        sector);
                int sampleTotal = 0;
                List<String> labels = new ArrayList<String>();
                List<String> values = new ArrayList<String>();
                int firstOptRow = curRow;
                for (Entry<String, Long> count : counts.entrySet()) {
                    row = getRow(curRow++, sheet);
                    String labelText = count.getKey();
                    if (labelText == null) {
                        labelText = "";
                    }
                    StringBuilder builder = new StringBuilder();
                    if (QuestionType.OPTION == question.getType() && !DEFAULT_LOCALE.equals(locale)) {
                        String[] tokens = labelText.split("\\|");
                        // see if we have a translation for this option
                        for (int i = 0; i < tokens.length; i++) {
                            if (i > 0) {
                                builder.append("|");
                            }
                            if (question.getOptionContainerDto() != null
                                    && question.getOptionContainerDto().getOptionsList() != null) {
                                boolean found = false;
                                for (QuestionOptionDto opt : question.getOptionContainerDto()
                                        .getOptionsList()) {
                                    if (opt.getText() != null
                                            && opt.getText().trim().equalsIgnoreCase(tokens[i])) {
                                        builder.append(getLocalizedText(tokens[i], opt.getTranslationMap()));
                                        found = true;
                                        break;
                                    }
                                }
                                if (!found) {
                                    builder.append(tokens[i]);
                                }
                            }
                        }
                    } else {
                        builder.append(labelText);
                    }
                    createCell(row, 0, builder.toString(), null);
                    createCell(row, 1, count.getValue().toString(), null);

                    labels.add(builder.toString());
                    values.add(count.getValue().toString());
                    sampleTotal += count.getValue();
                }
                row = getRow(curRow++, sheet);
                createCell(row, 0, TOTAL_LABEL.get(locale), null);
                createCell(row, 1, sampleTotal + "", null);
                for (int i = 0; i < values.size(); i++) {
                    row = getRow(firstOptRow + i, sheet);
                    if (sampleTotal > 0) {
                        createCell(row, 2, PCT_FMT.format((Double.parseDouble(values.get(i)) / sampleTotal)),
                                null);
                    } else {
                        createCell(row, 2, PCT_FMT.format(0), null);
                    }
                }

                tableBottomRow = curRow;

                if (stats != null && stats.getSampleCount() > 0) {
                    int tempRow = tableTopRow + 1;
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, "N", null);
                    createCell(row, 5, sampleTotal + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MEAN_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMean() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, STD_E_LABEL.get(locale), null);
                    createCell(row, 5, stats.getStandardError() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MEDIAN_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMedian() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MODE_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMode() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, STD_D_LABEL.get(locale), null);
                    createCell(row, 5, stats.getStandardDeviation() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, VAR_LABEL.get(locale), null);
                    createCell(row, 5, stats.getVariance() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, RANGE_LABEL.get(locale), null);
                    createCell(row, 5, stats.getRange() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MIN_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMin() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MAX_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMax() + "", null);
                    if (tableBottomRow < tempRow) {
                        tableBottomRow = tempRow;
                    }
                }
                curRow = tableBottomRow;
                if (labels.size() > 0) {
                    boolean hasVals = false;
                    if (values != null) {
                        for (String val : values) {
                            try {
                                if (val != null && new Double(val.trim()) > 0D) {
                                    hasVals = true;
                                    break;
                                }
                            } catch (Exception e) {
                                // no-op
                            }
                        }
                    }
                    // only insert the image if we have at least 1 non-zero
                    // value
                    if (hasVals && generateCharts) {
                        // now insert the graph
                        int indx = wb.addPicture(JFreechartChartUtil.getPieChart(labels, values,
                                getLocalizedText(question.getText(), question.getTranslationMap()), CHART_WIDTH,
                                CHART_HEIGHT), Workbook.PICTURE_TYPE_PNG);
                        ClientAnchor anchor = creationHelper.createClientAnchor();
                        anchor.setDx1(0);
                        anchor.setDy1(0);
                        anchor.setDx2(0);
                        anchor.setDy2(255);
                        anchor.setCol1(6);
                        anchor.setRow1(tableTopRow);
                        anchor.setCol2(6 + CHART_CELL_WIDTH);
                        anchor.setRow2(tableTopRow + CHART_CELL_HEIGHT);
                        anchor.setAnchorType(2);
                        patriarch.createPicture(anchor, indx);
                        if (tableTopRow + CHART_CELL_HEIGHT > tableBottomRow) {
                            curRow = tableTopRow + CHART_CELL_HEIGHT;
                        }
                    }
                }

                // add a blank row between questions
                getRow(curRow++, sheet);
                // flush the sheet so far to disk; we will not go back up
                ((SXSSFSheet) sheet).flushRows(0); // retain 0 last rows and
                // flush all others

            }
        }
    }
}

From source file:org.zafritech.zidingorms.io.excel.ExcelFunctions.java

private static Map<String, CellStyle> createStyles(Workbook wb) {

    Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
    CreationHelper creationHelper = wb.getCreationHelper();

    CellStyle style;/*from  ww w  .j a v a2s  . c  om*/

    // Header Font
    Font headerFont = wb.createFont();
    headerFont.setFontHeightInPoints((short) 12);
    headerFont.setBold(true);
    headerFont.setColor(IndexedColors.WHITE.getIndex());

    // Header Left Aligned Style
    style = createBorderedStyle(wb);
    style.setAlignment(HorizontalAlignment.LEFT);
    style.setVerticalAlignment(VerticalAlignment.CENTER);
    style.setFont(headerFont);
    style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles.put("HeaderLeftAlign", style);

    // Header Center Aligned Style
    style = createBorderedStyle(wb);
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.CENTER);
    style.setFont(headerFont);
    style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles.put("HeaderCenterAlign", style);

    // Body Left Aligned Style
    style = createBorderedStyle(wb);
    style.setAlignment(HorizontalAlignment.LEFT);
    style.setVerticalAlignment(VerticalAlignment.TOP);
    styles.put("BodyLeftAlign", style);

    // Body Center Aligned Style
    style = createBorderedStyle(wb);
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.TOP);
    styles.put("BodyCenterAlign", style);

    // Body Left Aligned WrapText Style
    style = createBorderedStyle(wb);
    style.setAlignment(HorizontalAlignment.LEFT);
    style.setVerticalAlignment(VerticalAlignment.TOP);
    style.setWrapText(true);
    styles.put("BodyLeftAlignWrapText", style);

    // Body Left Aligned Date Format Style
    style = createBorderedStyle(wb);
    style.setAlignment(HorizontalAlignment.LEFT);
    style.setVerticalAlignment(VerticalAlignment.TOP);
    style.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
    styles.put("BodyLeftAlignDate", style);

    // Body Center Aligned Date Format Style
    style = createBorderedStyle(wb);
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.TOP);
    style.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
    styles.put("BodyCenterAlignDate", style);

    return styles;
}

From source file:packtest.CellComments.java

License:Apache License

public static void main(String[] args) throws IOException {
    Workbook wb = new XSSFWorkbook();

    CreationHelper factory = wb.getCreationHelper();

    Sheet sheet = wb.createSheet();//from  w ww  .ja  v  a 2 s.  c  o m

    Cell cell1 = sheet.createRow(3).createCell(5);
    cell1.setCellValue("F4");

    Drawing drawing = sheet.createDrawingPatriarch();

    ClientAnchor anchor = factory.createClientAnchor();

    Comment comment1 = drawing.createCellComment(anchor);
    RichTextString str1 = factory.createRichTextString("Hello, World!");
    comment1.setString(str1);
    comment1.setAuthor("Apache POI");
    cell1.setCellComment(comment1);

    Cell cell2 = sheet.createRow(2).createCell(2);
    cell2.setCellValue("C3");

    Comment comment2 = drawing.createCellComment(anchor);
    RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
    //apply custom font to the text in the comment
    Font font = wb.createFont();
    font.setFontName("Arial");
    font.setFontHeightInPoints((short) 14);
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setColor(IndexedColors.RED.getIndex());
    str2.applyFont(font);

    comment2.setString(str2);
    comment2.setAuthor("Apache POI");
    //        comment2.setAddress(new CellAddress("C3"));

    String fname = "comments.xlsx";
    FileOutputStream out = new FileOutputStream(fname);
    wb.write(out);
    out.close();

    wb.close();
}

From source file:packtest.CreateCell.java

License:Apache License

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

    // Create a row and put some cells in it. Rows are 0 based.
    Row row = sheet.createRow((short) 0);
    // Create a cell and put a value in it.
    Cell cell = row.createCell((short) 0);
    cell.setCellValue(1);//from w w w. j a v  a 2 s .c  om

    //numeric value
    row.createCell(1).setCellValue(1.2);

    //plain string value
    row.createCell(2).setCellValue("This is a string cell");

    //rich text string
    RichTextString str = creationHelper.createRichTextString("Apache");
    Font font = wb.createFont();
    font.setItalic(true);
    font.setUnderline(Font.U_SINGLE);
    str.applyFont(font);
    row.createCell(3).setCellValue(str);

    //boolean value
    row.createCell(4).setCellValue(true);

    //formula
    row.createCell(5).setCellFormula("SUM(A1:B1)");

    //date
    CellStyle style = wb.createCellStyle();
    style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
    cell = row.createCell(6);
    cell.setCellValue(new Date());
    cell.setCellStyle(style);

    //hyperlink
    row.createCell(7).setCellFormula("SUM(A1:B1)");
    cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")");

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

From source file:packtest.HyperlinkExample.java

License:Apache License

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

    //cell style for hyperlinks
    //by default hyperlinks are blue and underlined
    CellStyle hlink_style = wb.createCellStyle();
    Font hlink_font = wb.createFont();
    hlink_font.setUnderline(Font.U_SINGLE);
    hlink_font.setColor(IndexedColors.BLUE.getIndex());
    hlink_style.setFont(hlink_font);//  w  w  w. j a v a  2 s. c o  m

    Cell cell;
    Sheet sheet = wb.createSheet("Hyperlinks");
    //URL
    cell = sheet.createRow(0).createCell((short) 0);
    cell.setCellValue("URL Link");

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

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

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

    //link to a place in this workbook

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

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

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

}

From source file:packtest.WorkingWithPictures.java

License:Apache License

public static void main(String[] args) throws IOException {

    //create a new workbook
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    try {/*from  w  w w  .  ja  v  a2  s.com*/
        CreationHelper helper = wb.getCreationHelper();

        //add a picture in this workbook.
        InputStream is = new FileInputStream(args[0]);
        byte[] bytes = IOUtils.toByteArray(is);
        is.close();
        int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);

        //create sheet
        Sheet sheet = wb.createSheet();

        //create drawing
        Drawing drawing = sheet.createDrawingPatriarch();

        //add a picture shape
        ClientAnchor anchor = helper.createClientAnchor();
        anchor.setCol1(1);
        anchor.setRow1(1);
        Picture pict = drawing.createPicture(anchor, pictureIdx);

        //auto-size picture
        pict.resize(2);

        //save workbook
        String file = "picture.xls";
        if (wb instanceof XSSFWorkbook)
            file += "x"; // NOSONAR
        OutputStream fileOut = new FileOutputStream(file);
        try {
            wb.write(fileOut);
        } finally {
            fileOut.close();
        }
    } finally {
        wb.close();
    }
}

From source file:payrol.Documento.java

public void generarDocumento() throws IOException {
    pago.actualizarPagos();/*from   w ww  .j a  v a 2s .c om*/
    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);
    }

}