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:com.globalsight.everest.webapp.pagehandler.administration.reports.generator.ReviewersCommentsReportGenerator.java

License:Apache License

/**
 * Create Report File.//from  w w  w .  j  a  v a 2 s.c  om
 */
protected File getFile(String p_reportType, Job p_job, Workbook p_workBook) {
    String langInfo = null;
    // If the Workbook has only one sheet, the report name should contain language pair info, such as en_US_de_DE.
    if (p_workBook != null && p_workBook.getNumberOfSheets() == 1) {
        Sheet sheet = p_workBook.getSheetAt(0);
        String srcLang = null, trgLang = null;
        if (p_job != null) {
            srcLang = p_job.getSourceLocale().toString();
        }
        if (trgLang == null) {
            trgLang = sheet.getSheetName();
        }
        if (srcLang != null && trgLang != null) {
            langInfo = srcLang + "_" + trgLang;
        }
    }

    return ReportHelper.getReportFile(p_reportType, p_job, ReportConstants.EXTENSION_XLSX, langInfo);
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.reports.generator.ScorecardReportGenerator.java

License:Apache License

/**
 * Create Report File./*from  w  w  w  .j  a va 2s  .c o  m*/
 */
protected File getFile(String p_reportType, Job p_job, Workbook p_workBook) {
    String langInfo = null;
    // If the Workbook has only one sheet, the report name should contain language pair info, such as en_US_de_DE.
    if (p_workBook != null && p_workBook.getNumberOfSheets() == 1) {
        Sheet sheet = p_workBook.getSheetAt(0);
        String srcLang = null, trgLang = null;
        if (p_job != null) {
            srcLang = p_job.getSourceLocale().toString();
        }
        if (srcLang == null) {
            Row languageInfoRow = sheet.getRow(1);
            if (languageInfoRow != null) {
                srcLang = languageInfoRow.getCell(0).getStringCellValue();
                srcLang = srcLang.substring(srcLang.indexOf("[") + 1, srcLang.indexOf("]"));
                trgLang = languageInfoRow.getCell(1).getStringCellValue();
                trgLang = trgLang.substring(trgLang.indexOf("[") + 1, trgLang.indexOf("]"));
            } else {
                Row dataRow = sheet.getRow(sheet.getLastRowNum());
                if (dataRow != null) {
                    try {
                        long jobId = (long) dataRow.getCell(0).getNumericCellValue();
                        Job job = ServerProxy.getJobHandler().getJobById(jobId);
                        srcLang = job.getSourceLocale().toString();
                    } catch (Exception e) {
                    }

                }
            }
        }
        if (trgLang == null) {
            trgLang = sheet.getSheetName();
        }
        if (srcLang != null && trgLang != null) {
            langInfo = srcLang + "_" + trgLang;
        }
    }

    return ReportHelper.getReportFile(p_reportType, p_job, ReportConstants.EXTENSION_XLSX, langInfo);
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.reports.generator.SummaryReportGenerator.java

License:Apache License

private void addNumberCell(Sheet p_sheet, int p_column, int p_row, double p_value, CellStyle cs) {
    try {//  w w  w.ja  va  2  s .com
        Cell cell = getCell(getRow(p_sheet, p_row), p_column);
        cell.setCellValue(p_value);
        if (cs != null)
            cell.setCellStyle(cs);
    } catch (Exception e) {
        logger.warn("addNumberCell Error1.[" + p_sheet.getSheetName() + ", " + p_column + ", " + p_row + ", "
                + p_value + "]", e);
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.reports.ReviewerLisaQAXlsReportHelper.java

License:Apache License

/**
 * Create workbook name areas for category failure drop down list, it is
 * from "AA8" to "AAn"./*from   w w  w.  j  a v a2 s  .  c om*/
 * <P>
 * Only write the data of drop down list into the first sheet as it can be
 * referenced from all sheets.
 * </P>
 * <P>
 * The formula is like
 * "[sheetName]!$AA$[startRow]:$AA$[endRow]",i.e."TER!$AA$8:$AA$32".
 * </P>
 */
private void createCategoryFailureNameArea(Workbook p_workbook) {
    Sheet firstSheet = getSheet(p_workbook, 0);
    List<String> categories = getFailureCategoriesList();
    // Set the categories in "AA" column, starts with row 8.
    int col = 26;
    for (int i = 0; i < categories.size(); i++) {
        Row row = getRow(firstSheet, SEGMENT_START_ROW + i);
        Cell cell = getCell(row, col);
        cell.setCellValue(categories.get(i));
    }

    String formula = firstSheet.getSheetName() + "!$AA$" + (SEGMENT_START_ROW + 1) + ":$AA$"
            + (SEGMENT_START_ROW + categories.size());
    Name name = p_workbook.createName();
    name.setRefersToFormula(formula);
    name.setNameName(CATEGORY_FAILURE_DROP_DOWN_LIST);

    // Hide "AA" column
    firstSheet.setColumnHidden(26, true);
}

From source file:com.googlecode.testcase.annotation.handle.toexcel.strategy.ToHtmlWithExcel.java

License:Apache License

public void printSheetPage(Sheet sheet) throws IOException {
    this.output = new FileWriter(dstfolder + sheet.getSheetName() + ".html");
    this.out = new Formatter(output);

    try {// w ww  .  j  av a 2  s  . co m
        ensureOut();
        if (completeHTML) {
            out.format("<?xml version=\"1.0\" encoding=\"gb2312\" ?>%n");
            out.format("<html>%n");
            out.format("<head>%n");
            out.format("</head>%n");
            out.format("<body>%n");
        }

        printInlineStyle();
        _printSheetPage(sheet);

        if (completeHTML) {
            out.format("</body>%n");
            out.format("</html>%n");
        }
    } finally {
        if (out != null)
            out.close();
        if (output instanceof Closeable) {
            Closeable closeable = (Closeable) output;
            closeable.close();
        }
    }
}

From source file:com.googlecode.testcase.annotation.handle.toexcel.strategy.ToHtmlWithExcel.java

License:Apache License

private void printColumnHeads(Sheet sheet) {
    out.format("<thead>%n");
    out.format("  <tr class=%s>%n", COL_HEAD_CLASS);
    out.format("    <th class=%s>%s</th>%n", COL_HEAD_CLASS, sheet.getSheetName());
    //noinspection UnusedDeclaration
    StringBuilder colName = new StringBuilder();
    for (int i = firstColumn; i < endColumn; i++) {
        colName.setLength(0);/* w  w w .jav a 2s .  c o  m*/
        int cnum = i;
        do {
            colName.insert(0, (char) ('A' + cnum % 26));
            cnum /= 26;
        } while (cnum > 0);
        out.format("    <th class=%s>%s</th>%n", COL_HEAD_CLASS, colName);
    }
    out.format("  </tr>%n");
    out.format("</thead>%n");
}

From source file:com.hurence.logisland.processor.excel.ExcelExtract.java

License:Apache License

/**
 * Extract every matching sheet from the raw excel input stream.
 *
 * @param inputStream an inputstream that will be closed once consumed.
 * @return a stream of {@link Record} each containing the stream raw data.
 *//* w w  w. j a  v  a2s .c o m*/
private Stream<Record> handleExcelStream(InputStream inputStream) {
    List<Record> ret = new ArrayList<>();
    try {
        try (Workbook workbook = WorkbookFactory.create(inputStream)) {
            Iterator<Sheet> iter = workbook.sheetIterator();
            while (iter.hasNext()) {
                String sheetName = "unknown";
                List<String> headerNames = null;

                try {
                    Sheet sheet = iter.next();
                    sheetName = sheet.getSheetName();
                    if (toBeSkipped(sheetName)) {
                        LOGGER.info("Skipped sheet {}", sheetName);
                        continue;
                    }
                    LOGGER.info("Extracting sheet {}", sheetName);
                    int count = 0;
                    for (Row row : sheet) {
                        if (row == null) {
                            continue;
                        }
                        if (configuration.getHeaderRowNumber() != null
                                && configuration.getHeaderRowNumber().equals(row.getRowNum())) {
                            headerNames = extractFieldNamesFromRow(row);

                        }
                        if (count++ < configuration.getRowsToSkip()) {
                            continue;
                        }
                        Record current = handleRow(row, headerNames);
                        current.setField(Fields.rowNumber(row.getRowNum()))
                                .setField(Fields.sheetName(sheetName));
                        ret.add(current);
                    }

                } catch (Exception e) {
                    LOGGER.error("Unrecoverable exception occurred while processing excel sheet", e);
                    ret.add(new StandardRecord().addError(ProcessError.RECORD_CONVERSION_ERROR.getName(),
                            String.format("Unable to parse sheet %s: %s", sheetName, e.getMessage())));
                }
            }
        }
    } catch (InvalidFormatException | NotOfficeXmlFileException ife) {
        LOGGER.error("Wrong or unsupported file format.", ife);
        ret.add(new StandardRecord().addError(ProcessError.INVALID_FILE_FORMAT_ERROR.getName(),
                ife.getMessage()));
    } catch (IOException ioe) {
        LOGGER.error("I/O Exception occurred while processing excel file", ioe);
        ret.add(new StandardRecord().addError(ProcessError.RUNTIME_ERROR.getName(), ioe.getMessage()));

    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return ret.stream();
}

From source file:com.hust.zsuper.DealWithPatent.ExcelToMySQL.java

License:Open Source License

public void addTableFromSheet(final Connection conn, final Sheet sheet) throws SQLException {
    final int numRows = sheet.getPhysicalNumberOfRows();
    if (numRows < 2) {
        //Not enough or can't determine
    }/*from w  w  w  . ja va 2 s  .c  om*/
    final List<Entry<String, ExcelType>> types = extractTypes(sheet);
    final String tableName = Utils.cleanUp(sheet.getSheetName());
    {
        final String dropStatement = "DROP TABLE IF EXISTS `" + tableName + "`;";
        conn.createStatement().execute(dropStatement);
        System.out.println(dropStatement);
    }
    {
        final String createStatement = getCreateTable(tableName, types);
        System.out.println(createStatement);
        conn.createStatement().execute(createStatement);
    }

    int rowCount = 0;
    for (final Row row : new IteratorWrapper<Row>(sheet.iterator())) {
        if (rowCount > 0) {
            final String insert = createInsert(tableName, types, row);
            if (insert != null) {
                System.out.println(insert);
                conn.createStatement().execute(insert);
            }
        }
        rowCount++;
    }
}

From source file:com.hust.zsuper.DealWithPatent.WorkhseetToMySQL.java

License:Open Source License

public WorkhseetToMySQL(Sheet sheet) {
    this.sheet = sheet;
    this.types = new ArrayList<Entry<String, ExcelType>>();
    extractTypes(sheet);/*from w  w w  . j av a 2  s. c o m*/
    this.tableName = Utils.cleanUp(sheet.getSheetName());
    this.columnOffset = 0;
}

From source file:com.ibm.db2j.GExcel.java

License:Open Source License

/**
 * Put the next row in the dvd row given in parameter.
 * Return SCAN_COMPLETED if there is no more row in the spreadsheet, or GOT_ROW if a row was successfully put in the dvd row.
 * /*from w  w  w. j  a va 2 s  . c  o m*/
 * Uses the attribute currentRow to save the previous row fetched.
 * 
 * @param sheet
 * @param dvdr
 * @param numberOfLogicalColumnsInvolved
 * @param columnIndexes
 * @return SCAN_COMPLETED or GOT_ROW
 * @throws SQLException
 */
private int createNextRow(Sheet sheet, DataValueDescriptor[] dvdr) {
    boolean gotData = false;

    /*
     * Find the next row to return.
     * 
     * currentRow should currently point to the last row returned.
     * If that's null, then start from first row.
     * Else, search for the next non-empty row (until we hit the end of the prescribed range).
     */
    if (currentRow == null)
        currentRow = sheet.getRow(firstRowIndex + (firstRowIsMetaData ? 1 : 0));
    else {
        int nextRowIndex = currentRow.getRowNum() + 1;
        currentRow = null;

        if (stopScanOnFirstEmptyRow) {
            currentRow = sheet.getRow(nextRowIndex);
        } else {
            while (currentRow == null && nextRowIndex <= lastRowIndex) {
                currentRow = sheet.getRow(nextRowIndex);
                nextRowIndex++;
            }
        }
    }

    /*
     * If we've run out of spreadsheet (currentRow == null) or gone out of the prescribed range,
     * then scan complete - return that.
     */
    if (currentRow == null || currentRow.getRowNum() > lastRowIndex) {
        return SCAN_COMPLETED;
    }

    /*
     * Get the offset of the first column in the spreadsheet.
     * Note: this is used when iterating below, so that we can correctly relate 
     * the actual column in the spreadsheet to the correct 'column' in the 
     * DataValueDescriptor [] representing the row.
     */
    int columnOffset = firstColumnIndex;

    //Figure out how many columns there are
    int numberOfColumns = lastColumnIndex - firstColumnIndex + 1;

    for (int i = 0; i < numberOfColumns; i++) {
        /*
         * Note: i is used to refer to the index of the DataValueDescriptor which represents
         * the actual spreadsheet column (at i + columnOffset) in the DataValueDescriptor[] 
         * representing this row. 
         */

        Cell cell = currentRow.getCell(i + columnOffset);

        if (cell == null) {
            dvdr[i].setToNull();
        } else {
            try {
                int cellValueType = cell.getCellType();

                if (cellValueType == Cell.CELL_TYPE_FORMULA)
                    cellValueType = cell.getCachedFormulaResultType();

                switch (cellValueType) {

                case Cell.CELL_TYPE_STRING:
                    dvdr[i].setValue(cell.getStringCellValue());
                    break;

                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell))
                        dvdr[i].setValue(new java.sql.Date(cell.getDateCellValue().getTime()));
                    else {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        dvdr[i].setValue(cell.getStringCellValue());
                    }
                    break;

                case Cell.CELL_TYPE_BOOLEAN:
                    dvdr[i].setValue(cell.getBooleanCellValue());
                    break;

                default:
                    dvdr[i].setToNull();
                    break;
                }

                //If a cell has data that is not null - then flag that we actually have data to return
                if (!dvdr[i].isNull())
                    gotData = true;

            } catch (Exception e) {
                dvdr[i].setToNull();
                logger.logWarning(GDBMessages.DSWRAPPER_GEXCEL_MAP_LT_ERROR, "Excel cell [spreadsheet "
                        + sheet.getSheetName() + "; row " + cell.getRow().getRowNum() + "; column "
                        + cell.getColumnIndex() + "; value " + cell
                        + "] could not be mapped into the logical table because of the column logical type: "
                        + e);
            }
        }
    }

    if (!gotData && stopScanOnFirstEmptyRow) {
        logger.logInfo(
                "Ending GExcel table scan on first empty row (as no row limit was specified in the ending cell config constraint)");
        return SCAN_COMPLETED;
    }

    return GOT_ROW;
}