Example usage for org.apache.poi.ss.usermodel Workbook getNumberOfSheets

List of usage examples for org.apache.poi.ss.usermodel Workbook getNumberOfSheets

Introduction

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

Prototype

int getNumberOfSheets();

Source Link

Document

Get the number of spreadsheets in the workbook

Usage

From source file:org.codelabor.example.crud.emp.web.controller.EmpController.java

License:Apache License

private List<EmpDto> fileToDtoList(MultipartFile file, List<String> failureMessages)
        throws IllegalArgumentException, InvalidFormatException, IOException { // NOPMD
    // by// www  . ja  v  a 2 s.  c  o  m
    // "SHIN Sang-jae"

    Workbook wb = WorkbookFactory.create(file.getInputStream());
    int numberOfSheets = wb.getNumberOfSheets();
    logger.debug("numberOfSheets: {}", numberOfSheets);

    // prepare model
    List<EmpDto> empDtoList = new ArrayList<EmpDto>();

    // set effective position
    int effectiveFirstSheetIndex = 0;
    int effectiveLastSheetIndex = numberOfSheets - 1;

    // traverse sheet
    StringBuilder sb = new StringBuilder();
    for (int i = effectiveFirstSheetIndex; i <= effectiveLastSheetIndex; i++) {
        Sheet sheet = wb.getSheetAt(i);
        String sheetName = sheet.getSheetName();
        logger.debug("sheetName: {}", sheetName);
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        logger.debug("firstRowNum: {},  lastRowNum: {}", firstRowNum, lastRowNum);

        // set effective position
        int effectiveFirstRowIndex = 1; // header row: 0
        int effectiveLastRowIndex = lastRowNum;

        // traverse row
        for (int j = effectiveFirstRowIndex; j <= effectiveLastRowIndex; j++) {
            // prepare model
            EmpDto empDto = new EmpDto(); // NOPMD by "SHIN Sang-jae"

            Row row = sheet.getRow(j);
            int rowNum = row.getRowNum();
            int firstCellNum = row.getFirstCellNum();
            int lastCellNum = row.getLastCellNum();
            logger.debug("rowNum: {}, firstCellNum: {},  lastCellNum: {}", rowNum, firstCellNum, lastCellNum);

            // set effective position
            int effectiveFirstCellIndex = firstCellNum;
            int effectiveLastCellIndex = lastCellNum - 1;

            // traverse cell
            for (int k = effectiveFirstCellIndex; k <= effectiveLastCellIndex; k++) {
                Cell cell = row.getCell(k);
                if (cell != null) {
                    int rowIndex = cell.getRowIndex();
                    int columnIndex = cell.getColumnIndex();
                    CellReference cellRef = new CellReference(rowIndex, columnIndex); // NOPMD by "SHIN Sang-jae"

                    logger.debug("cellRef: {}, rowIndex: {}, columnIndex: {}", cellRef, rowIndex, columnIndex);
                    // populate dto
                    switch (k) {
                    case 0: // EMPNO
                        empDto.setEmpNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 1: // ENAME
                        empDto.setEname(cell.getRichStringCellValue().toString());
                        break;
                    case 2: // JOB
                        empDto.setJob(cell.getRichStringCellValue().toString());
                        break;
                    case 3: // MGR
                        empDto.setMgr(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 4: // HIREDATE
                        empDto.setHireDate(cell.getDateCellValue());
                        break;
                    case 5: // SAL
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setSal(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 6: // COMM
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setComm(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 7: // DEPTNO
                        empDto.setDeptNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    default:
                        break;
                    }
                }
            }
            logger.debug("empDto: {}", empDto);

            // validate
            Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
            Set<ConstraintViolation<EmpDto>> violations = validator.validate(empDto);

            if (violations.isEmpty()) {
                // do all or nothing
                empDtoList.add(empDto);
            } else {
                // add failure message
                sb.setLength(0); // init StringBuilder for reuse
                for (ConstraintViolation<EmpDto> violation : violations) {
                    String propertyPath = violation.getPropertyPath().toString();
                    String message = violation.getMessage();
                    sb.append(message);
                    sb.append(" (row: ").append(j).append(", property: ").append(propertyPath).append(')');
                    failureMessages.add(sb.toString());
                    logger.error(sb.toString());
                    sb.setLength(0);
                }
            }
        }
    }
    return empDtoList;
}

From source file:org.codelabor.example.crud.emp.web.controller.EmpController.java

License:Apache License

private List<EmpDto> fileToDtoList(Part file, List<String> failureMessages)
        throws IllegalArgumentException, InvalidFormatException, IOException { // NOPMD
    // by/*from   w w w  .j  a v a  2  s. c  om*/
    // "SHIN Sang-jae"

    Workbook wb = WorkbookFactory.create(file.getInputStream());
    int numberOfSheets = wb.getNumberOfSheets();
    logger.debug("numberOfSheets: {}", numberOfSheets);

    // prepare model
    List<EmpDto> empDtoList = new ArrayList<EmpDto>();

    // set effective position
    int effectiveFirstSheetIndex = 0;
    int effectiveLastSheetIndex = numberOfSheets - 1;

    // traverse sheet
    StringBuilder sb = new StringBuilder();
    for (int i = effectiveFirstSheetIndex; i <= effectiveLastSheetIndex; i++) {
        Sheet sheet = wb.getSheetAt(i);
        String sheetName = sheet.getSheetName();
        logger.debug("sheetName: {}", sheetName);
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        logger.debug("firstRowNum: {},  lastRowNum: {}", firstRowNum, lastRowNum);

        // set effective position
        int effectiveFirstRowIndex = 1; // header row: 0
        int effectiveLastRowIndex = lastRowNum;

        // traverse row
        for (int j = effectiveFirstRowIndex; j <= effectiveLastRowIndex; j++) {
            // prepare model
            EmpDto empDto = new EmpDto(); // NOPMD by "SHIN Sang-jae"

            Row row = sheet.getRow(j);
            int rowNum = row.getRowNum();
            int firstCellNum = row.getFirstCellNum();
            int lastCellNum = row.getLastCellNum();
            logger.debug("rowNum: {}, firstCellNum: {},  lastCellNum: {}", rowNum, firstCellNum, lastCellNum);

            // set effective position
            int effectiveFirstCellIndex = firstCellNum;
            int effectiveLastCellIndex = lastCellNum - 1;

            // traverse cell
            for (int k = effectiveFirstCellIndex; k <= effectiveLastCellIndex; k++) {
                Cell cell = row.getCell(k);
                if (cell != null) {
                    int rowIndex = cell.getRowIndex();
                    int columnIndex = cell.getColumnIndex();
                    CellReference cellRef = new CellReference(rowIndex, columnIndex); // NOPMD by "SHIN Sang-jae"

                    logger.debug("cellRef: {}, rowIndex: {}, columnIndex: {}", cellRef, rowIndex, columnIndex);
                    // populate dto
                    switch (k) {
                    case 0: // EMPNO
                        empDto.setEmpNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 1: // ENAME
                        empDto.setEname(cell.getRichStringCellValue().toString());
                        break;
                    case 2: // JOB
                        empDto.setJob(cell.getRichStringCellValue().toString());
                        break;
                    case 3: // MGR
                        empDto.setMgr(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 4: // HIREDATE
                        empDto.setHireDate(cell.getDateCellValue());
                        break;
                    case 5: // SAL
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setSal(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 6: // COMM
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setComm(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 7: // DEPTNO
                        empDto.setDeptNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    default:
                        break;
                    }
                }
            }
            logger.debug("empDto: {}", empDto);

            // validate
            Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
            Set<ConstraintViolation<EmpDto>> violations = validator.validate(empDto);

            if (violations.isEmpty()) {
                // do all or nothing
                empDtoList.add(empDto);
            } else {
                // add failure message
                sb.setLength(0); // init StringBuilder for reuse
                for (ConstraintViolation<EmpDto> violation : violations) {
                    String propertyPath = violation.getPropertyPath().toString();
                    String message = violation.getMessage();
                    sb.append(message);
                    sb.append(" (row: ").append(j).append(", property: ").append(propertyPath).append(')');
                    failureMessages.add(sb.toString());
                    logger.error(sb.toString());
                    sb.setLength(0);
                }
            }
        }
    }
    return empDtoList;
}

From source file:org.codelabor.example.emp.web.controller.EmpController.java

License:Apache License

private List<EmpDto> fileToDtoList(MultipartFile file, List<String> failureMessages)
        throws IllegalArgumentException, InvalidFormatException, IOException { // NOPMD by "SHIN Sang-jae"

    Workbook wb = WorkbookFactory.create(file.getInputStream());
    int numberOfSheets = wb.getNumberOfSheets();
    logger.debug("numberOfSheets: {}", numberOfSheets);

    // prepare model
    List<EmpDto> empDtoList = new ArrayList<EmpDto>();

    // set effective position
    int effectiveFirstSheetIndex = 0;
    int effectiveLastSheetIndex = numberOfSheets - 1;

    // traverse sheet
    StringBuilder sb = new StringBuilder();
    for (int i = effectiveFirstSheetIndex; i <= effectiveLastSheetIndex; i++) {
        Sheet sheet = wb.getSheetAt(i);//from w  ww  .  j av  a2 s.co m
        String sheetName = sheet.getSheetName();
        logger.debug("sheetName: {}", sheetName);
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        logger.debug("firstRowNum: {},  lastRowNum: {}", firstRowNum, lastRowNum);

        // set effective position
        int effectiveFirstRowIndex = 1; // header row: 0
        int effectiveLastRowIndex = lastRowNum;

        // traverse row
        for (int j = effectiveFirstRowIndex; j <= effectiveLastRowIndex; j++) {
            // prepare model
            EmpDto empDto = new EmpDto(); // NOPMD by "SHIN Sang-jae"

            Row row = sheet.getRow(j);
            int rowNum = row.getRowNum();
            int firstCellNum = row.getFirstCellNum();
            int lastCellNum = row.getLastCellNum();
            logger.debug("rowNum: {}, firstCellNum: {},  lastCellNum: {}", rowNum, firstCellNum, lastCellNum);

            // set effective position
            int effectiveFirstCellIndex = firstCellNum;
            int effectiveLastCellIndex = lastCellNum - 1;

            // traverse cell
            for (int k = effectiveFirstCellIndex; k <= effectiveLastCellIndex; k++) {
                Cell cell = row.getCell(k);
                if (cell != null) {
                    int rowIndex = cell.getRowIndex();
                    int columnIndex = cell.getColumnIndex();
                    CellReference cellRef = new CellReference(rowIndex, columnIndex); // NOPMD by "SHIN Sang-jae"

                    logger.debug("cellRef: {}, rowIndex: {}, columnIndex: {}", cellRef, rowIndex, columnIndex);
                    // populate dto
                    switch (k) {
                    case 0: // EMPNO
                        empDto.setEmpNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 1: // ENAME
                        empDto.setEname(cell.getRichStringCellValue().toString());
                        break;
                    case 2: // JOB
                        empDto.setJob(cell.getRichStringCellValue().toString());
                        break;
                    case 3: // MGR
                        empDto.setMgr(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 4: // HIREDATE
                        empDto.setHireDate(cell.getDateCellValue());
                        break;
                    case 5: // SAL
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setSal(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 6: // COMM
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setComm(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 7: // DEPTNO
                        empDto.setDeptNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    default:
                        break;
                    }
                }
            }
            logger.debug("empDto: {}", empDto);

            // validate
            Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
            Set<ConstraintViolation<EmpDto>> violations = validator.validate(empDto);

            if (violations.isEmpty()) {
                // do all or nothing
                empDtoList.add(empDto);
            } else {
                // add failure message
                sb.setLength(0); // init StringBuilder for reuse
                for (ConstraintViolation<EmpDto> violation : violations) {
                    String propertyPath = violation.getPropertyPath().toString();
                    String message = violation.getMessage();
                    sb.append(message);
                    sb.append(" (row: ").append(j).append(", property: ").append(propertyPath).append(')');
                    failureMessages.add(sb.toString());
                    logger.error(sb.toString());
                    sb.setLength(0);
                }
            }
        }
    }
    return empDtoList;
}

From source file:org.codelabor.example.emp.web.controller.EmpController.java

License:Apache License

private List<EmpDto> fileToDtoList(Part file, List<String> failureMessages)
        throws IllegalArgumentException, InvalidFormatException, IOException { // NOPMD by "SHIN Sang-jae"

    Workbook wb = WorkbookFactory.create(file.getInputStream());
    int numberOfSheets = wb.getNumberOfSheets();
    logger.debug("numberOfSheets: {}", numberOfSheets);

    // prepare model
    List<EmpDto> empDtoList = new ArrayList<EmpDto>();

    // set effective position
    int effectiveFirstSheetIndex = 0;
    int effectiveLastSheetIndex = numberOfSheets - 1;

    // traverse sheet
    StringBuilder sb = new StringBuilder();
    for (int i = effectiveFirstSheetIndex; i <= effectiveLastSheetIndex; i++) {
        Sheet sheet = wb.getSheetAt(i);//  www .j  ava  2s.  co m
        String sheetName = sheet.getSheetName();
        logger.debug("sheetName: {}", sheetName);
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        logger.debug("firstRowNum: {},  lastRowNum: {}", firstRowNum, lastRowNum);

        // set effective position
        int effectiveFirstRowIndex = 1; // header row: 0
        int effectiveLastRowIndex = lastRowNum;

        // traverse row
        for (int j = effectiveFirstRowIndex; j <= effectiveLastRowIndex; j++) {
            // prepare model
            EmpDto empDto = new EmpDto(); // NOPMD by "SHIN Sang-jae"

            Row row = sheet.getRow(j);
            int rowNum = row.getRowNum();
            int firstCellNum = row.getFirstCellNum();
            int lastCellNum = row.getLastCellNum();
            logger.debug("rowNum: {}, firstCellNum: {},  lastCellNum: {}", rowNum, firstCellNum, lastCellNum);

            // set effective position
            int effectiveFirstCellIndex = firstCellNum;
            int effectiveLastCellIndex = lastCellNum - 1;

            // traverse cell
            for (int k = effectiveFirstCellIndex; k <= effectiveLastCellIndex; k++) {
                Cell cell = row.getCell(k);
                if (cell != null) {
                    int rowIndex = cell.getRowIndex();
                    int columnIndex = cell.getColumnIndex();
                    CellReference cellRef = new CellReference(rowIndex, columnIndex); // NOPMD by "SHIN Sang-jae"

                    logger.debug("cellRef: {}, rowIndex: {}, columnIndex: {}", cellRef, rowIndex, columnIndex);
                    // populate dto
                    switch (k) {
                    case 0: // EMPNO
                        empDto.setEmpNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 1: // ENAME
                        empDto.setEname(cell.getRichStringCellValue().toString());
                        break;
                    case 2: // JOB
                        empDto.setJob(cell.getRichStringCellValue().toString());
                        break;
                    case 3: // MGR
                        empDto.setMgr(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 4: // HIREDATE
                        empDto.setHireDate(cell.getDateCellValue());
                        break;
                    case 5: // SAL
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setSal(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 6: // COMM
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setComm(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 7: // DEPTNO
                        empDto.setDeptNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    default:
                        break;
                    }
                }
            }
            logger.debug("empDto: {}", empDto);

            // validate
            Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
            Set<ConstraintViolation<EmpDto>> violations = validator.validate(empDto);

            if (violations.isEmpty()) {
                // do all or nothing
                empDtoList.add(empDto);
            } else {
                // add failure message
                sb.setLength(0); // init StringBuilder for reuse
                for (ConstraintViolation<EmpDto> violation : violations) {
                    String propertyPath = violation.getPropertyPath().toString();
                    String message = violation.getMessage();
                    sb.append(message);
                    sb.append(" (row: ").append(j).append(", property: ").append(propertyPath).append(')');
                    failureMessages.add(sb.toString());
                    logger.error(sb.toString());
                    sb.setLength(0);
                }
            }
        }
    }
    return empDtoList;
}

From source file:org.corpus_tools.peppermodules.spreadsheet.Spreadsheet2SaltMapper.java

License:Apache License

private void setDocMetaData(Workbook workbook) {
    Sheet metaSheet = null;//from   w w  w  .  ja v  a2  s.  co m

    // default ("Tabelle2"/ second sheet)
    if (getProps().getMetaSheet().equals("Tabelle2")) {
        if (workbook.getNumberOfSheets() > 1) {
            metaSheet = workbook.getSheetAt(1);
        }
    } else {
        // get corpus sheet by name
        metaSheet = workbook.getSheet(getProps().getCorpusSheet());
    }

    if (metaSheet != null) {
        DataFormatter formatter = new DataFormatter();
        // start with the second row of the table, since the first row holds
        // the name of each tier
        int currRow = 1;
        while (currRow < metaSheet.getPhysicalNumberOfRows()) {
            // iterate through all rows of the given meta informations

            Row row = metaSheet.getRow(currRow);
            Cell metaKey = row.getCell(0);
            Cell metaValue = row.getCell(1);

            if (metaKey != null && !metaKey.toString().isEmpty()) {
                if (metaValue != null && !metaValue.toString().isEmpty()) {
                    if (getDocument().getMetaAnnotation(metaKey.toString()) == null) {
                        getDocument().createMetaAnnotation(null, formatter.formatCellValue(metaKey),
                                formatter.formatCellValue(metaValue));
                    } else {
                        SpreadsheetImporter.logger
                                .warn("A meta information with the name \"" + formatter.formatCellValue(metaKey)
                                        + "\" allready exists and will not be replaced.");
                    }
                } else {
                    SpreadsheetImporter.logger
                            .warn("No value for the meta data: \"" + metaKey.toString() + "\" found.");
                }
            } else {
                if (metaValue != null && !metaValue.toString().isEmpty()) {
                    SpreadsheetImporter.logger.warn(
                            "No meta annotation name for the value \"" + metaValue.toString() + "\" found.");
                }
            }
            currRow++;
        }
    }
}

From source file:org.cytoscape.tableimport.internal.ImportAttributeTableReaderTask.java

License:Open Source License

@Override
public void run(TaskMonitor tm) throws Exception {

    tm.setTitle("Loading table data");
    tm.setProgress(0.0);//from   w  ww.  j  av a 2 s . c o m
    tm.setStatusMessage("Loading table...");

    Workbook workbook = null;
    // Load Spreadsheet data for preview.
    if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) {
        try {
            workbook = WorkbookFactory.create(is);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Could not read Excel file.  Maybe the file is broken?");
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) {

        //            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        //               final Sheet sheet = workbook.getSheetAt(i);
        //
        //               this.reader = new ExcelAttributeSheetReader(sheet, amp);
        //               loadAnnotation(tm);
        //            }

        // Fixed bug# 1668, Only load data from the first sheet, ignore the rest sheets
        if (workbook.getNumberOfSheets() > 0) {
            final Sheet sheet = workbook.getSheetAt(0);
            this.reader = new ExcelAttributeSheetReader(sheet, amp);
            loadAnnotation(tm);
        }
    } else {
        this.reader = new DefaultAttributeTableReader(null, amp, this.is);
        loadAnnotation(tm);
    }
}

From source file:org.cytoscape.tableimport.internal.LoadTableReaderTask.java

License:Open Source License

@Override
public void run(TaskMonitor tm) throws Exception {

    tm.setTitle("Loading table data");
    tm.setProgress(0.0);/*from w  ww  .j  a  v a  2  s. co  m*/
    tm.setStatusMessage("Loading table...");

    List<String> attrNameList = new ArrayList<String>();
    int colCount;
    int startLoadRowTemp;
    String[] attributeNames;

    Workbook workbook = null;
    // Load Spreadsheet data for preview.
    if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) {
        try {
            workbook = WorkbookFactory.create(isStart);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Could not read Excel file.  Maybe the file is broken?");
        } finally {
            if (isStart != null) {
                isStart.close();
            }
        }
    }
    if (startLoadRow > 0)
        startLoadRow--;
    startLoadRowTemp = startLoadRow;
    if (firstRowAsColumnNames)
        startLoadRowTemp = 0;

    previewPanel.setPreviewTable(workbook, fileType, inputName, isStart, delimiters.getSelectedValues(), null,
            50, null, startLoadRowTemp);

    colCount = previewPanel.getPreviewTable().getColumnModel().getColumnCount();
    importFlag = new boolean[colCount];
    Object curName = null;

    if (firstRowAsColumnNames) {
        setFirstRowAsColumnNames();
        startLoadRow++;
    }

    for (int i = 0; i < colCount; i++) {
        importFlag[i] = true;
        curName = previewPanel.getPreviewTable().getColumnModel().getColumn(i).getHeaderValue();

        if (attrNameList.contains(curName)) {
            int dupIndex = 0;

            for (int idx = 0; idx < attrNameList.size(); idx++) {
                if (curName.equals(attrNameList.get(idx))) {
                    dupIndex = idx;

                    break;
                }
            }

            if (importFlag[i] && importFlag[dupIndex]) {
                //TODO add message to user
                return;
            }
        }

        if (curName == null) {
            attrNameList.add("Column " + i);
        } else {
            attrNameList.add(curName.toString());
        }
    }
    attributeNames = attrNameList.toArray(new String[0]);

    final Byte[] test = previewPanel.getDataTypes(previewPanel.getSelectedSheetName());

    final Byte[] attributeTypes = new Byte[test.length];

    for (int i = 0; i < test.length; i++) {
        attributeTypes[i] = test[i];
    }

    if (keyColumnIndex > 0)
        keyColumnIndex--;

    amp = new AttributeMappingParameters(delimiters.getSelectedValues(),
            delimitersForDataList.getSelectedValue(), keyColumnIndex, attributeNames, attributeTypes,
            previewPanel.getCurrentListDataTypes(), importFlag, true, startLoadRow, null);

    if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) {

        // Fixed bug# 1668, Only load data from the first sheet, ignore the rest sheets
        if (workbook.getNumberOfSheets() > 0) {
            final Sheet sheet = workbook.getSheetAt(0);
            this.reader = new ExcelAttributeSheetReader(sheet, amp);
            loadAnnotation(tm);
        }
    } else {
        this.reader = new DefaultAttributeTableReader(null, amp, this.isEnd);
        loadAnnotation(tm);
    }
}

From source file:org.cytoscape.tableimport.internal.ui.PreviewTablePanel.java

License:Open Source License

/**
 * Load file and show preview./*from w  ww  . java 2s.c  o  m*/
 */
public void updatePreviewTable(final Workbook workbook, final String fileType, final String fileFullName,
        final InputStream tempIs, final List<String> delimiters, final String commentLineChar,
        final int startLine) throws IOException {
    if (tempIs == null)
        return;

    if ((commentLineChar != null) && (commentLineChar.trim().length() != 0))
        this.commentChar = commentLineChar;
    else
        this.commentChar = null;

    this.startLine = startLine;

    updating = true;

    try {
        getSheetComboBox().removeAllItems();
        getSheetComboBox().setVisible(false);
        sheetLabel.setVisible(false);

        PreviewTableModel newModel = null;

        if (SupportedFileType.EXCEL.getExtension().equalsIgnoreCase(fileType)
                || SupportedFileType.OOXML.getExtension().equalsIgnoreCase(fileType)) {
            final int numberOfSheets = workbook.getNumberOfSheets();

            if (numberOfSheets == 0)
                throw new IllegalStateException("No sheet found in the workbook.");

            for (int i = 0; i < numberOfSheets; i++) {
                final Sheet sheet = workbook.getSheetAt(i);

                if (sheet.getPhysicalNumberOfRows() > 0)
                    getSheetComboBox().addItem(sheet);
            }

            if (getSheetComboBox().getItemCount() > 0)
                getSheetComboBox().setSelectedIndex(0);

            if (getSheetComboBox().getItemCount() > 1) {
                sheetLabel.setVisible(true);
                getSheetComboBox().setVisible(true);
            }

            /*
             * Load each sheet in the workbook.
             */
            if (getSheetComboBox().getItemCount() > 0) {
                final Sheet sheet = workbook.getSheetAt(0);
                updatePreviewTable(sheet);
            } else {
                throw new RuntimeException("No data found in the Excel sheets.");
            }
        } else {
            newModel = parseText(tempIs, delimiters, startLine);

            String sourceName;
            String[] urlParts = fileFullName.split("/");

            if (urlParts.length > 0 && !fileFullName.isEmpty())
                sourceName = urlParts[urlParts.length - 1];
            else
                sourceName = "Source Table";

            dataTypes = TypeUtil.guessDataTypes(newModel);
            types = TypeUtil.guessTypes(importType, newModel, dataTypes, null);
            listDelimiters = new String[newModel.getColumnCount()];

            updatePreviewTable(newModel, sourceName);
        }
    } finally {
        updating = false;
    }
}

From source file:org.databene.formats.xls.XLSUtil.java

License:Open Source License

public static void autoSizeColumns(Workbook workbook) {
    int sheetCount = workbook.getNumberOfSheets();
    for (int i = 0; i < sheetCount; i++) {
        Sheet sheet = workbook.getSheetAt(i);
        int firstRowNum = sheet.getFirstRowNum();
        if (firstRowNum >= 0) {
            Row firstRow = sheet.getRow(firstRowNum);
            for (int cellnum = firstRow.getFirstCellNum(); cellnum < firstRow.getLastCellNum(); cellnum++)
                sheet.autoSizeColumn(cellnum);
        }//from  ww w . j av a  2s  . c o m
    }
}

From source file:org.dbunit.dataset.excel.MyXlsDataSet.java

License:Open Source License

/**
 * Creates a new XlsDataSet object that loads the specified Excel document.
 *//*from  w w  w. java  2s  . co  m*/
public MyXlsDataSet(InputStream in) throws IOException, DataSetException {
    _tables = super.createTableNameMap();

    Workbook workbook;
    try {
        workbook = WorkbookFactory.create(in);
    } catch (InvalidFormatException e) {
        throw new IOException(e);
    }

    int sheetCount = workbook.getNumberOfSheets();
    for (int i = 0; i < sheetCount; i++) {
        ITable table = new MyXlsTable(workbook.getSheetName(i), workbook.getSheetAt(i));
        _tables.add(table.getTableMetaData().getTableName(), table);
    }
}