Example usage for org.apache.poi.ss.usermodel WorkbookFactory create

List of usage examples for org.apache.poi.ss.usermodel WorkbookFactory create

Introduction

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

Prototype

public static Workbook create(File file) throws IOException, EncryptedDocumentException 

Source Link

Document

Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and be readable.

Usage

From source file:org.cgiar.ccafs.marlo.utils.ReadExcelFile.java

License:Open Source License

public Object[][] readExcelFile(File file) {
    Object[][] data = null;/*w w w . j a  v  a 2s . c  o  m*/
    if (file != null) {
        try {
            InputStream fip = new FileInputStream(file);
            Workbook wb = WorkbookFactory.create(fip);
            Sheet sheet = wb.getSheetAt(0);
            Row firstRow = sheet.getRow(9);// fila del encabezado del template
            List<Row> rows = this.searchForEmptyRows(sheet);
            // totalRows = (sheet.getLastRowNum() - firstRow.getRowNum());
            totalRows = rows.size();
            totalColumns = firstRow.getLastCellNum();
            data = new Object[totalRows][totalColumns];
            for (int fila = 0; fila < rows.size(); fila++) {
                Row row = rows.get(fila);
                for (int col = 0; col < totalColumns; col++) {
                    Cell cell = row.getCell(col);
                    data[fila][col] = this.getCellData(cell);
                }

            }

        } catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
            e.printStackTrace();
        }
    }

    return data;

}

From source file:org.cgiar.ccafs.marlo.utils.ReadExcelFile.java

License:Open Source License

public boolean validarExcelFile(File file) {
    InputStream fip;//from w w w . j  a  va 2  s. c o  m
    boolean equal = true;
    try {
        fip = new FileInputStream(file);
        Workbook wb = WorkbookFactory.create(fip);
        List<String> header = this.getHeadersExcelFile(wb);
        if (header.size() == HEAD_TEMPLATE.length) {
            for (int i = 0; i < header.size(); i++) {
                if (!header.get(i).equals(HEAD_TEMPLATE[i])) {
                    equal = false;
                }
            }
        } else {
            equal = false;
        }

    } catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
        equal = false;
    }

    return equal;
}

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//from ww w.  j av 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.crud.emp.web.controller.EmpController.java

License:Apache License

private List<EmpDto> fileToDtoList(Part file, List<String> failureMessages)
        throws IllegalArgumentException, InvalidFormatException, IOException { // NOPMD
    // by/* w  ww  . j  a  v  a 2  s . co 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.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);//  w  w w. j  a v a2s  .c o 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);//from   w ww .j a va2 s. c  om
        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

/**
 * open document, create document graph and timeline in salt, print logging
 * infos, throw warning, if there are any problems while handling the
 * document/* w w  w . ja v  a2 s .c o  m*/
 * 
 * @param resource
 *            string of the document path
 */
private void readSpreadsheetResource(String resource) {
    getDocument().setDocumentGraph(SaltFactory.createSDocumentGraph());

    STimeline timeline = SaltFactory.createSTimeline();
    getDocument().getDocumentGraph().setTimeline(timeline);

    SpreadsheetImporter.logger.debug("Importing the file {}.", resource);
    SpreadsheetImporter.logger.info(resource);

    // get the excel files here
    InputStream excelFileStream;
    File excelFile;
    Workbook workbook = null;

    try {
        excelFile = new File(resource);
        excelFileStream = new FileInputStream(excelFile);
        workbook = WorkbookFactory.create(excelFileStream);
        workbook.close();

    } catch (IOException | EncryptedDocumentException | InvalidFormatException e) {
        SpreadsheetImporter.logger.warn("Could not open file '" + resource + "'.");
    }

    getPrimTextTiers(workbook, timeline);

}

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 ww  w .  ja v  a  2s. 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.ImportNetworkTableReaderTask.java

License:Open Source License

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

    monitor.setTitle("Loading network from table");
    monitor.setProgress(0.0);//from  ww  w  .j a va  2s  .  c  o m
    monitor.setStatusMessage("Loading network...");

    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?", e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    String networkName;

    if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) {
        Sheet sheet = workbook.getSheetAt(0);
        networkName = workbook.getSheetName(0);

        reader = new ExcelNetworkSheetReader(networkName, sheet, ntmp, this.nMap, this.rootNetwork);
    } else {
        networkName = this.inputName;
        reader = new NetworkTableReader(networkName, this.is, ntmp, this.nMap, this.rootNetwork);
    }
    loadNetwork(monitor);

    monitor.setProgress(1.0);
}

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

License:Open Source License

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

    monitor.setTitle("Loading network from table");
    monitor.setProgress(0.0);//  w  ww.  j  a va  2 s.co  m
    monitor.setStatusMessage("Loading network...");
    taskMonitor = monitor;
    int startLoadRowTemp;

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

    if (is != null)
        netReader = networkReaderManager.getReader(is, inputName);

    if (netReader == null)
        netReader = networkReaderManager.getReader(uri, inputName);

    if (netReader instanceof CombineReaderAndMappingTask) {
        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(new FileInputStream(tempFile));
            } catch (InvalidFormatException e) {
                //e.printStackTrace();
                throw new IllegalArgumentException("Could not read Excel file.  Maybe the file is broken?", e);
            } finally {

            }
        }

        netReader = null;
        if (startLoadRow > 0)
            startLoadRow--;
        startLoadRowTemp = startLoadRow;
        if (firstRowAsColumnNames)
            startLoadRowTemp = 0;

        previewPanel.setPreviewTable(workbook, fileType, tempFile.getAbsolutePath(),
                new FileInputStream(tempFile), 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 (indexColumnSourceInteraction > 0)
            indexColumnSourceInteraction--;

        if (indexColumnTargetInteraction > 0)
            indexColumnTargetInteraction--;

        if (indexColumnTypeInteraction > 0)
            indexColumnTypeInteraction--;

        ntmp = new NetworkTableMappingParameters(delimiters.getSelectedValues(),
                delimitersForDataList.getSelectedValue(), attributeNames, attributeTypes,
                previewPanel.getCurrentListDataTypes(), importFlag, indexColumnSourceInteraction,
                indexColumnTargetInteraction, indexColumnTypeInteraction, defaultInteraction, startLoadRow,
                null);

        if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
                || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) {
            Sheet sheet = workbook.getSheetAt(0);
            networkName = workbook.getSheetName(0);

            reader = new ExcelNetworkSheetReader(networkName, sheet, ntmp, this.nMap, this.rootNetwork);
        } else {
            networkName = this.inputName;
            reader = new NetworkTableReader(networkName, new FileInputStream(tempFile), ntmp, this.nMap,
                    this.rootNetwork);
        }
        loadNetwork(monitor);

        monitor.setProgress(1.0);
    } else {
        networkName = this.inputName;
        insertTasksAfterCurrentTask(netReader);
    }
}