Example usage for org.apache.poi.ss.usermodel Row createCell

List of usage examples for org.apache.poi.ss.usermodel Row createCell

Introduction

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

Prototype

Cell createCell(int column);

Source Link

Document

Use this to create new cells within the row and return it.

Usage

From source file:com.fjn.helper.common.io.file.office.excel.ExcelUtil.java

License:Apache License

/**
 * ??java Bean ???@ExcelHeader,// w ww  .  j a v a2  s  .  c  o m
 *
 * @param sheet
 * @param clazz
 * @param fieldnames
 */
public static void addHeaderRow(Sheet sheet, int rowIndex, Class clazz, List<String> fieldnames) {
    Row row = null;
    Cell cell = null;

    // Field[] fields=clazz.getDeclaredFields();

    // Excelheader,?
    row = sheet.createRow(rowIndex);
    for (int i = 0; i < fieldnames.size(); i++) {
        Field tempfield = null;
        try {
            tempfield = clazz.getDeclaredField(fieldnames.get(i));
        } catch (Exception ex) {
            if (logger.isEnabledFor(Priority.ERROR)) {
                logger.error("??");
            }
        }

        if (tempfield != null) {
            ExcelHeader excelheader = tempfield.getAnnotation(ExcelHeader.class);
            if (excelheader != null) {
                cell = row.createCell(i);
                cell.setCellValue(excelheader.value());
            }
        } else {
            logger.warn("" + fieldnames.get(i) + "@ExcelHeader ???");
            fieldnames.remove(i);
        }
    }
}

From source file:com.fjn.helper.common.io.file.office.excel.ExcelUtil.java

License:Apache License

/**
 * ??/*from  w  ww . java2s  .  c o  m*/
 *
 * @param sheet
 * @param clazz
 *            ???java bean
 * @param fieldnames
 *            java bean???ExeclHeader
 * @param list
 *            ?
 * @return
 */
@SuppressWarnings("unused")
public static Sheet addDataToSheet(Sheet sheet, Class clazz, List<String> fieldnames, List<?> list) {
    // ?
    Row row = null;
    Cell cell = null;
    int lastRowNum = sheet.getLastRowNum();
    for (int i = 0; i < list.size(); i++) {
        row = sheet.createRow(lastRowNum + 1 + i);
        for (int j = 0; j < fieldnames.size(); j++) {
            try {
                Field field = clazz.getDeclaredField(fieldnames.get(j));
                field.setAccessible(true);
                cell = row.createCell(j);
                Class fieldType = field.getType();
                // cell.setCellType(Cell.);
                Object value = field.get(list.get(i));
                setCellValue(cell, value);

            } catch (Exception ex) {
                if (logger.isEnabledFor(Priority.ERROR)) {
                    logger.error("" + (i + 1) + "" + j + "", ex);
                }
            }
        }
    }

    return sheet;
}

From source file:com.fjn.helper.common.io.file.office.excel.ListExcelSheetEditor.java

License:Apache License

public void addTitle(String title) {
    Sheet sheet = excelSheet.getSheet();
    Row row = sheet.createRow(excelSheet.sheet.getFirstRowNum());
    Cell cell = row.createCell(0);
    /*cell.setCellType(Cell.CELL_TYPE_STRING);
    cell.setCellValue(title);*///w  w w  . j  a  va 2 s  .c  om
    setCellValue(cell, title);
}

From source file:com.fjn.helper.common.io.file.office.excel.ListExcelSheetEditor.java

License:Apache License

/**
 * //w  ww .  j  ava 2  s . c o m
 * @param rowIndex
 */
public void addHeaderRow(int rowIndex) {
    Sheet sheet = excelSheet.getSheet();
    Row row = null;
    Cell cell = null;
    row = sheet.createRow(rowIndex + 1);
    List<String> headers = excelSheet.getHeaders();
    for (int i = 0; i < headers.size(); i++) {
        cell = row.createCell(i);
        cell.setCellValue(headers.get(i));
    }
}

From source file:com.fjn.helper.common.io.file.office.excel.ListExcelSheetEditor.java

License:Apache License

@SuppressWarnings({ "unchecked", "unused", "deprecation" })
public <T> void insertItemToSheet(int rowIndex, T t) {
    if (t == null)
        return;//w w  w.j a va  2  s  .  c om
    // ?
    Row row = null;
    Cell cell = null;
    Class<T> clazz = (Class<T>) t.getClass();
    Sheet sheet = excelSheet.sheet;
    row = sheet.createRow(rowIndex);
    for (int j = 0; j < excelSheet.getFieldList().size(); j++) {
        try {
            Field field = clazz.getDeclaredField(excelSheet.getFieldList().get(j));
            field.setAccessible(true);
            cell = row.createCell(j);
            Class fieldType = field.getType();
            //   cell.setCellType(Cell.);
            Object value = field.get(t);
            setCellValue(cell, value);

        } catch (Exception ex) {
            if (logger.isEnabledFor(Priority.ERROR)) {
                logger.error("" + row.getRowNum() + "" + j + "", ex);
            }
        }
    }

}

From source file:com.fjn.helper.common.io.file.office.excel.ListExcelSheetEditor.java

License:Apache License

@SuppressWarnings({ "unused", "deprecation" })
public void addItemsToSheet() {
    // ?/* ww w .ja v a2 s .co  m*/
    Class clazz = excelSheet.getBeanClass();
    if (clazz == null) {
        return;
    }
    List<String> fieldnames = null;
    fieldnames = excelSheet.getFieldList();
    if (fieldnames == null)
        return;
    List<?> items = null;
    items = excelSheet.getDataList();
    if (items == null)
        return;
    Sheet sheet = excelSheet.sheet;
    Row row = null;
    Cell cell = null;
    int lastRowNum = sheet.getLastRowNum();
    for (int i = 0; i < items.size(); i++) {
        row = sheet.createRow(lastRowNum + 1 + i);
        for (int j = 0; j < fieldnames.size(); j++) {
            try {
                Field field = clazz.getDeclaredField(fieldnames.get(j));
                field.setAccessible(true);
                cell = row.createCell(j);
                Class fieldType = field.getType();
                //   cell.setCellType(Cell.);
                Object value = field.get(items.get(i));
                setCellValue(cell, value);

            } catch (Exception ex) {
                if (logger.isEnabledFor(Priority.ERROR)) {
                    logger.error("" + (i + 1) + "" + j + "", ex);
                }
            }
        }
    }

}

From source file:com.funtl.framework.smoke.core.commons.excel.ExportExcel.java

License:Apache License

/**
 * ?/*w  ww. jav a  2  s.  c  o  m*/
 *
 * @param row    
 * @param column ?
 * @param val    
 * @param align  ??1?23??
 * @return ?
 */
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType) {
    Cell cell = row.createCell(column);
    String cellFormatString = "@";
    try {
        if (val == null) {
            cell.setCellValue("");
        } else if (fieldType != Class.class) {
            cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
        } else {
            if (val instanceof String) {
                cell.setCellValue((String) val);
            } else if (val instanceof Integer) {
                cell.setCellValue((Integer) val);
                cellFormatString = "0";
            } else if (val instanceof Long) {
                cell.setCellValue((Long) val);
                cellFormatString = "0";
            } else if (val instanceof Double) {
                cell.setCellValue((Double) val);
                cellFormatString = "0.00";
            } else if (val instanceof Float) {
                cell.setCellValue((Float) val);
                cellFormatString = "0.00";
            } else if (val instanceof Date) {
                cell.setCellValue((Date) val);
                cellFormatString = "yyyy-MM-dd HH:mm";
            } else {
                cell.setCellValue((String) Class
                        .forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
                                "fieldtype." + val.getClass().getSimpleName() + "Type"))
                        .getMethod("setValue", Object.class).invoke(null, val));
            }
        }
        if (val != null) {
            CellStyle style = styles.get("data_column_" + column);
            if (style == null) {
                style = wb.createCellStyle();
                style.cloneStyleFrom(styles.get("data" + (align >= 1 && align <= 3 ? align : "")));
                style.setDataFormat(wb.createDataFormat().getFormat(cellFormatString));
                styles.put("data_column_" + column, style);
            }
            cell.setCellStyle(style);
        }
    } catch (Exception ex) {
        log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());
        cell.setCellValue(val.toString());
    }
    return cell;
}

From source file:com.github.autoprimer3.Primer3ResultViewController.java

License:Open Source License

private void writePrimersToExcel(final File f) throws IOException {
    final Service<Void> service = new Service<Void>() {
        @Override//  ww w.j  ava 2  s .c  o  m
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws IOException {
                    BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(f));
                    Workbook wb = new XSSFWorkbook();
                    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);
                    CreationHelper createHelper = wb.getCreationHelper();
                    Sheet listSheet = wb.createSheet();
                    Sheet detailsSheet = wb.createSheet();
                    Row row = null;
                    int rowNo = 0;
                    int sheetNo = 0;
                    wb.setSheetName(sheetNo++, "List");
                    wb.setSheetName(sheetNo++, "Details");

                    row = listSheet.createRow(rowNo++);
                    String header[] = { "Primer", "Sequence", "Product Size (bp)" };
                    for (int col = 0; col < header.length; col++) {
                        Cell cell = row.createCell(col);
                        cell.setCellValue(header[col]);
                    }

                    updateMessage("Writing primers . . .");
                    updateProgress(0, data.size() * 3);
                    int n = 0;
                    for (Primer3Result r : data) {
                        n++;
                        updateMessage("Writing primer list " + n + " . . .");
                        row = listSheet.createRow(rowNo++);
                        int col = 0;
                        Cell cell = row.createCell(col++);
                        cell.setCellValue(r.getName() + "F");
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getLeftPrimer());
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getProductSize());
                        updateProgress(n, data.size() * 3);
                        updateMessage("Writing primer list " + n + " . . .");
                        row = listSheet.createRow(rowNo++);
                        col = 0;
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getName() + "R");
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getRightPrimer());
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getProductSize());
                        n++;
                        updateProgress(n, data.size() * 3);
                    }
                    rowNo = 0;
                    row = detailsSheet.createRow(rowNo++);
                    ArrayList<String> detailsHeader = new ArrayList<>(Arrays.asList("Name", "Other IDs",
                            "Left Primer", "Right Primer", "Product Size (bp)", "Region", "in-silico PCR"));
                    if (ispcrResCol.isVisible()) {
                        detailsHeader.add("in-silico PCR Results");
                    }
                    for (int col = 0; col < detailsHeader.size(); col++) {
                        Cell cell = row.createCell(col);
                        cell.setCellValue(detailsHeader.get(col));
                    }
                    int m = 0;
                    for (Primer3Result r : data) {
                        m++;
                        updateMessage("Writing details for pair " + m + " . . .");
                        row = detailsSheet.createRow(rowNo++);
                        int col = 0;
                        Cell cell = row.createCell(col++);
                        cell.setCellValue(r.getName());
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getTranscripts());
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getLeftPrimer());
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getRightPrimer());
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getProductSize());
                        cell = row.createCell(col++);
                        cell.setCellValue(r.getRegion());
                        cell = row.createCell(col++);
                        if (r.getIsPcrUrl() != null) {
                            cell.setCellValue("isPCR");
                            org.apache.poi.ss.usermodel.Hyperlink hl = createHelper
                                    .createHyperlink(org.apache.poi.ss.usermodel.Hyperlink.LINK_URL);
                            hl.setAddress(r.getIsPcrUrl());
                            cell.setHyperlink(hl);
                            cell.setCellStyle(hlink_style);
                        } else {
                            cell.setCellValue("");
                        }
                        if (ispcrResCol.isVisible()) {
                            cell = row.createCell(col++);
                            if (r.getIsPcrResults() != null) {
                                cell.setCellValue(r.getIsPcrResults());
                            } else {
                                cell.setCellValue("");
                            }
                        }
                        updateProgress(n + m, data.size() * 3);
                    }

                    updateMessage("Wrote " + data.size() + " primer pairs to file.");
                    wb.write(bo);
                    bo.close();
                    return null;
                }
            };
        }

    };

    service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {

            Action response = Dialogs.create().title("Done").masthead("Finished writing")
                    .message("Primers successfully written to " + f.getAbsolutePath()
                            + "\n\nDo you want to open " + "this file now?")
                    .actions(Dialog.ACTION_YES, Dialog.ACTION_NO).styleClass(Dialog.STYLE_CLASS_NATIVE)
                    .showConfirm();

            if (response == Dialog.ACTION_YES) {
                try {
                    openFile(f);
                } catch (IOException ex) {
                    Action openFailed = Dialogs.create().title("Open failed")
                            .masthead("Could not open output file")
                            .message("Exception encountered when attempting to open "
                                    + "the saved file. See below:")
                            .styleClass(Dialog.STYLE_CLASS_NATIVE).showException(ex);
                }
            }
            progressBar.progressProperty().unbind();
            progressBar.setVisible(false);
            summaryLabel.textProperty().unbind();
            summaryLabel.setText(summary);
            closeButton.setDisable(false);
            closeMenuItem.setDisable(false);
            setCheckIsPcrButton();
        }
    });
    service.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            Dialogs writeCancelled = Dialogs.create().title("Writing Cancelled")
                    .masthead("Cancelled writing to file").message("User cancelled writing primers to file.")
                    .styleClass(Dialog.STYLE_CLASS_NATIVE);
            writeCancelled.showInformation();
            progressBar.progressProperty().unbind();
            progressBar.setVisible(false);
            summaryLabel.textProperty().unbind();
            summaryLabel.setText(summary);
            closeButton.setDisable(false);
            closeMenuItem.setDisable(false);
            setCheckIsPcrButton();
        }
    });
    service.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            Action writeFailed = Dialogs.create().title("Writing failed")
                    .masthead("Could not write primers to file")
                    .message("Exception encountered when attempting to write " + "primers to file. See below:")
                    .styleClass(Dialog.STYLE_CLASS_NATIVE).showException(e.getSource().getException());
            progressBar.progressProperty().unbind();
            progressBar.setVisible(false);
            summaryLabel.textProperty().unbind();
            summaryLabel.setText(summary);
            closeButton.setDisable(false);
            closeMenuItem.setDisable(false);
            setCheckIsPcrButton();
        }
    });
    progressBar.setVisible(true);
    progressBar.progressProperty().bind(service.progressProperty());
    summaryLabel.textProperty().bind(service.messageProperty());
    closeButton.setDisable(true);
    closeMenuItem.setDisable(true);
    checkIsPcrButton.setText("Cancel");
    checkIsPcrButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            service.cancel();

        }
    });
    service.start();
}

From source file:com.github.camaral.sheeco.Sheeco.java

License:Apache License

private void createCell(final CreationHelper creationHelper, final Row row, Attribute attribute) {
    if (row.getCell(attribute.getColumnIndex()) == null) {
        final Cell cell = row.createCell(attribute.getColumnIndex());
        RichTextString cellName = creationHelper.createRichTextString(attribute.getColumnName());
        cell.setCellValue(cellName);//from   w  ww .  j a  va2 s  . c o  m
    }
}

From source file:com.github.camellabs.iot.cloudlet.geofencing.service.DefaultRouteService.java

License:Apache License

@Override
public byte[] exportRoutes(String client, String format) {
    try {/*  w  w  w  .  j a va  2 s  . c  om*/
        List<List<String>> exportedRoutes = exportRoutes(client);
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("Routes report for " + client);

        for (int i = 0; i < exportedRoutes.size(); i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < exportedRoutes.get(i).size(); j++) {
                row.createCell(j).setCellValue(exportedRoutes.get(i).get(j));
            }
        }

        ByteArrayOutputStream xlsBytes = new ByteArrayOutputStream();
        workbook.write(xlsBytes);
        xlsBytes.close();
        return xlsBytes.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}