Example usage for org.apache.poi.hssf.usermodel HSSFRow getRowNum

List of usage examples for org.apache.poi.hssf.usermodel HSSFRow getRowNum

Introduction

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

Prototype

@Override
public int getRowNum() 

Source Link

Document

get row number this row represents

Usage

From source file:org.projectforge.excel.ExcelImport.java

License:Open Source License

/**
 * convert a single row to an object.// ww  w. j  a  v  a  2 s  .  c  o m
 * 
 * @param row the row containing the values.
 * @param columnNames the row containing the column-names.
 * @param rowNum the current rownum
 * @return a new created object populated with the values.
 * @throws InstantiationException if the object creation fails.
 * @throws IllegalAccessException if the object creation fails or the invoked setter is not public.
 * @throws InvocationTargetException if the object creation fails with an exception or the setter threw an exception.
 * @throws NoSuchMethodException if the setter for the property name is not existant.
 */
private T convertToBean(final HSSFRow row, final HSSFRow columnNames, final int rowNum)
        throws InstantiationException, IllegalAccessException, InvocationTargetException,
        NoSuchMethodException {
    if (row == null) {
        log.debug("created no bean for row#" + rowNum);
        return null;
    }
    final T o = clazzFactory.newInstance(row);
    if (columnNames == null) {
        return null;
    }
    for (int column = 0; column < columnNames.getPhysicalNumberOfCells(); column++) {
        if (columnNames.getCell(column) == null) {
            continue;
        }
        String columnName = columnNames.getCell(column).getStringCellValue();
        if (columnName != null) {
            columnName = columnName.trim();
        }
        String propName = columnName;
        if (columnToPropertyMap != null) {
            final String mapName = columnToPropertyMap.get(columnName);
            if (mapName != null) {
                propName = mapName.trim();
            }
        }
        try {
            final Class<?> destClazz = PropertyUtils.getPropertyType(o, propName);
            if (propName == null || destClazz == null) {
                log.debug("Skipping column " + columnName);
                continue;
            }
            final Object value = toNativeType(row.getCell(column), destClazz);
            log.debug("Setting property=" + propName + " to " + value + " class="
                    + ClassUtils.getShortClassName(value, "null"));
            PropertyUtils.setProperty(o, propName, value);
        } catch (final ConversionException e) {
            log.warn(e);
            throw new ExcelImportException("Falscher Datentyp beim Excelimport", new Integer(row.getRowNum()),
                    columnName);
        } catch (final Exception e) {
            log.warn(e);
            throw new ExcelImportException("Falscher Datentyp beim Excelimport", new Integer(row.getRowNum()),
                    columnName);
        }
    }
    if (log.isDebugEnabled() == true) {
        log.debug("created bean " + o + " for row#" + rowNum);
    }
    return o;
}

From source file:org.rti.zcore.dar.utils.PoiUtils.java

License:Apache License

/**
 * This utility is a version of HSSF.main that does not use deprecated methods.
 * It is helpful in figuring out what row a filed is on when outputting Excel files via POI.
 * @param pathExcelMaster/*w ww .ja  v a 2 s . c o m*/
 */
public static void testExcelOutput(String pathExcelMaster) {

    try {
        //HSSF hssf = new HSSF(args[ 0 ]);

        System.out.println("Data dump:\n");
        //HSSFWorkbook wb = hssf.hssfworkbook;
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(pathExcelMaster));
        HSSFWorkbook wb = new HSSFWorkbook(fs);

        for (int k = 0; k < wb.getNumberOfSheets(); k++) {
            System.out.println("Sheet " + k);
            HSSFSheet sheet = wb.getSheetAt(k);
            int rows = sheet.getPhysicalNumberOfRows();

            for (int r = 0; r < rows; r++) {
                //HSSFRow row   = sheet.getPhysicalRowAt(r);
                HSSFRow row = sheet.getRow(r);
                if (row != null) {
                    int cells = row.getPhysicalNumberOfCells();
                    System.out.println("ROW " + row.getRowNum());
                    for (int c = 0; c < cells; c++) {
                        //HSSFCell cell  = row.getPhysicalCellAt(c);
                        HSSFCell cell = row.getCell(c);
                        String value = null;
                        if (cell != null) {
                            switch (cell.getCellType()) {

                            case HSSFCell.CELL_TYPE_FORMULA:
                                value = "FORMULA ";
                                value = "FORMULA " + cell.getCellFormula();
                                break;

                            case HSSFCell.CELL_TYPE_NUMERIC:
                                value = "NUMERIC value=" + cell.getNumericCellValue();
                                break;

                            case HSSFCell.CELL_TYPE_STRING:
                                //value = "STRING value=" + cell.getStringCellValue();
                                HSSFRichTextString str = cell.getRichStringCellValue();
                                value = "STRING value=" + str;
                                break;

                            default:
                            }
                            //System.out.println("CELL col=" + cell.getCellNum()  + " VALUE=" + value);
                            System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.seasar.dbflute.helper.io.xls.DfTableXlsReader.java

License:Apache License

protected void throwCellValueHandlingException(DfDataTable table, DfDataColumn column, HSSFRow row,
        HSSFCell cell, Object value, RuntimeException cause) {
    final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
    br.addNotice("Failed to handle the cell value on the xls file.");
    br.addItem("Advice");
    br.addElement("Confirm the exception message.");
    br.addElement("The cell value may be wrong type for the column.");
    br.addElement("So confirm the value on the xls file.");
    br.addItem("RuntimeException");
    br.addElement(cause.getMessage());//from  www  .  j  a v  a  2  s  .c o  m
    br.addItem("Xls File");
    br.addElement(_xlsFile);
    br.addItem("Table");
    br.addElement(table.getTableDbName());
    br.addItem("Column");
    br.addElement(column != null ? column.getColumnDbName() : null);
    br.addItem("Mapping Type");
    final DfDtsColumnType columnType = column.getColumnType();
    br.addElement(columnType != null ? columnType.getType() : null);
    br.addItem("Cell Type");
    if (cell != null) {
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_NUMERIC:
            br.addElement("CELL_TYPE_NUMERIC");
            break;
        case HSSFCell.CELL_TYPE_STRING:
            br.addElement("CELL_TYPE_STRING");
            break;
        case HSSFCell.CELL_TYPE_FORMULA:
            br.addElement("CELL_TYPE_FORMULA");
            break;
        case HSSFCell.CELL_TYPE_BLANK:
            br.addElement("CELL_TYPE_BLANK");
            break;
        case HSSFCell.CELL_TYPE_BOOLEAN:
            br.addElement("CELL_TYPE_BOOLEAN");
            break;
        case HSSFCell.CELL_TYPE_ERROR:
            br.addElement("CELL_TYPE_ERROR");
            break;
        default:
            br.addElement(cell.getCellType());
            break;
        }
    }
    br.addItem("Cell Value");
    br.addElement(value);
    br.addItem("Row Number");
    br.addElement(column != null ? row.getRowNum() : null);
    final String msg = br.buildExceptionMessage();
    throw new DfXlsReaderReadFailureException(msg, cause);
}

From source file:org.seasar.dbflute.helper.io.xls.DfTableXlsReader.java

License:Apache License

protected void throwLargeDataReferenceDataNotFoundException(DfDataTable table, int columnIndex, HSSFRow row,
        String str, String dataKey) {
    final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
    br.addNotice("Not found the reference data of large data for the column.");
    br.addItem("Xls File");
    br.addElement(_xlsFile);/* w  ww .  j a v a 2s .  co  m*/
    br.addItem("Table Name");
    br.addElement(table.getTableDbName());
    br.addItem("Column");
    br.addElement(table.getColumnName(columnIndex));
    br.addItem("Row Number");
    br.addElement(row.getRowNum());
    br.addItem("Cell Value");
    br.addElement(str);
    br.addItem("Data Key");
    br.addElement(dataKey);
    final String msg = br.buildExceptionMessage();
    throw new DfXlsReaderReadFailureException(msg);
}

From source file:org.seasar.dbflute.helper.io.xls.DfTableXlsWriter.java

License:Apache License

protected String resolveLargeDataReferenceIfNeeds(DfDataTable table, int columnIndex, HSSFRow row,
        String strValue) {/*from ww w.jav a 2s .  co m*/
    final String mark = "...";
    final int splitLength = getCellLengthLimit() - mark.length();
    if (strValue != null && strValue.length() > splitLength) {
        final String filteredValue;
        if (_largeDataHandling) {
            if (_largeDataMap == null) {
                _largeDataMap = StringKeyMap.createAsFlexibleOrdered();
            }
            final String tableDbName = table.getTableDbName();
            final DfDataColumn column = table.getColumn(columnIndex);
            final String columnDbName = column.getColumnDbName();
            final String columnTitle = tableDbName + "." + columnDbName;
            Map<String, List<String>> dataMap = _largeDataMap.get(columnTitle);
            if (dataMap == null) {
                dataMap = DfCollectionUtil.newLinkedHashMap();
                _largeDataMap.put(columnTitle, dataMap);
            }
            final String plainKey = columnTitle + ":" + row.getRowNum();
            final String dataKey = Integer.toHexString(plainKey.hashCode());
            dataMap.put(dataKey, toLargeDataSplitList(strValue));
            filteredValue = toLargeDataReferenceExp(dataKey);
        } else {
            filteredValue = strValue.substring(0, splitLength) + mark;
        }
        return filteredValue;
    }
    return strValue;
}

From source file:org.seasar.dbflute.helper.io.xls.DfXlsReader.java

License:Apache License

protected void throwCellValueHandlingException(DfDataTable table, DfDataColumn column, HSSFRow row,
        HSSFCell cell, Object value, RuntimeException e) {
    String msg = "Look! Read the message below." + ln();
    msg = msg + "/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -" + ln();
    msg = msg + "Failed to handling the cell value!" + ln();
    msg = msg + ln();/*from www  . jav  a  2s  .c o m*/
    msg = msg + "[Table]" + ln() + table.getTableDbName() + ln();
    msg = msg + ln();
    msg = msg + "[Column]" + ln() + (column != null ? column.getColumnDbName() : null) + ln();
    msg = msg + ln();
    msg = msg + "[Row Number]" + ln() + row.getRowNum() + ln();
    msg = msg + ln();
    msg = msg + "[Cell Object]" + ln() + cell + ln();
    msg = msg + ln();
    if (cell != null) {
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_NUMERIC:
            msg = msg + "[Cell Type]" + ln() + "CELL_TYPE_NUMERIC" + ln();
            break;
        case HSSFCell.CELL_TYPE_STRING:
            msg = msg + "[Cell Type]" + ln() + "CELL_TYPE_STRING" + ln();
            break;
        case HSSFCell.CELL_TYPE_FORMULA:
            msg = msg + "[Cell Type]" + ln() + "CELL_TYPE_FORMULA" + ln();
            break;
        case HSSFCell.CELL_TYPE_BLANK:
            msg = msg + "[Cell Type]" + ln() + "CELL_TYPE_BLANK" + ln();
            break;
        case HSSFCell.CELL_TYPE_BOOLEAN:
            msg = msg + "[Cell Type]" + ln() + "CELL_TYPE_BOOLEAN" + ln();
            break;
        case HSSFCell.CELL_TYPE_ERROR:
            msg = msg + "[Cell Type]" + ln() + "CELL_TYPE_ERROR" + ln();
            break;
        default:
            msg = msg + "[Cell Type]" + ln() + cell.getCellType() + ln();
            break;
        }
    }
    msg = msg + ln();
    msg = msg + "[Cell Value]" + ln() + value + ln();
    msg = msg + "- - - - - - - - - -/";
    throw new IllegalStateException(msg, e);
}

From source file:org.sharegov.cirm.utils.ExcelExportUtil.java

License:Apache License

public Integer searchCriteriaRows1(Json searchCriteria, HSSFCellStyle boldCenterStyle, int totalRecords) {
    int rowCounter = 0;
    int cellCounter = 0;
    //Create Headings and info about the report
    HSSFRow row = sheet.createRow(rowCounter++);
    HSSFCell cell = row.createCell(cellCounter++);
    cell.setCellValue(basicSearchReportHeader);
    cell.setCellStyle(boldCenterStyle);/*from w ww  .j  a  v  a2  s  .c  om*/
    sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), cell.getColumnIndex(),
            cell.getColumnIndex() + 3));
    row = sheet.createRow(rowCounter++);
    cellCounter = 0;
    cell = row.createCell(cellCounter++);
    cell.setCellValue(searchCriteriaHeader);
    sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), cell.getColumnIndex(),
            cell.getColumnIndex() + 2));

    for (Entry<String, Json> prop : searchCriteria.asJsonMap().entrySet()) {
        row = sheet.createRow(rowCounter++);
        cellCounter = 0;
        cell = row.createCell(cellCounter++);
        cell.setCellValue(prop.getKey());
        cell = row.createCell(cellCounter++);
        cell.setCellValue(prop.getValue().asString());
    }

    row = sheet.createRow(rowCounter++);
    row = sheet.createRow(rowCounter++);
    cellCounter = 0;
    cell = row.createCell(cellCounter++);
    cell.setCellValue(totalResults + " : " + totalRecords);
    sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), cell.getColumnIndex(),
            cell.getColumnIndex() + 1));
    row = sheet.createRow(rowCounter++);
    return rowCounter;
}

From source file:org.sharegov.cirm.utils.ExcelExportUtil.java

License:Apache License

public Integer searchCriteriaRows(Json allData, HSSFCellStyle boldStyle) {
    Json basicSCLabels = Json.object().set("type", "SR Type").set("legacy:hasCaseNumber", "SR ID")
            .set("atAddress", "Address").set("isCreatedBy", "Input By").set("name", "First Name")
            .set("lastName", "Last Name").set("legacy:hasStatus", "Status")
            .set("legacy:hasIntakeMethod", "Intake Method").set("legacy:hasPriority", "Priority")
            .set("serviceQuestion", "SR Question").set("legacy:hasDueDate", "Over Due Date")
            .set("hasDateCreated", "Created Date").set("legacy:hasServiceCaseActor", "Customer Name")
            .set("gisColumnName", "");

    Json searchCriteria = allData.at("searchCriteria");

    OWLOntology ont = ontology();//from  ww  w . j a va2s  .  c  om
    int rowCounter = 0;
    //int cellCounter = 0;
    //Create Headings and info about the report
    HSSFRow row = sheet.createRow(rowCounter++);
    HSSFCell cell = row.createCell(0);
    cell.setCellValue(basicSearchReportHeader);
    cell.setCellStyle(boldStyle);
    sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), cell.getColumnIndex(),
            cell.getColumnIndex() + 3));
    row = sheet.createRow(rowCounter++);
    row = sheet.createRow(rowCounter++);
    //       cellCounter = 0;
    cell = row.createCell(0);
    cell.setCellValue(searchCriteriaHeader);
    sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), cell.getColumnIndex(),
            cell.getColumnIndex() + 2));
    for (Entry<String, Json> prop : searchCriteria.asJsonMap().entrySet()) {
        if (prop.getKey().equalsIgnoreCase("sortBy") || prop.getKey().equalsIgnoreCase("caseSensitive")
                || prop.getKey().equalsIgnoreCase("sortDirection")
                || prop.getKey().equalsIgnoreCase("currentPage")
                || prop.getKey().equalsIgnoreCase("itemsPerPage"))
            continue;
        if (prop.getKey().equalsIgnoreCase("type")) {
            if (prop.getValue().isString() && prop.getValue().asString().equalsIgnoreCase("legacy:ServiceCase"))
                continue;
            if (prop.getValue().isArray()) {
                List<Json> typeList = prop.getValue().asJsonList();
                if (typeList.size() == 1 && typeList.get(0).asString().equalsIgnoreCase("legacy:ServiceCase"))
                    continue;
            }
        }

        StringBuilder sbQuestion = new StringBuilder("");
        StringBuilder sbAnswer = new StringBuilder("");

        sbQuestion.append(
                basicSCLabels.has(prop.getKey()) ? basicSCLabels.at(prop.getKey()).asString() : prop.getKey());
        if (prop.getKey().equalsIgnoreCase("type")) {
            //sbAnswer.append(getEntityLabel(individual(prop.getValue().asString())));
            sbAnswer.append("SR TYPE");
        } else if (ont.isDeclared(dataProperty(fullIri(prop.getKey())), true)) {
            sbAnswer.append(prop.getValue().asString());
        } else if (ont.isDeclared(objectProperty(fullIri(prop.getKey())), true)) {
            if (prop.getKey().equals("legacy:hasStatus") || prop.getKey().equals("legacy:hasIntakeMethod")
                    || prop.getKey().equals("legacy:hasPriority")) {
                sbAnswer.append(getEntityLabel(individual(prop.getValue().at("iri").asString())));
            }
            if (prop.getKey().equals("atAddress")) {
                if (prop.getValue().has("fullAddress"))
                    sbAnswer.append(prop.getValue().at("fullAddress").asString());
                if (prop.getValue().has("Street_Unit_Number"))
                    sbAnswer.append("#").append(prop.getValue().at("Street_Unit_Number").asString());
                if (prop.getValue().has("Street_Address_City"))
                    sbAnswer.append(", ").append(ServiceRequestReportUtil.getCity(prop.getValue()));
                if (prop.getValue().has("Zip_Code"))
                    sbAnswer.append(" - ").append(prop.getValue().at("Zip_Code").asString());
            } else if (prop.getKey().equals("legacy:hasServiceCaseActor")) {
                if (prop.getValue().has("Name"))
                    sbAnswer.append(prop.getValue().at("Name").asString());
                if (prop.getValue().has("LastName"))
                    sbAnswer.append(" ").append(prop.getValue().at("LastName").asString());
            } else if (prop.getKey().equals("hasGeoPropertySet")) {
                sbQuestion = new StringBuilder("");
                for (Entry<String, Json> geoProp : prop.getValue().asJsonMap().entrySet()) {
                    if (geoProp.getKey().equals("type"))
                        continue;
                    else {
                        sbQuestion.append(geoProp.getKey());
                        sbAnswer.append(geoProp.getValue().asString());
                    }
                }
            }
        } else if (ont.containsIndividualInSignature(fullIri(prop.getKey()), true)) {
            sbQuestion = new StringBuilder("");
            sbQuestion.append(getEntityLabel(individual(prop.getKey())));
            if (prop.getValue().isString())
                sbAnswer.append(getEntityLabel(individual(prop.getValue().asString())));
            else if (prop.getValue().isObject())
                sbAnswer.append(prop.getValue().at("literal").asString());
        } else {
            continue;
        }
        row = sheet.createRow(rowCounter++);
        //          cellCounter = 0;
        cell = row.createCell(0);
        cell.setCellValue(sbQuestion.toString());
        sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), cell.getColumnIndex(),
                cell.getColumnIndex() + 1));
        cell = row.createCell(2);
        cell.setCellValue(sbAnswer.toString());
        sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), cell.getColumnIndex(),
                cell.getColumnIndex() + 1));
    }

    row = sheet.createRow(rowCounter++);
    row = sheet.createRow(rowCounter++);
    //       cellCounter = 0;
    cell = row.createCell(0);
    cell.setCellValue(totalResults);
    cell.setCellStyle(boldStyle);
    cell = row.createCell(1);
    cell.setCellValue(allData.at("data").asJsonList().size());
    //       boldStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
    //       boldStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    cell.setCellStyle(boldStyle);

    row = sheet.createRow(rowCounter++);
    return rowCounter;
}

From source file:poi.hssf.usermodel.examples.HSSFReadWrite.java

License:Apache License

/**
  * Method main//from w  w  w .  j av  a2 s  . c o  m
  *
  * Given 1 argument takes that as the filename, inputs it and dumps the
  * cell values/types out to sys.out.<br/>
  *
  * given 2 arguments where the second argument is the word "write" and the
  * first is the filename - writes out a sample (test) spreadsheet
  * see {@link HSSFReadWrite#testCreateSampleSheet(String)}.<br/>
  *
  * given 2 arguments where the first is an input filename and the second
  * an output filename (not write), attempts to fully read in the
  * spreadsheet and fully write it out.<br/>
  *
  * given 3 arguments where the first is an input filename and the second an
  * output filename (not write) and the third is "modify1", attempts to read in the
  * spreadsheet, deletes rows 0-24, 74-99.  Changes cell at row 39, col 3 to
  * "MODIFIED CELL" then writes it out.  Hence this is "modify test 1".  If you
  * take the output from the write test, you'll have a valid scenario.
  */
public static void main(String[] args) {
    if (args.length < 1) {
        System.err.println("At least one argument expected");
        return;
    }

    String fileName = args[0];
    try {
        if (args.length < 2) {

            HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);

            System.out.println("Data dump:\n");

            for (int k = 0; k < wb.getNumberOfSheets(); k++) {
                HSSFSheet sheet = wb.getSheetAt(k);
                int rows = sheet.getPhysicalNumberOfRows();
                System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows + " row(s).");
                for (int r = 0; r < rows; r++) {
                    HSSFRow row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }

                    int cells = row.getPhysicalNumberOfCells();
                    System.out.println("\nROW " + row.getRowNum() + " has " + cells + " cell(s).");
                    for (int c = 0; c < cells; c++) {
                        HSSFCell cell = row.getCell(c);
                        String value = null;

                        switch (cell.getCellType()) {

                        case HSSFCell.CELL_TYPE_FORMULA:
                            value = "FORMULA value=" + cell.getCellFormula();
                            break;

                        case HSSFCell.CELL_TYPE_NUMERIC:
                            value = "NUMERIC value=" + cell.getNumericCellValue();
                            break;

                        case HSSFCell.CELL_TYPE_STRING:
                            value = "STRING value=" + cell.getStringCellValue();
                            break;

                        default:
                        }
                        System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);
                    }
                }
            }
        } else if (args.length == 2) {
            if (args[1].toLowerCase().equals("write")) {
                System.out.println("Write mode");
                long time = System.currentTimeMillis();
                HSSFReadWrite.testCreateSampleSheet(fileName);

                System.out.println("" + (System.currentTimeMillis() - time) + " ms generation time");
            } else {
                System.out.println("readwrite test");
                HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
                FileOutputStream stream = new FileOutputStream(args[1]);

                wb.write(stream);
                stream.close();
            }
        } else if (args.length == 3 && args[2].toLowerCase().equals("modify1")) {
            // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"

            HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
            FileOutputStream stream = new FileOutputStream(args[1]);
            HSSFSheet sheet = wb.getSheetAt(0);

            for (int k = 0; k < 25; k++) {
                HSSFRow row = sheet.getRow(k);

                sheet.removeRow(row);
            }
            for (int k = 74; k < 100; k++) {
                HSSFRow row = sheet.getRow(k);

                sheet.removeRow(row);
            }
            HSSFRow row = sheet.getRow(39);
            HSSFCell cell = row.getCell(3);
            cell.setCellValue("MODIFIED CELL!!!!!");

            wb.write(stream);
            stream.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:poi.HSSFReadWrite.java

License:Apache License

/**
  * Method main//from  ww  w  .  ja v a2  s .co m
  *
  * Given 1 argument takes that as the filename, inputs it and dumps the
  * cell values/types out to sys.out.<br/>
  *
  * given 2 arguments where the second argument is the word "write" and the
  * first is the filename - writes out a sample (test) spreadsheet
  * see {@link HSSFReadWrite#testCreateSampleSheet(String)}.<br/>
  *
  * given 2 arguments where the first is an input filename and the second
  * an output filename (not write), attempts to fully read in the
  * spreadsheet and fully write it out.<br/>
  *
  * given 3 arguments where the first is an input filename and the second an
  * output filename (not write) and the third is "modify1", attempts to read in the
  * spreadsheet, deletes rows 0-24, 74-99.  Changes cell at row 39, col 3 to
  * "MODIFIED CELL" then writes it out.  Hence this is "modify test 1".  If you
  * take the output from the write test, you'll have a valid scenario.
  */
public static void main(String[] args) {
    if (args.length < 1) {
        System.err.println("At least one argument expected");
        return;
    }

    String fileName = args[0];
    try {
        if (args.length < 2) {

            HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);

            System.out.println("Data dump:\n");

            for (int k = 0; k < wb.getNumberOfSheets(); k++) {
                HSSFSheet sheet = wb.getSheetAt(k);
                int rows = sheet.getPhysicalNumberOfRows();
                System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows + " row(s).");
                for (int r = 0; r < rows; r++) {
                    HSSFRow row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }

                    int cells = row.getPhysicalNumberOfCells();
                    System.out.println("\nROW " + row.getRowNum() + " has " + cells + " cell(s).");
                    for (int c = 0; c < cells; c++) {
                        HSSFCell cell = row.getCell(c);
                        String value = null;

                        switch (cell.getCellType()) {

                        case HSSFCell.CELL_TYPE_FORMULA:
                            value = "FORMULA value=" + cell.getCellFormula();
                            break;

                        case HSSFCell.CELL_TYPE_NUMERIC:
                            value = "NUMERIC value=" + cell.getNumericCellValue();
                            break;

                        case HSSFCell.CELL_TYPE_STRING:
                            value = "STRING value=" + cell.getStringCellValue();
                            break;

                        default:
                        }
                        System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);
                    }
                }
            }
            //            wb.close();
        } else if (args.length == 2) {
            if (args[1].toLowerCase(Locale.ROOT).equals("write")) {
                System.out.println("Write mode");
                long time = System.currentTimeMillis();
                HSSFReadWrite.testCreateSampleSheet(fileName);

                System.out.println("" + (System.currentTimeMillis() - time) + " ms generation time");
            } else {
                System.out.println("readwrite test");
                HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
                FileOutputStream stream = new FileOutputStream(args[1]);

                wb.write(stream);
                stream.close();
                //               wb.close();
            }
        } else if (args.length == 3 && args[2].toLowerCase(Locale.ROOT).equals("modify1")) {
            // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"

            HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
            FileOutputStream stream = new FileOutputStream(args[1]);
            HSSFSheet sheet = wb.getSheetAt(0);

            for (int k = 0; k < 25; k++) {
                HSSFRow row = sheet.getRow(k);

                sheet.removeRow(row);
            }
            for (int k = 74; k < 100; k++) {
                HSSFRow row = sheet.getRow(k);

                sheet.removeRow(row);
            }
            HSSFRow row = sheet.getRow(39);
            HSSFCell cell = row.getCell(3);
            cell.setCellValue("MODIFIED CELL!!!!!");

            wb.write(stream);
            stream.close();
            //            wb.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}