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

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

Introduction

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

Prototype

short getLastCellNum();

Source Link

Document

Gets the index of the last cell contained in this row PLUS ONE.

Usage

From source file:com.cpjd.roblu.csv.ToCSV.java

License:Apache License

/**
 * Called to convert a row of cells into a line of data that can later be
 * output to the CSV file.// www . j  a va  2s .  co m
 *
 * @param row An instance of either the HSSFRow or XSSFRow classes that
 *            encapsulates information about a row of cells recovered from
 *            an Excel workbook.
 */
private void rowToCSV(Row row) {
    Cell cell;
    int lastCellNum;
    ArrayList<String> csvLine = new ArrayList<>();

    // Check to ensure that a row was recovered from the sheet as it is
    // possible that one or more rows between other populated rows could be
    // missing - blank. If the row does contain cells then...
    if (row != null) {

        // Get the index for the right most cell on the row and then
        // step along the row from left to right recovering the contents
        // of each cell, converting that into a formatted String and
        // then storing the String into the csvLine ArrayList.
        lastCellNum = row.getLastCellNum();
        for (int i = 0; i <= lastCellNum; i++) {
            cell = row.getCell(i);
            if (cell == null) {
                csvLine.add("");
            } else {
                if (cell.getCellType() != 2) {
                    csvLine.add(this.formatter.formatCellValue(cell));
                } else {
                    csvLine.add(this.formatter.formatCellValue(cell, this.evaluator));
                }
            }
        }
        // Make a note of the index number of the right most cell. This value
        // will later be used to ensure that the matrix of data in the CSV file
        // is square.
        if (lastCellNum > this.maxRowWidth) {
            this.maxRowWidth = lastCellNum;
        }
    }
    this.csvData.add(csvLine);
}

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {

    wb = new XSSFWorkbook();
    String safeName = WorkbookUtil.createSafeSheetName(filename);
    Sheet sheet = wb.createSheet(safeName);

    cellStyle = wb.createCellStyle();/*from w  w w.  j  a  v a  2 s  . c o m*/
    facetStyle = wb.createCellStyle();
    titleStyle = wb.createCellStyle();
    createCustomFonts();

    int maxColumns = 0;
    StringTokenizer st = new StringTokenizer(tableId, ",");
    while (st.hasMoreElements()) {
        String tableName = (String) st.nextElement();
        UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                tableName);
        if (component == null) {
            throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
        }
        if (!(component instanceof DataTable || component instanceof DataList)) {
            throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                    + "\", exporter must target a PrimeFaces DataTable/DataList.");
        }

        DataList list = null;
        DataTable table = null;
        int cols = 0;
        if (preProcessor != null) {
            preProcessor.invoke(context.getELContext(), new Object[] { wb });
        }
        if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {
            Row titleRow = sheet.createRow(sheet.getLastRowNum());
            int cellIndex = titleRow.getLastCellNum() == -1 ? 0 : titleRow.getLastCellNum();
            Cell cell = titleRow.createCell(cellIndex);
            cell.setCellValue(new XSSFRichTextString(tableTitle));
            Font titleFont = wb.createFont();
            titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
            titleStyle.setFont(titleFont);
            cell.setCellStyle(titleStyle);
            sheet.createRow(sheet.getLastRowNum() + 3);

        }
        if (component instanceof DataList) {
            list = (DataList) component;

            if (list.getHeader() != null) {
                tableFacet(context, sheet, list, "header");
            }
            if (pageOnly) {
                exportPageOnly(context, list, sheet);
            } else {
                exportAll(context, list, sheet);
            }
            cols = list.getRowCount();
        } else {

            table = (DataTable) component;
            int columnsCount = getColumnsCount(table);

            if (table.getHeader() != null && !subTable) {
                tableFacet(context, sheet, table, columnsCount, "header");

            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "header");
            }

            addColumnFacets(table, sheet, ColumnType.HEADER);

            if (pageOnly) {
                exportPageOnly(context, table, sheet);
            } else if (selectionOnly) {
                exportSelectionOnly(context, table, sheet);
            } else {
                exportAll(context, table, sheet, subTable);
            }

            if (table.hasFooterColumn() && !subTable) {
                addColumnFacets(table, sheet, ColumnType.FOOTER);
            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "footer");
            }
            table.setRowIndex(-1);
            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { wb });
            }
            cols = table.getColumnsCount();

            if (maxColumns < cols) {
                maxColumns = cols;
            }
        }
        sheet.createRow(sheet.getLastRowNum() + Integer.parseInt(datasetPadding));
    }

    if (!subTable)
        for (int i = 0; i < maxColumns; i++) {
            sheet.autoSizeColumn((short) i);
        }

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE);
    sheet.setPrintGridlines(true);

    writeExcelToResponse(context.getExternalContext(), wb, filename);

}

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

protected void exportCells(DataList list, Sheet sheet) {
    int sheetRowIndex = sheet.getLastRowNum() + 1;
    Row row = sheet.createRow(sheetRowIndex);

    for (UIComponent component : list.getChildren()) {
        if (component instanceof Column) {
            UIColumn column = (UIColumn) component;
            for (UIComponent childComponent : column.getChildren()) {
                int cellIndex = row.getLastCellNum() == -1 ? 0 : row.getLastCellNum();
                Cell cell = row.createCell(cellIndex);
                if (component.isRendered()) {
                    String value = component == null ? ""
                            : exportValue(FacesContext.getCurrentInstance(), childComponent);
                    cell.setCellValue(new XSSFRichTextString(value));
                    cell.setCellStyle(cellStyle);
                }/* www  .j  a  v  a  2  s .  c o m*/
            }

        } else {
            int cellIndex = row.getLastCellNum() == -1 ? 0 : row.getLastCellNum();
            Cell cell = row.createCell(cellIndex);
            if (component.isRendered()) {
                String value = component == null ? ""
                        : exportValue(FacesContext.getCurrentInstance(), component);
                cell.setCellValue(new XSSFRichTextString(value));
                cell.setCellStyle(cellStyle);
            }
        }
    }

}

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

protected void addColumnValue(Row row, UIComponent component, String type) {
    int cellIndex = row.getLastCellNum() == -1 ? 0 : row.getLastCellNum();
    Cell cell = row.createCell(cellIndex);
    String value = component == null ? "" : exportValue(FacesContext.getCurrentInstance(), component);
    cell.setCellValue(new XSSFRichTextString(value));
    if (type.equalsIgnoreCase("facet")) {
        // addColumnAlignments(component,facetStyle);
        cell.setCellStyle(facetStyle);//from  w ww . java 2  s  .  c o  m
    } else {
        CellStyle cellStyle = this.cellStyle;
        cellStyle = addColumnAlignments(component, cellStyle);
        cell.setCellStyle(cellStyle);
    }

}

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

protected void addColumnValue(Row row, List<UIComponent> components, String type) {
    int cellIndex = row.getLastCellNum() == -1 ? 0 : row.getLastCellNum();
    Cell cell = row.createCell(cellIndex);
    StringBuilder builder = new StringBuilder();
    FacesContext context = FacesContext.getCurrentInstance();

    for (UIComponent component : components) {
        if (component.isRendered()) {
            String value = exportValue(context, component);

            if (value != null) {
                builder.append(value);//from   w w w  .ja  v  a 2  s . c  o m
            }
        }
    }

    cell.setCellValue(new XSSFRichTextString(builder.toString()));

    if (type.equalsIgnoreCase("facet")) {
        //addColumnAlignments(components,facetStyle);
        cell.setCellStyle(facetStyle);
    } else {
        CellStyle cellStyle = this.cellStyle;
        for (UIComponent component : components) {
            cellStyle = addColumnAlignments(component, cellStyle);
            cell.setCellStyle(cellStyle);
        }
    }

}

From source file:com.dataart.spreadsheetanalytics.engine.ConverterUtils.java

License:Apache License

/**
 * Gets an instance of a Workbook ({@link ConverterUtils#newWorkbook(InputStream)}, creates copy of original file, 
 * clears all the cell values, but preserves formatting.
 *//*from  w ww. j  a va  2s  .  co  m*/
static Workbook clearContent(final Workbook book) {
    ByteArrayOutputStream originalOut = new ByteArrayOutputStream();

    try {
        book.write(originalOut);
    } catch (IOException e) {
        throw new CalculationEngineException(e);
    }

    InputStream originalIn = new ByteArrayInputStream(copyOf(originalOut.toByteArray(), originalOut.size()));

    Workbook w = ConverterUtils.newWorkbook(originalIn);
    Sheet s = w.getSheetAt(0); //TODO: only one sheet is supported

    for (int i = s.getFirstRowNum(); i <= s.getLastRowNum(); i++) {
        Row r = s.getRow(i);
        if (r == null) {
            continue;
        }

        for (int j = r.getFirstCellNum(); j <= r.getLastCellNum(); j++) {
            Cell c = r.getCell(j);
            if (c == null) {
                continue;
            }

            c.setCellType(CELL_TYPE_BLANK);
        }
    }

    return w;
}

From source file:com.dataart.spreadsheetanalytics.engine.DataModelConverters.java

License:Apache License

/**
 * For given {@link Workbook} does convert everything to new {@link DataModel} structure.
 * Does copy all supported fields (for supported fields see {@link DataModel} class.
 *///from   ww  w .j  ava  2 s  .c o  m
static IDataModel toDataModel(final Workbook workbook) {
    if (workbook == null) {
        return null;
    }

    //add custom functions information
    workbook.addToolPack(getUdfFinder());

    Sheet s = workbook.getSheetAt(0); //TODO: only one sheet is supported
    if (s == null) {
        return null;
    }

    IDataModel dm = new DataModel(s.getSheetName());

    for (int i = s.getFirstRowNum(); i <= s.getLastRowNum(); i++) {
        Row r = s.getRow(i);
        if (r == null) {
            continue;
        }

        DmRow row = new DmRow(i);
        dm.setRow(i, row);

        for (int j = r.getFirstCellNum(); j < r.getLastCellNum(); j++) {
            Cell c = r.getCell(j);
            if (c == null) {
                continue;
            }

            DmCell cell = new DmCell();
            row.setCell(j, cell);

            cell.setAddress(new CellAddress(dm.getDataModelId(), A1Address.fromRowColumn(i, j)));
            cell.setContent(ConverterUtils.resolveCellValue(c));
        }
    }

    EvaluationWorkbook evaluationWbook = ConverterUtils.newEvaluationWorkbook(workbook);

    for (int nIdx = 0; nIdx < workbook.getNumberOfNames(); nIdx++) {
        Name name = workbook.getNameAt(nIdx);

        String reference = name.getRefersToFormula();
        if (reference == null) {
            continue;
        }

        if (A1Address.isAddress(removeSheetFromNameRef(reference))) {
            dm.setNamedAddress(name.getNameName(), A1Address.fromA1Address(removeSheetFromNameRef(reference)));
        } else if (isFormula(reference, evaluationWbook)) {
            dm.setNamedValue(name.getNameName(), new CellValue(FORMULA_PREFIX + reference));
        } else {
            dm.setNamedValue(name.getNameName(), CellValue.from(reference));
        }
    }

    return dm;
}

From source file:com.dataart.spreadsheetanalytics.engine.DataSetConverters.java

License:Apache License

/**
 * Converts a {@link Workbook} to new {@link IDataSet}.
 * Ignores empty rows./*from w  w  w.jav a2  s. com*/
 * 
 * @throws {@link CalculationEngineException} if {@link Workbook} contains formulas or Cell references.
 */
static IDataSet toDataSet(final Workbook workbook) {
    Sheet sheet = workbook.getSheetAt(0); //TODO: this works only for single sheet documents
    DataSet dataSet = new DataSet(sheet.getSheetName());

    for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
        IDsRow dsRow = dataSet.addRow();
        Row row = sheet.getRow(i);
        for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
            Cell wbCell = row.getCell(j);
            if (wbCell != null && wbCell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                throw new CalculationEngineException("DataSet should not contain formulas");
            }
            IDsCell cell = dsRow.addCell();
            cell.setValue(ConverterUtils.resolveCellValue(wbCell));
        }
    }
    return dataSet;
}

From source file:com.dataart.spreadsheetanalytics.engine.PoiWorkbookConverters.java

License:Apache License

private PoiProxySheet makeSheet(Workbook wb, FormulaParsingWorkbook ewb) {
    Sheet wbSheet = wb.getSheetAt(0);/*  w  ww .  j a va2 s . c  o m*/
    PoiProxySheet sheet = new PoiProxySheet(wbSheet.getSheetName());

    for (int r = 0; r <= wbSheet.getLastRowNum(); r++) {
        Row wbSheetRow = wbSheet.getRow(r);
        if (wbSheetRow == null) {
            continue;
        }

        for (int c = 0; c <= wbSheetRow.getLastCellNum(); c++) {
            Cell wbSheetRowCell = wbSheetRow.getCell(c);
            if (wbSheetRowCell == null) {
                continue;
            }

            final Ptg[] tokens = CELL_TYPE_FORMULA == wbSheetRowCell.getCellType()
                    ? FormulaParser.parse(wbSheetRowCell.getCellFormula(), ewb, FormulaType.CELL, 0)
                    : null;
            sheet.setCell(PoiProxyCell.makeCell(sheet, wbSheetRowCell, tokens));
        }
    }

    return sheet;
}

From source file:com.dituiba.excel.ExcelUtility.java

License:Apache License

public static void copyRows(Sheet st, int startRow, int endRow, int pPosition) {
    int pStartRow = startRow;
    int pEndRow = endRow;
    int targetRowFrom;
    int targetRowTo;
    int columnCount;
    CellRangeAddress region = null;/*  ww  w .  j a  v a  2  s. c  o m*/
    int i;
    int j;
    for (i = 0; i < st.getNumMergedRegions(); i++) {
        region = st.getMergedRegion(i);
        if ((region.getFirstRow() >= pStartRow) && (region.getLastRow() <= pEndRow)) {
            targetRowFrom = region.getFirstRow() - pStartRow + pPosition;
            targetRowTo = region.getLastRow() - pStartRow + pPosition;

            CellRangeAddress newRegion = region.copy();

            newRegion.setFirstRow(targetRowFrom);
            newRegion.setFirstColumn(region.getFirstColumn());
            newRegion.setLastRow(targetRowTo);
            newRegion.setLastColumn(region.getLastColumn());
            st.addMergedRegion(newRegion);
        }
    }
    //set the column height and value
    for (i = pStartRow; i <= pEndRow; i++) {
        Row sourceRow = st.getRow(i);
        columnCount = sourceRow.getLastCellNum();
        if (sourceRow != null) {
            Row newRow = st.createRow(pPosition + i);
            newRow.setHeight(sourceRow.getHeight());
            for (j = 0; j < columnCount; j++) {
                Cell templateCell = sourceRow.getCell(j);
                if (templateCell != null) {
                    Cell newCell = newRow.createCell(j);
                    copyCell(templateCell, newCell);
                }
            }
        }
    }
}