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

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

Introduction

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

Prototype

String getSheetName();

Source Link

Document

Returns the name of this sheet

Usage

From source file:org.ramadda.data.docs.TabularOutputHandler.java

License:Apache License

/**
 * _more_//from   ww  w  . j a va  2  s . c o  m
 *
 * @param request _more_
 * @param entry _more_
 * @param suffix _more_
 * @param inputStream _more_
 * @param visitInfo _more_
 * @param visitor _more_
 *
 * @throws Exception _more_
 */
private void visitXls(Request request, Entry entry, String suffix, InputStream inputStream,
        TextReader visitInfo, TabularVisitor visitor) throws Exception {
    //        System.err.println("visitXls: making workbook");
    Workbook wb = makeWorkbook(suffix, inputStream);
    //        System.err.println("visitXls:" + visitInfo.getSkip() + " max rows:" + visitInfo.getMaxRows()+ " #sheets:" + wb.getNumberOfSheets());
    int maxRows = visitInfo.getMaxRows();
    for (int sheetIdx = 0; sheetIdx < wb.getNumberOfSheets(); sheetIdx++) {
        if (!visitInfo.okToShowSheet(sheetIdx)) {
            continue;
        }
        Sheet sheet = wb.getSheetAt(sheetIdx);
        //            System.err.println("\tsheet:" + sheet.getSheetName() + " #rows:" + sheet.getLastRowNum());
        List<List<Object>> rows = new ArrayList<List<Object>>();
        int sheetSkip = visitInfo.getSkip();
        for (int rowIdx = sheet.getFirstRowNum(); (rows.size() < maxRows)
                && (rowIdx <= sheet.getLastRowNum()); rowIdx++) {
            if (sheetSkip-- > 0) {
                continue;
            }

            Row row = sheet.getRow(rowIdx);
            if (row == null) {
                continue;
            }
            List<Object> cols = new ArrayList<Object>();
            short firstCol = row.getFirstCellNum();
            for (short col = firstCol; (col < MAX_COLS) && (col < row.getLastCellNum()); col++) {
                Cell cell = row.getCell(col);
                if (cell == null) {
                    break;
                }
                Object value = null;
                int type = cell.getCellType();
                if (type == cell.CELL_TYPE_NUMERIC) {
                    value = new Double(cell.getNumericCellValue());
                } else if (type == cell.CELL_TYPE_BOOLEAN) {
                    value = new Boolean(cell.getBooleanCellValue());
                } else if (type == cell.CELL_TYPE_ERROR) {
                    value = "" + cell.getErrorCellValue();
                } else if (type == cell.CELL_TYPE_BLANK) {
                    value = "";
                } else if (type == cell.CELL_TYPE_FORMULA) {
                    value = cell.getCellFormula();
                } else {
                    value = cell.getStringCellValue();
                }
                cols.add(value);
            }

            /**
             * ** TODO
             * org.ramadda.util.text.Row row = new Row(cols);
             *
             * if ( !visitInfo.rowOk(row)) {
             *   if (rows.size() == 0) {
             *       //todo: check for the header line
             *   } else {
             *       continue;
             *   }
             * }
             */
            rows.add(cols);
        }
        if (!visitor.visit(visitInfo, sheet.getSheetName(), rows)) {
            break;
        }
    }
}

From source file:org.ramadda.data.docs.TabularOutputHandler.java

License:Apache License

/**
 * _more_//  w ww  .java 2  s  .  c o m
 *
 * @param args _more_
 *
 * @throws Exception _more_
 */
public static void main(String[] args) throws Exception {
    Workbook wb = makeWorkbook(IOUtil.getFileExtension(args[0]), new FileInputStream(args[0]));
    for (int sheetIdx = 0; sheetIdx < wb.getNumberOfSheets(); sheetIdx++) {
        Sheet sheet = wb.getSheetAt(sheetIdx);
        System.err.println(sheet.getSheetName());
        for (int rowIdx = sheet.getFirstRowNum(); rowIdx <= sheet.getLastRowNum(); rowIdx++) {
            Row row = sheet.getRow(rowIdx);
            if (row == null) {
                continue;
            }
            short firstCol = row.getFirstCellNum();
            int colCnt = 0;
            for (short col = firstCol; col < row.getLastCellNum(); col++) {
                Cell cell = row.getCell(col);
                if (cell == null) {
                    break;
                }
                Object value = null;
                int type = cell.getCellType();
                if (type == cell.CELL_TYPE_NUMERIC) {
                    value = new Double(cell.getNumericCellValue());
                } else if (type == cell.CELL_TYPE_BOOLEAN) {
                    value = new Boolean(cell.getBooleanCellValue());
                } else if (type == cell.CELL_TYPE_ERROR) {
                    value = "" + cell.getErrorCellValue();
                } else if (type == cell.CELL_TYPE_BLANK) {
                    value = "";
                } else if (type == cell.CELL_TYPE_FORMULA) {
                    value = cell.getCellFormula();
                } else {
                    value = cell.getStringCellValue();
                }
                if (colCnt++ > 0)
                    System.out.print(",");
                System.out.print(value);
            }
            System.out.println("");
        }
    }
}

From source file:org.ramadda.plugins.media.TabularOutputHandler.java

License:Open Source License

/**
 * _more_//from ww w . ja va 2 s.  com
 *
 * @param request _more_
 * @param entry _more_
 * @param suffix _more_
 * @param inputStream _more_
 * @param visitInfo _more_
 * @param visitor _more_
 *
 * @throws Exception _more_
 */
private void visitXls(Request request, Entry entry, String suffix, InputStream inputStream, Visitor visitInfo,
        TabularVisitor visitor) throws Exception {
    //        System.err.println("visitXls: making workbook");
    Workbook wb = makeWorkbook(suffix, inputStream);
    //        System.err.println("visitXls:" + visitInfo.getSkip() + " max rows:" + visitInfo.getMaxRows()+ " #sheets:" + wb.getNumberOfSheets());
    int maxRows = visitInfo.getMaxRows();
    for (int sheetIdx = 0; sheetIdx < wb.getNumberOfSheets(); sheetIdx++) {
        if (!visitInfo.okToShowSheet(sheetIdx)) {
            continue;
        }
        Sheet sheet = wb.getSheetAt(sheetIdx);
        //            System.err.println("\tsheet:" + sheet.getSheetName() + " #rows:" + sheet.getLastRowNum());
        List<List<Object>> rows = new ArrayList<List<Object>>();
        int sheetSkip = visitInfo.getSkip();
        for (int rowIdx = sheet.getFirstRowNum(); (rows.size() < maxRows)
                && (rowIdx <= sheet.getLastRowNum()); rowIdx++) {
            if (sheetSkip-- > 0) {
                continue;
            }

            Row row = sheet.getRow(rowIdx);
            if (row == null) {
                continue;
            }
            List<Object> cols = new ArrayList<Object>();
            short firstCol = row.getFirstCellNum();
            for (short col = firstCol; (col < MAX_COLS) && (col < row.getLastCellNum()); col++) {
                Cell cell = row.getCell(col);
                if (cell == null) {
                    break;
                }
                Object value = null;
                int type = cell.getCellType();
                if (type == cell.CELL_TYPE_NUMERIC) {
                    value = new Double(cell.getNumericCellValue());
                } else if (type == cell.CELL_TYPE_BOOLEAN) {
                    value = new Boolean(cell.getBooleanCellValue());
                } else if (type == cell.CELL_TYPE_ERROR) {
                    value = "" + cell.getErrorCellValue();
                } else if (type == cell.CELL_TYPE_BLANK) {
                    value = "";
                } else if (type == cell.CELL_TYPE_FORMULA) {
                    value = cell.getCellFormula();
                } else {
                    value = cell.getStringCellValue();
                }
                cols.add(value);
            }

            /**
             * ** TODO
             * org.ramadda.util.text.Row row = new Row(cols);
             *
             * if ( !visitInfo.rowOk(row)) {
             *   if (rows.size() == 0) {
             *       //todo: check for the header line
             *   } else {
             *       continue;
             *   }
             * }
             */
            rows.add(cols);
        }
        if (!visitor.visit(visitInfo, sheet.getSheetName(), rows)) {
            break;
        }
    }
}

From source file:org.rhq.helpers.perftest.test.ExcelExporterTest.java

License:Open Source License

/**
 * Test writing a workbook twice.//from w w w.j  a  va 2s.co m
 * Should contain one Overview tab and one 'test' tab
 * with two times the same result
 * @throws Exception If anything goes wrong
 */
public void testRewriteSheets() throws Exception {

    /*
     * Run a dummy test.
     */
    TestNG testNG = new TestNG();
    testNG.setTestClasses(new Class[] { DummyTest.class });
    TestListenerAdapter adapter = new TestListenerAdapter();
    testNG.addListener(adapter);
    testNG.run();
    // RHQ additional timing data
    Map<String, Long> timings = new HashMap<String, Long>();
    timings.put("test", 123L);

    /*
     * Set up the reporter
     */
    PerformanceReportExporter rep = new ExcelExporter();
    rep.setBaseFile("test1");
    rep.setRolling(PerformanceReporting.Rolling.NONE);

    /*
     * Write to .xls file twice
     */
    rep.export(timings, adapter.getPassedTests().iterator().next());
    rep.export(timings, adapter.getPassedTests().iterator().next());

    /*
     * Now check the workbook written
     * But first delete an existing file
     */
    File file = new File("test1.xls");

    FileInputStream fis = new FileInputStream(file);
    Workbook wb = new HSSFWorkbook(fis);

    assert wb.getNumberOfSheets() == 2 : "Workbook does not have 2 sheets";

    Sheet overview = wb.getSheetAt(0);
    assert overview.getSheetName().equals("Overview") : "Sheet 0 is not the Overview";
    assert wb.getSheetAt(1).getSheetName().equals("DummyTest.one") : "Sheet 1 is not DummyTest.one";

    // 0 based as opposed to xls where it rows are 1 based.
    assert overview.getLastRowNum() == 2 : "Last row of overview is not 4, but " + overview.getLastRowNum();

    fis.close();

    if (file.exists()) {
        assert file.delete();
    }
}

From source file:org.smart.migrate.dao.impl.MetaExcelDao.java

@Override
public List<String> getTables(Connection connection) {
    List<String> tables = new ArrayList<String>();
    try {//from   w  w  w.jav a2 s . c o m
        InputStream inp = new FileInputStream(dbfile);
        Workbook wb = WorkbookFactory.create(inp);
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            Sheet sheet = wb.getSheetAt(i);
            if (sheet.getPhysicalNumberOfRows() > 0) {
                tables.add(sheet.getSheetName());
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(MetaExcelDao.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(MetaExcelDao.class.getName()).log(Level.SEVERE, null, ex);
    }
    return tables;
}

From source file:org.specrunner.source.excel.SourceFactoryExcel.java

License:Open Source License

/**
 * Get caption./*from w ww .j a  va 2 s.  co m*/
 * 
 * @param table
 *            The target table.
 * @param sheet
 *            The sheet.
 * @return The caption.
 */
protected Element readCaption(Element table, Sheet sheet) {
    Element caption = new Element("caption");
    table.appendChild(caption);
    {
        caption.appendChild(sheet.getSheetName());
    }
    return caption;
}

From source file:org.squashtest.tm.service.internal.batchimport.testcase.excel.ExcelWorkbookParserBuilder.java

License:Open Source License

@SuppressWarnings("rawtypes")
private void processSheet(Workbook wb, WorkbookMetaData wmd, List<WorksheetFormatStatus> worksheetKOStatuses,
        int iSheet) {
    Sheet ws = wb.getSheetAt(iSheet);
    String sheetName = ws.getSheetName();

    Collection<TemplateWorksheet> sheetTypes = TemplateWorksheet.coerceFromSheetName(sheetName);

    for (TemplateWorksheet sheetType : sheetTypes) {
        if (sheetType != null) {
            LOGGER.trace("Worksheet named '{}' will be added to metamodel as standard worksheet {}", sheetName,
                    sheetType);/*w  w w.  jav a 2  s  . c om*/

            WorksheetDef<?> wd = new WorksheetDef(sheetType);
            wmd.addWorksheetDef(wd);
            WorksheetFormatStatus workSheetFormatStatus = populateColumnDefs(wd, ws);
            if (!workSheetFormatStatus.isFormatOk()) {
                worksheetKOStatuses.add(workSheetFormatStatus);
            }
        } else {
            LOGGER.trace("Skipping unrecognized worksheet named '{}'", ws.getSheetName());

        }
    }
}

From source file:org.talend.dataprep.schema.xls.streaming.StreamingWorkbook.java

License:Open Source License

/**
 * {@inheritDoc}//from  w ww  . j a  v  a  2  s .  c om
 */
@Override
public int getSheetIndex(Sheet sheet) {
    if (sheet instanceof StreamingSheet) {
        return reader.findSheetByName(sheet.getSheetName());
    } else {
        throw new UnsupportedOperationException("Cannot use non-StreamingSheet sheets");
    }
}

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

License:Open Source License

private List<Schema.SheetContent> parseAllSheetsStream(Request request) {
    Workbook workbook = StreamingReader.builder() //
            .bufferSize(4096) //
            .rowCacheSize(1) //
            .open(request.getContent());
    try {/*  w w w  .j ava  2s.  c o m*/
        List<Schema.SheetContent> schemas = new ArrayList<>();
        int sheetNumber = 0;
        for (Sheet sheet : workbook) {
            List<ColumnMetadata> columnsMetadata = createMetadataFromFirstNonEmptyRowAndInitSheet(sheet);
            int totalColumnsNumber = getTotalColumnsNumber((StreamingSheet) sheet);

            /*
             * Protecting the app against too large data sets => It would break mongo by submitting too large empty
             * column metadata or saturate the memory during analysis.
             *
             * @see https://jira.talendforge.org/browse/TDP-3459
             */
            if (totalColumnsNumber > maxNumberOfColumns) {
                throw new TDPException(DataSetErrorCodes.DATASET_HAS_TOO_MANY_COLUMNS, ExceptionContext.build()
                        .put("number-of-columns", totalColumnsNumber).put("max-allowed", maxNumberOfColumns));
            }

            String sheetName = sheet.getSheetName();
            Schema.SheetContent sheetContent = new Schema.SheetContent(
                    StringUtils.isEmpty(sheetName) ? "sheet-" + sheetNumber : sheetName, columnsMetadata);

            // if less columns found than the metadata we complete
            completeWithEmptyColumnsMetadata(columnsMetadata, totalColumnsNumber);
            schemas.add(sheetContent);
        }
        return schemas;
    } finally {
        try {
            workbook.close();
        } catch (IOException e) {
            LOGGER.error("Unable to close excel file.", e);
        }
    }
}

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.// w  w w.j  a va2s.  co  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);
    }
}