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.unhcr.eg.odk.utilities.xlsform.excel.ExcelFileUtility.java

public static void addToDestination(HSSFWorkbook source, HSSFWorkbook destination) {
    ArrayList<String> listOfSheet = getListOfSheets(destination);
    int numberOfSheet = source.getNumberOfSheets();
    int j = 0;//from  w  w w  .  j a va 2 s  . c o m
    int sheetDestinationIndex;
    for (int i = 0; i < numberOfSheet; i++) {
        Sheet sheetSource = source.getSheetAt(i);
        String newName = sheetSource.getSheetName();
        sheetDestinationIndex = destination.getSheetIndex(newName);
        while (listOfSheet.contains(newName)) {
            newName = sheetSource.getSheetName() + "_" + j;
            newName = newName.substring(Math.max(newName.length() - 31, 0), Math.min(newName.length(), 31));
            sheetDestinationIndex = destination.getSheetIndex(newName);
            j++;
        }
        listOfSheet.add(newName);
        Sheet sheetDestination = destination.createSheet(newName);
        copyContent(sheetSource, sheetDestination);
    }
}

From source file:org.wandora.application.tools.extractors.excel.AbstractExcelExtractor.java

License:Open Source License

public Topic getCellTopic(Cell cell, TopicMap tm) throws TopicMapException {
    String cellIdentifier = null;
    switch (CELL_TOPIC_IS_BASED_ON) {
    case CELL_VALUE: {
        cellIdentifier = getCellValueAsString(cell);
        break;// w  ww  .  ja  va 2s. co m
    }
    case CELL_SHEET_AND_LOCATION: {
        Sheet sheet = cell.getSheet();
        String sheetName = sheet.getSheetName();
        cellIdentifier = sheetName + "-" + cell.getColumnIndex() + "-" + cell.getRowIndex();
        break;
    }
    case CELL_LOCATION: {
        cellIdentifier = cell.getColumnIndex() + "-" + cell.getRowIndex();
        break;
    }
    case CELL_HASH: {
        cellIdentifier = Integer.toString(cell.hashCode());
        break;
    }
    }
    if (cellIdentifier != null) {
        String si = EXCEL_CELL_SI_PREFIX + "/" + urlEncode(cellIdentifier);
        Topic cellTopic = getOrCreateTopic(tm, si, cellIdentifier);
        cellTopic.addType(getCellTypeTopic(tm));
        return cellTopic;
    }
    return null;
}

From source file:org.wandora.application.tools.extractors.excel.AbstractExcelExtractor.java

License:Open Source License

public Topic getSheetTopic(Cell cell, TopicMap tm) throws TopicMapException {
    Sheet sheet = cell.getSheet();
    if (sheet != null) {
        String sheetName = sheet.getSheetName();
        Topic topic = getOrCreateTopic(tm, EXCEL_SHEET_SI_PREFIX + "/" + urlEncode(sheetName), sheetName);
        topic.addType(getSheetTypeTopic(tm));
        return topic;
    }//from w w w .  j av a 2 s  .c o  m
    return null;
}

From source file:org.wso2.carbon.dataservices.sql.driver.processor.reader.ExcelDataReader.java

License:Open Source License

public void populateData() throws SQLException {
    Workbook workbook = ((TExcelConnection) getConnection()).getWorkbook();
    int noOfSheets = workbook.getNumberOfSheets();
    for (int i = 0; i < noOfSheets; i++) {
        Sheet sheet = workbook.getSheetAt(i);
        String sheetName = sheet.getSheetName();
        ColumnInfo[] headers = this.extractColumnHeaders(sheet);
        DataTable dataTable = new FixedDataTable(sheetName, headers);

        Iterator<Row> rowItr = sheet.rowIterator();
        while (rowItr.hasNext()) {
            Row row = rowItr.next();/*from  ww  w.  jav  a 2  s  .  c om*/
            if (row.getRowNum() != 0) {
                DataRow dataRow = new DataRow(row.getRowNum() - 1);
                Iterator<Cell> cellItr = row.cellIterator();
                int cellIndex = 0;
                while (cellItr.hasNext()) {
                    Cell cell = cellItr.next();
                    DataCell dataCell = new DataCell(cellIndex + 1, cell.getCellType(), extractCellValue(cell));
                    dataRow.addCell(dataCell.getColumnId(), dataCell);
                    cellIndex++;
                }
                dataTable.addRow(dataRow);
            }
        }
        this.getData().put(dataTable.getTableName(), dataTable);
    }
}

From source file:org.wso2.carbon.dataservices.sql.driver.processor.reader.ExcelDataReader.java

License:Open Source License

/**
 * Extracts out the columns in the given excel sheet
 *
 * @param sheet Sheet instance corresponding to the desired Excel sheet
 * @return Array containing the column header data
 * @throws java.sql.SQLException SQLException
 *//*from   w w  w .  j  a  v  a2 s .  c  o m*/
private ColumnInfo[] extractColumnHeaders(Sheet sheet) throws SQLException {
    List<ColumnInfo> headers = new ArrayList<ColumnInfo>();

    /* If hasHeader property is set to false, populate header map with column names following
     * the format 'COLUMN' + 'i' where i corresponds to the column id */
    if (!((TConnection) getConnection()).hasHeader()) {
        int maxColumns = ((TConnection) getConnection()).getMaxColumns();
        for (int i = 0; i < maxColumns; i++) {
            headers.add(new ColumnInfo(i + 1, Constants.COLUMN + (i + 1), sheet.getSheetName(), -1, i + 1));
        }
        return headers.toArray(new ColumnInfo[headers.size()]);
    }
    // Retrieving the first row of the sheet as the header row.
    Row row = sheet.getRow(0);
    if (row != null) {
        Iterator<Cell> itr = row.cellIterator();
        while (itr.hasNext()) {
            Cell cell = itr.next();
            if (cell != null) {
                int cellType = cell.getCellType();
                switch (cellType) {
                case Cell.CELL_TYPE_STRING:
                    headers.add(new ColumnInfo(cell.getColumnIndex() + 1, cell.getStringCellValue(),
                            sheet.getSheetName(), Types.VARCHAR, cell.getColumnIndex() + 1));
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    headers.add(new ColumnInfo(cell.getColumnIndex() + 1,
                            String.valueOf(cell.getNumericCellValue()), sheet.getSheetName(), Types.INTEGER,
                            cell.getColumnIndex() + 1));
                    break;
                default:
                    throw new SQLException("Invalid column type");
                }
            }
        }
    }
    return headers.toArray(new ColumnInfo[headers.size()]);
}

From source file:org.wso2.samples.RegistryResourceImporter.java

License:Open Source License

private static void addAssets(Registry registry, Workbook[] workbooks, String artifactType,
        Properties artifactMappings) throws Exception {
    for (Workbook workbook : workbooks) {
        Sheet sheet = workbook.getSheet(workbook.getSheetName(0));

        if (sheet == null || sheet.getLastRowNum() == -1) {
            throw new RuntimeException("The first sheet is empty");
        } else {// w  w  w .ja v a2s . c o m
            System.out.println("Adding data in Sheet : " + sheet.getSheetName());
        }

        int limit = sheet.getLastRowNum();
        if (limit < 1) {
            throw new RuntimeException("Column headers were not specified in Asset Data Spreadsheet");
        } else {
            System.out.println("Total number of rows in the sheet : " + limit);
        }

        Row row = sheet.getRow(0);

        // We use a linked list to keep the order
        List<String> headersAttributeNames = new LinkedList<String>();
        String value;
        int count = 0;
        Set artifactAttributes = artifactMappings.keySet();

        while ((value = getCellValue(row.getCell(count++), null)) != null) {
            headersAttributeNames.add(getMappingName(artifactMappings, value));
        }

        Registry governanceRegistry = GovernanceUtils.getGovernanceUserRegistry(registry, USERNAME);
        addAssetValues(governanceRegistry, sheet, limit, artifactType, headersAttributeNames,
                artifactAttributes);
    }
}

From source file:org.wso2.security.tool.adapter.ExcelInputAdapter.java

License:Open Source License

/**
 * Converts the data in the files with .xlsx extension to the JSON format.
 * A workbook is created from the the excel file (.xlsx) and while iterating through the sheets in the workbook;
 * the data is read and  set in to a JSONObject. The JSONObject returned by the method contains an array of
 * row objects corresponding to each row in the workbook. A row object contains values of each cell in a given row,
 * with key values starting from letter 'A'.
 *
 * @param dataFilePath The path where the data file uploaded is saved.
 * @return returns the JSON object that contains all the data in the .xlsx file.
 * @throws FeedbackToolException If the .xlsx file is not found in the given path or due to an error in
 *                               parsing the data in the data file.
 */// w  w w .j av  a 2s. co m
@Override
public JSONObject convert(String dataFilePath) throws FeedbackToolException {

    // JSONObject to hold the array of row objects
    JSONObject dataJSONObject = new JSONObject();
    try {
        Workbook workbook = WorkbookFactory.create(new File(dataFilePath));
        logInfo = "Workbook has " + workbook.getNumberOfSheets() + " sheets";
        log.info(logInfo);

        Iterator<Sheet> sheetIterator = workbook.sheetIterator();

        // JSONArray to hold all the row objects
        JSONArray rowsJSONArray = new JSONArray();
        while (sheetIterator.hasNext()) {
            Sheet sheet = sheetIterator.next();
            logInfo = "Sheet: " + sheet.getSheetName() + " has " + sheet.getNumMergedRegions()
                    + " merged regions";
            log.info(logInfo);

            DataFormatter dataFormatter = new DataFormatter();

            logInfo = "Iterating over Rows and Columns using for-each loop";
            log.info(logInfo);
            for (Row row : sheet) {

                // JSONObject to hold the data in the cells of a given row
                JSONObject rowJSONObject = new JSONObject();

                char keyLetter = 'A';
                for (Cell cell : row) {
                    String cellValue = dataFormatter.formatCellValue(cell);
                    rowJSONObject.put(keyLetter, cellValue);
                    ++keyLetter;
                }
                rowsJSONArray.add(rowJSONObject);
            }
        }
        dataJSONObject.put(Constants.JSON_DATA_OBJECT, rowsJSONArray);
    } catch (InvalidFormatException e) {
        throw new FeedbackToolException("Error in parsing the data file uploaded", e);
    } catch (IOException e) {
        throw new FeedbackToolException("Data file was not found in the specified location", e);
    }
    return dataJSONObject;
}

From source file:pruebaimportarexcel.PantallaPrincipal.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    List<Object> columnsName;
    List<List<Object>> datas;

    Sheet sheet = this.excelFile.getSheet((String) this.jComboBox3.getSelectedItem());
    //Row row = this.excelFile.getRow(sheet, 0);

    try {/*from  w ww  .j  a va2s  .  c  o m*/
        columnsName = Excels.getColumnsName(excelFile, (String) this.jComboBox3.getSelectedItem());

        datas = Excels.getDatasSheet(excelFile, (String) this.jComboBox3.getSelectedItem(), columnsName.size());

        this.jTable1.setModel(SwingUtil.initTableModel(columnsName, datas));
    } catch (NullPointerException ex) {
        JOptionPane.showMessageDialog(this,
                "La pagina " + sheet.getSheetName() + ".\n No es apta para ser importada a una base de datos.",
                "Informacion", JOptionPane.INFORMATION_MESSAGE);
    }
}

From source file:ru.operator.log.FileCreator.java

@Override
public Sheet createSheetWithHead(String sheetName) {
    Sheet s = wb.cloneSheet(0);
    wb.setSheetName(wb.getSheetIndex(s.getSheetName()), sheetName);
    System.out.println("Created " + s.getSheetName());
    return s;//from   ww  w . ja  va  2s. c om
}

From source file:ru.spb.nicetu.tableviewer.server.XlsToHtml.java

License:Apache License

public void printSheet(Sheet sheet, int numSheet) {
    ensureOut();//from w  w w. j av  a  2  s.c  o  m
    gotBounds = false;
    String sheetName = sheet.getSheetName();
    if (sheetName == null)
        sheetName = "";
    out.format((numSheet > 0 ? "<br/>%n" : "")
            + "<div width=\"100%%\" style=\"background-color: #dddddd; border: medium solid #dd7777; margin-bottom: 3px;\"><b>?  %s :  '%s'</b></div>%n",
            "" + (numSheet + 1), sheetName.replace("<", "&lt;"));
    out.format("<table class=%s>%n", DEFAULTS_CLASS);
    printCols(sheet);
    printSheetContent(sheet);
    out.format("</table>%n");
}