Example usage for org.apache.poi.ss.usermodel Row getPhysicalNumberOfCells

List of usage examples for org.apache.poi.ss.usermodel Row getPhysicalNumberOfCells

Introduction

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

Prototype

int getPhysicalNumberOfCells();

Source Link

Document

Gets the number of defined cells (NOT number of cells in the actual row!).

Usage

From source file:au.com.onegeek.lambda.parser.Excel2SeleniumParser.java

License:Apache License

private void parse(InputStream stream)
        throws CannotCompileException, NotFoundException, CannotCreateTestClassException,
        InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    logger.debug("Parsing...");

    if (this.dataMap != null && this.tests != null) {
        return;/*from ww w.  j a  va  2 s .c om*/
    }

    this.dataMap = new ArrayList<Map<String, Object>>();
    this.tests = new ArrayList<Class<Test>>();

    Workbook workbook = null;
    try {
        workbook = new XSSFWorkbook(stream);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    logger.debug("workbook" + workbook.toString());

    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        Sheet sheet = workbook.getSheetAt(i);
        if (sheet.getSheetName().startsWith("data")) {
            // parse key\value pairs
            HashMap<String, Object> map = new HashMap<String, Object>();
            dataMap.add(map);
            boolean done = false;

            Row row = sheet.getRow(sheet.getFirstRowNum());

            while (!done && row != null && row.getPhysicalNumberOfCells() > 0) {
                // TODO: parse numerics correctly (i.e. don't add decimal points if not needed)
                String key = (String) XslxUtil.objectFrom(workbook, row.getCell(0));
                String value = null;
                try {
                    value = (String) XslxUtil.objectFrom(workbook, row.getCell(1));
                    logger.debug("Adding variable to map: " + key + ":" + value);
                    map.put(key, value);

                    row = sheet.getRow(row.getRowNum() + 1);

                    if (row == null || (row.getRowNum() == sheet.getLastRowNum() + 1)) {
                        done = true;
                    }
                } catch (NullPointerException e) {
                    //throw new CannotCreateVariableException("No value found for variable '" + key + "' in dataset: " + sheet.getSheetName());
                    done = true;
                }
            }
        }
    }

    JavassistTestBuilderImpl builder = JavassistTestBuilderImpl.getInstance();

    // Parse Test sheets into Test objects
    for (int s = 0; s < workbook.getNumberOfSheets(); s++) {
        Sheet sheet = workbook.getSheetAt(s);
        int i = 0;

        // Ignore data sheets
        if (sheet.getSheetName().startsWith("suite")) {

            int maxRows = sheet.getPhysicalNumberOfRows();
            int currentRow = sheet.getFirstRowNum();
            logger.debug("Nr rows in sheet: " + maxRows);

            // Create Test Class
            String testCaseName = "Test" + Excel2SeleniumParser.toCamelCase(sheet.getSheetName());
            logger.debug("Creating Test class with name: " + testCaseName);
            builder.makeTestClass(testCaseName, this.dataMap);
            boolean testCaseInProgress = false;
            boolean dataProviderAdded = false;

            // Get First row, containing the test name and the data to be injected
            while (i < maxRows) {
                logger.debug("i: " + i);
                logger.debug("currentRow: " + currentRow);
                Row row = sheet.getRow(currentRow);
                TestCommand command = null;

                // Check for empty row
                if (row != null && row.getPhysicalNumberOfCells() != 0) {
                    i++;

                    // Get Cells
                    Iterator<Cell> iterator = row.cellIterator();
                    while (iterator.hasNext()) {
                        Cell cell = iterator.next();
                        String cellValue = (cell == null || cell.toString() == "") ? ""
                                : XslxUtil.objectFrom(workbook, cell).toString();
                        logger.debug("Cell: " + cellValue);

                        if (cellValue.startsWith("test")) {
                            logger.debug("Test case found: " + cellValue + ". Creating Test Case");

                            // Create new Test CASE
                            try {
                                builder.addTest(cellValue);
                                testCaseInProgress = true;
                                dataProviderAdded = false;
                            } catch (CannotModifyTestMethodException e) {
                                e.printStackTrace();
                                throw new CannotCreateTestClassException(
                                        "Could not create Test Class as there was a variable not found in test assertion. Embedded exception: "
                                                + e.getMessage());
                            } catch (VariableNotFoundException e) {
                                e.printStackTrace();
                                throw new CannotCreateTestClassException(
                                        "Could not create Test Class as there was a variable not found in test assertion. Embedded exception: "
                                                + e.getMessage());
                            }
                            break;
                        } else {
                            if (command == null & !cellValue.equals("")) {
                                logger.debug("Command found: " + cellValue + ". Creating new TestCommand");
                                command = new TestCommand(cellValue);
                            } else if (!cellValue.equals("")) {
                                logger.debug("Command argument found: " + cellValue);
                                command.addParameter(cellValue);
                            }
                        }
                    }
                } else {
                    // Blank row could mean a test case has just been completed
                    // Complete last test case by adding a data provider
                    if (testCaseInProgress && !dataProviderAdded) {
                        try {
                            logger.debug("In Progress Test Case now being closed off and added to class...");
                            builder.addDataProvider();
                            dataProviderAdded = true;
                            logger.debug("In Progress Test Case now closed off!");
                        } catch (CannotCreateDataProviderException e) {
                            throw new CannotCreateTestClassException(
                                    "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                            + e.getMessage());
                        }
                    }
                }
                try {
                    if (command != null) {
                        logger.debug("Adding command to method");
                        builder.appendTestToLastMethod(command);
                    }
                } catch (CannotModifyTestMethodException e) {
                    throw new CannotCreateTestClassException("Unable to add Test Case '" + command.toString()
                            + "' to Test Class. Embedded exception: " + e.getMessage());
                } catch (VariableNotFoundException e) {
                    throw new CannotCreateTestClassException("Unable to add Test Case '" + command.toString()
                            + "' to Test Class as a variable was not found. Embedded exception: "
                            + e.getMessage());
                }
                currentRow++;
            }
            // Blank row could mean a test case has just been completed
            // Complete last test case by adding a data provider
            logger.debug(
                    "End of rows...Checking if In Progress Test Case now being closed off and added to class...");
            if (testCaseInProgress && !dataProviderAdded) {
                logger.debug(" In Progress Test Case now being closed off and added to class...");
                try {
                    builder.addDataProvider();
                    dataProviderAdded = true;
                    logger.debug("In Progress Test Case now closed off!");
                } catch (CannotCreateDataProviderException e) {
                    throw new CannotCreateTestClassException(
                            "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                    + e.getMessage());
                }
            }

            if (testCaseInProgress) {
                logger.debug("Generating class file");
                try {
                    this.tests.add(builder.getCreatedClass());
                } catch (CannotModifyTestMethodException e) {
                    e.printStackTrace();
                    throw new CannotCreateTestClassException(
                            "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                    + e.getMessage());
                }
                testCaseInProgress = false;
            }
        }
    }

    try {
        stream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.info("Looking at our classes...");

    // Look at the Test Objects
    for (Class<Test> clazz : tests) {
        logger.info("Class: " + clazz.getName());
        for (Method m : clazz.getMethods()) {
            logger.info("Method: " + m);
            if (m.getName().equalsIgnoreCase("testRetailDataProvider")) {
                logger.info("invoking data provider");
                Test test = clazz.newInstance();
                Object[][] data = (Object[][]) m.invoke(test);
                for (Object[] obs : data) {
                    for (Object o : obs) {
                        logger.info("data value: " + o);
                    }
                }
            }
        }
    }
}

From source file:browsermator.com.MyTable.java

MyTable(String csvFile) {
    DataFile = csvFile;/*www  .  j a v  a  2 s.c  om*/
    DataTable = new JTable();
    myEntries = new ArrayList<>();
    File filecheck = new File(csvFile);
    if (filecheck.isAbsolute()) {

        String[] left_right_side_of_dot = csvFile.split("\\.");
        String file_extension = left_right_side_of_dot[left_right_side_of_dot.length - 1];

        switch (file_extension) {
        case "xls":
            try {
                FileInputStream file = new FileInputStream(new File(DataFile));

                HSSFWorkbook workbook = new HSSFWorkbook(file);

                //Get first sheet from the workbook
                HSSFSheet sheet = workbook.getSheetAt(0);

                //Iterate through each rows from first sheet
                Iterator<Row> rowIterator = sheet.iterator();

                int number_of_cells = 0;
                while (rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    int number_of_thesecells = row.getPhysicalNumberOfCells();
                    if (number_of_thesecells > number_of_cells) {
                        number_of_cells = number_of_thesecells;
                    }
                }
                Iterator<Row> rowIterator2 = sheet.iterator();
                while (rowIterator2.hasNext()) {
                    Row row = rowIterator2.next();

                    String[] myRow = new String[number_of_cells];
                    Iterator<Cell> cellIterator = row.cellIterator();

                    int cell_index = 0;
                    while (cellIterator.hasNext()) {

                        Cell cell = cellIterator.next();

                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_BOOLEAN:
                            Boolean boolvalue = cell.getBooleanCellValue();
                            String cellvalue = "false";
                            if (boolvalue) {
                                cellvalue = "true";
                            } else

                                myRow[cell_index] = cellvalue;
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            myRow[cell_index] = Double.toString(cell.getNumericCellValue());
                            break;
                        case Cell.CELL_TYPE_STRING:
                            myRow[cell_index] = cell.getRichStringCellValue().getString();
                            break;
                        case Cell.CELL_TYPE_BLANK:
                            myRow[cell_index] = "";
                            break;
                        case Cell.CELL_TYPE_ERROR:
                            myRow[cell_index] = "";
                            break;
                        case Cell.CELL_TYPE_FORMULA:
                            myRow[cell_index] = cell.getCellFormula();
                            break;
                        }
                        cell_index++;
                    }
                    if (cell_index != number_of_cells) {
                        for (int x = cell_index; x < number_of_cells; x++)
                            myRow[cell_index] = "";
                    }

                    myEntries.add(myRow);
                }

                file.close();
            }

            catch (Exception e) {
                System.out.println("Error occurred while reading XLS file: " + e.toString());
            }
            break;
        case "xlsx":
            try {
                FileInputStream file = new FileInputStream(new File(DataFile));

                XSSFWorkbook workbook = new XSSFWorkbook(file);

                //Get first sheet from the workbook
                XSSFSheet sheet = workbook.getSheetAt(0);

                //Iterate through each rows from first sheet
                Iterator<Row> rowIterator = sheet.iterator();

                int number_of_cells = 0;
                while (rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    int number_of_thesecells = row.getPhysicalNumberOfCells();
                    if (number_of_thesecells > number_of_cells) {
                        number_of_cells = number_of_thesecells;
                    }
                }
                Iterator<Row> rowIterator2 = sheet.iterator();
                while (rowIterator2.hasNext()) {
                    Row row = rowIterator2.next();

                    String[] myRow = new String[number_of_cells];
                    Iterator<Cell> cellIterator = row.cellIterator();

                    int cell_index = 0;
                    while (cellIterator.hasNext()) {

                        Cell cell = cellIterator.next();

                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_BOOLEAN:
                            Boolean boolvalue = cell.getBooleanCellValue();
                            String cellvalue = "false";
                            if (boolvalue) {
                                cellvalue = "true";
                            } else

                                myRow[cell_index] = cellvalue;
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            myRow[cell_index] = Double.toString(cell.getNumericCellValue());
                            break;
                        case Cell.CELL_TYPE_STRING:
                            myRow[cell_index] = cell.getRichStringCellValue().getString();
                            break;
                        case Cell.CELL_TYPE_BLANK:
                            myRow[cell_index] = "";
                            break;
                        case Cell.CELL_TYPE_ERROR:
                            myRow[cell_index] = "";
                            break;
                        case Cell.CELL_TYPE_FORMULA:
                            myRow[cell_index] = cell.getCellFormula();
                            break;
                        }
                        cell_index++;
                    }
                    if (cell_index != number_of_cells) {
                        for (int x = cell_index; x < number_of_cells; x++)
                            myRow[cell_index] = "";
                    }

                    myEntries.add(myRow);
                }

                file.close();
            }

            catch (Exception ex) {
                System.out.print("Exception during XLSX import: " + ex.toString());
            }

            break;
        case "csv":
            try {
                CSVFileReader = new CSVReader(new FileReader(DataFile), ',', '"', '\0');
                myEntries = CSVFileReader.readAll();
            } catch (Exception e) {

            }

        }

        columnnames = (String[]) myEntries.get(0);
        DefaultTableModel tableModel = new DefaultTableModel(columnnames, myEntries.size() - 1);
        rowcount = tableModel.getRowCount();
        this.number_of_records = rowcount;
        for (int x = 0; x < rowcount + 1; x++) {

            int columnnumber = 0;
            if (x > 0) {
                for (String thiscellvalue : (String[]) myEntries.get(x)) {
                    tableModel.setValueAt(thiscellvalue, x - 1, columnnumber);
                    columnnumber++;
                }
            }

        }

        DataTable = new JTable(tableModel);

        int number_of_rows = DataTable.getRowCount();
        if (number_of_rows < 20) {
            DataTable.setPreferredScrollableViewportSize(
                    new Dimension(1200, number_of_rows * DataTable.getRowHeight()));
        }

    } else {

        columnnames[0] = "Stored URL List:" + csvFile;
        DefaultTableModel tableModel = new DefaultTableModel(columnnames, 0);

        DataTable = new JTable(tableModel);
        DataTable.getColumnModel().getColumn(0).setPreferredWidth(200);
        DataTable.setPreferredScrollableViewportSize(new Dimension(20, 0));

    }

}

From source file:co.foldingmap.data.ExcelDataConnector.java

License:Open Source License

/**
 * Parses the cells from the workbook into a TabulaData class.
 * /*from  ww  w  .ja v a 2s. c o  m*/
 * @param workingSheet
 * @return 
 */
private TabularData parseWorkbook() {
    ArrayList<ArrayList<DataCell>> rows;
    ArrayList<DataCell> cells;
    int columnIndex, currentCellColumnIndex, lastCellcolumnIndex;
    int numberOfCells, previousRowLength, rowIndex;
    TabularData dataFile;

    dataFile = new TabularData();
    previousRowLength = 0;
    rows = new ArrayList<ArrayList<DataCell>>();
    rowIndex = -1;

    try {
        for (Row row : workingSheet) {
            cells = new ArrayList<DataCell>();
            columnIndex = row.getFirstCellNum();
            lastCellcolumnIndex = -1;
            numberOfCells = row.getPhysicalNumberOfCells();
            rowIndex++;

            //add blank cells
            for (int i = 0; i < columnIndex; i++)
                cells.add(new DataCell(""));

            for (Cell cell : row) {
                currentCellColumnIndex = cell.getColumnIndex();

                if ((lastCellcolumnIndex + 1) == currentCellColumnIndex) {
                    cells.add(getCellText(cell));
                    lastCellcolumnIndex = currentCellColumnIndex;
                } else {
                    for (int i = (lastCellcolumnIndex + 1); i < currentCellColumnIndex; i++) {
                        cells.add(new DataCell(""));
                    }

                    cells.add(getCellText(cell));
                    lastCellcolumnIndex = currentCellColumnIndex;
                }
            }

            //if this row does not match the length of the last one, add blank cells
            for (int i = (lastCellcolumnIndex + 1); i <= previousRowLength; i++) {
                cells.add(new DataCell(""));
                lastCellcolumnIndex = i;
            }

            previousRowLength = lastCellcolumnIndex;
            rows.add(cells);
        }
    } catch (Exception e) {
        Logger.log(Logger.ERR, "Error in ExcelDataConnector.parseWorkbook(Sheet) - " + e);
    }

    dataFile.loadData(rows);

    return dataFile;
}

From source file:com.abixen.platform.service.businessintelligence.multivisualisation.service.impl.parser.ExcelParserServiceImpl.java

License:Open Source License

private List<DataFileColumn> getColumns(Row headerRow, Sheet sheet, Boolean readFirstColumnAsColumnName) {
    List<DataFileColumn> dataFileColumns = new ArrayList<>();
    for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
        DataFileColumn dataFileColumn = new DataFileColumn();
        int firstDataRow = readFirstColumnAsColumnName ? headerRowIndex + 1 : headerRowIndex;
        DataValueType columnType = getColumnTypeAsDataValueType(sheet.getRow(firstDataRow).getCell(i), i);
        dataFileColumn.setDataValueType(columnType);
        dataFileColumn.setPosition(i);//from  w  w  w .  j a v  a2 s.  c  om
        dataFileColumn.setName(getColumnNames(sheet, i, readFirstColumnAsColumnName));
        dataFileColumn.setValues(getValues(sheet, i, columnType, firstDataRow));
        dataFileColumns.add(dataFileColumn);
    }
    return dataFileColumns;
}

From source file:com.abixen.platform.service.businessintelligence.multivisualisation.service.impl.parser.ExcelParserServiceImpl.java

License:Open Source License

private boolean validate(FileParserMessage<DataFileColumn> msg, Row headerRow, Sheet sheet,
        Boolean readFirstColumnAsColumnName) {
    for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
        int firstDataRow = readFirstColumnAsColumnName ? headerRowIndex + 1 : headerRowIndex;
        Cell columnCell = sheet.getRow(firstDataRow).getCell(i);
        if (columnCell == null) {
            msg.addFileParseError(new FileParseError(1, String.format(
                    "[Line %d, column %d] Cell is empty. Column can't be validated", headerRowIndex + 1, i)));
        } else {/*from w w w.j  av  a  2s  .c  o m*/
            DataValueType columnType = getColumnTypeAsDataValueType(columnCell, i);
            for (int j = firstDataRow; j < sheet.getPhysicalNumberOfRows(); j++) {
                Cell cell = sheet.getRow(j).getCell(i);
                if (cell == null) {
                    msg.addFileParseError(
                            new FileParseError(1, String.format("[Line %d, column %d] Cell is empty", j, i)));
                } else {
                    if (!columnType.equals(getColumnTypeAsDataValueType(cell, i))) {
                        msg.addFileParseError(new FileParseError(1, String.format(
                                "[Line %d, column %d] Cell type is diffrent that first cell in this column", j,
                                i)));
                    }
                }
            }
        }
    }
    return msg.getFileParseErrors().isEmpty();
}

From source file:com.adobe.acs.commons.mcp.impl.ProcessErrorReportExcelServlet.java

License:Apache License

@SuppressWarnings("squid:S3776")
protected Workbook createSpreadsheet(ManagedProcess report) {
    Workbook wb = new XSSFWorkbook();

    String name = report.getName();
    for (char ch : new char[] { '\\', '/', '*', '[', ']', ':', '?' }) {
        name = StringUtils.remove(name, ch);
    }//w  w w.j  av a  2 s  .  co  m
    Sheet sheet = wb.createSheet(name);
    sheet.createFreezePane(0, 1, 0, 1);

    Row headerRow = sheet.createRow(0);
    CellStyle headerStyle = createHeaderStyle(wb);
    CellStyle dateStyle = wb.createCellStyle();
    CreationHelper createHelper = wb.getCreationHelper();
    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyy/mm/dd h:mm:ss"));

    for (String columnName : Arrays.asList("Time", "Path", "Error", "Stack trace")) {
        Cell headerCell = headerRow.createCell(headerRow.getPhysicalNumberOfCells());
        headerCell.setCellValue(columnName);
        headerCell.setCellStyle(headerStyle);
    }

    Collection<ArchivedProcessFailure> rows = report.getReportedErrorsList();
    //make rows, don't forget the header row
    for (ArchivedProcessFailure error : rows) {
        Row row = sheet.createRow(sheet.getPhysicalNumberOfRows());
        Cell c;

        c = row.createCell(0);
        c.setCellValue(error.time);
        c.setCellStyle(dateStyle);
        c = row.createCell(1);
        c.setCellValue(error.nodePath);
        c = row.createCell(2);
        c.setCellValue(error.error);
        c = row.createCell(3);
        c.setCellValue(error.stackTrace);
    }
    autosize(sheet, 4);
    sheet.setAutoFilter(new CellRangeAddress(0, 1 + rows.size(), 0, 3));
    return wb;
}

From source file:com.blackducksoftware.tools.commonframework.standard.protex.report.template.TemplateReader.java

License:Apache License

/**
 * Called by the TemplateReader./*from  www. j a  v a 2 s .c  om*/
 *
 * @param sheet
 *            the sheet
 * @param templateSheet
 *            the template sheet
 * @throws Exception
 *             the exception
 */
private void populateColumns(Sheet sheet, TemplateSheet templateSheet) throws Exception {
    Map<String, TemplateColumn> columnMap = templateSheet.getColumnMap();
    Row headerRow = sheet.getRow(0);
    if (headerRow == null) {
        throw new Exception("No header row found! Please create one.");
    }

    Row styleRow = sheet.getRow(1);
    if (styleRow == null) {
        throw new Exception(
                "Sheet name " + templateSheet.getSheetName() + ": No style row found! Please create one.");
    }

    for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
        TemplateColumn column = new TemplateColumn();
        Cell headerCell = headerRow.getCell(i);
        Cell styleCell = styleRow.getCell(i);

        if (headerCell == null) {
            throw new Exception("The following column appears to be empty: " + i);
        }

        if (styleCell == null) {
            throw new Exception("The following style position is not defined: " + i);
        }

        String columnName = headerCell.getStringCellValue();
        // We want to use the style cell (row below) as the header will
        // always be text.
        Integer cellType = styleCell.getCellType();

        column.setColumnPos(i);
        column.setCellStyle(styleCell.getCellStyle());
        column.setColumnName(columnName);
        column.setCellType(cellType);
        if (cellType == Cell.CELL_TYPE_FORMULA) {
            column.setCellFormula(styleCell.getCellFormula());
        }

        columnMap.put(columnName, column);
    }

    populateColumnMappings(columnMap);
}

From source file:com.blackducksoftware.tools.commonframework.standard.protex.report.template.TemplateReader.java

License:Apache License

/**
 * Populate columns.//from   w w  w  .  j  ava 2 s . com
 *
 * @param sheet
 *            the sheet
 * @param templateSheet
 *            the template sheet
 * @param columnNames
 *            the column names
 * @throws Exception
 *             the exception
 */
private void populateColumns(Sheet sheet, TemplateSheet templateSheet, List<String> columnNames)
        throws Exception {
    Map<String, TemplateColumn> columnMap = templateSheet.getColumnMap();
    Row headerRow = sheet.getRow(0);

    if (headerRow == null) {
        throw new Exception("No header row found!");
    }

    for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
        Cell headerCell = headerRow.getCell(i);
        if (headerCell == null) {
            throw new Exception("The following header column is empty: " + i);
        }

        String headerName = headerCell.getStringCellValue().trim();
        if (columnNames.contains(headerName)) {
            log.info("Processing user specified column: " + headerName);
            TemplateColumn column = new TemplateColumn();

            column.setColumnPos(i);
            column.setColumnName(headerName);

            columnMap.put(headerName, column);
        }
    }
}

From source file:com.blackducksoftware.tools.commonframework.standard.protex.report.template.TemplateWriterTest.java

License:Apache License

/**
 * Test column count.//from   w  w w. ja v  a 2s. co  m
 */
@Test
public void testColumnCount() {
    Sheet sheet = outputBook.getSheet(TEST_SHEET_NAME);
    Row testRow = sheet.getRow(1);

    int cellCount = testRow.getPhysicalNumberOfCells();

    Assert.assertEquals(3, cellCount);

}

From source file:com.cn.controller.CommonController.java

/**
 * ?/*from  ww  w .  java 2  s.c om*/
 *
 * @param beanPackage
 * @param className
 * @param fileName
 * @return
 * @throws Exception
 */
public ArrayList<Object> importData(String beanPackage, String className, String fileName) throws Exception {
    //???
    Class objClass = Class.forName(beanPackage + className);
    Field[] fields = objClass.getDeclaredFields();
    ArrayList<Field> accessFields = new ArrayList<>();
    ArrayList<String> fieldDes = new ArrayList<>();

    for (Field field : fields) {
        if (field.isAnnotationPresent(FieldDescription.class)) {
            FieldDescription description = field.getAnnotation(FieldDescription.class);
            if (description.operate().compareTo("import") == 0) {
                fieldDes.add(description.description());
                accessFields.add(field);
            }
        }
    }

    //?, ?Excel?
    InputStream inputStream = null;
    File file = new File(fileName);
    inputStream = new FileInputStream(file);
    Sheet sheet;
    if (fileName.endsWith(".xls")) {
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
        sheet = workbook.getSheetAt(0);
    } else if (fileName.endsWith(".xlsx")) {
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        sheet = workbook.getSheetAt(0);
    } else {
        logger.info("?Excel!");
        return null;
    }

    Row headerRow = sheet.getRow(0);
    //????, ???
    //System.out.println("cells num:" + headerRow.getPhysicalNumberOfCells() + ",des size:" + fieldDes.size());
    if (headerRow == null || headerRow.getPhysicalNumberOfCells() != fieldDes.size()) {
        //json = Units.objectToJson(-1, "???, ?, ???", null);
        return null;
    }

    //?????
    int[] templateDataIndex = new int[fieldDes.size()];
    for (int i = 0; i < fieldDes.size(); i++) {
        Cell cell = headerRow.getCell(i);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        String fieldName = cell.getStringCellValue();
        if (fieldDes.indexOf(fieldName) != -1) {
            templateDataIndex[fieldDes.indexOf(fieldName)] = i;
        } else {
            return null;
        }
    }

    ArrayList<Object> result = new ArrayList<>();
    //??, List
    for (int i = 1; i <= sheet.getPhysicalNumberOfRows(); i++) {
        Row row = sheet.getRow(i);
        if (row == null) {
            continue;
        }
        if (Units.isEmptyRowForExcel(row)) {
            continue;
        }

        Object object = objClass.newInstance();
        for (int j = 0; j < accessFields.size(); j++) {
            Field field = accessFields.get(j);
            field.setAccessible(true);
            Cell cell = row.getCell(templateDataIndex[j]);
            if (field.getType() == int.class) {
                if (cell == null) {
                    field.set(object, 0);
                } else {
                    if (Units.strIsEmpty(Units.getStringCellValue(cell))) {
                        field.set(object, 0);
                    } else {
                        field.set(object, Double.valueOf(Units.getStringCellValue(cell)).intValue());
                    }
                }
            } else if (field.getType() == float.class) {
                if (cell == null) {
                    field.set(object, 0);
                } else {
                    if (Units.strIsEmpty(Units.getStringCellValue(cell))) {
                        field.set(object, 0);
                    } else {
                        field.set(object, Double.valueOf(Units.getStringCellValue(cell)).floatValue());
                    }
                }
            } else if (field.getType() == double.class) {
                if (cell == null) {
                    field.set(object, 0);
                } else {
                    if (Units.strIsEmpty(Units.getStringCellValue(cell))) {
                        field.set(object, 0);
                    } else {
                        field.set(object, Double.valueOf(Units.getStringCellValue(cell)));
                    }
                }
            } else if (field.getType() == boolean.class) {
                if (cell == null) {
                    field.set(object, false);
                } else {
                    if (Units.strIsEmpty(Units.getStringCellValue(cell))) {
                        field.set(object, false);
                    } else {
                        field.set(object, Boolean.valueOf(Units.getStringCellValue(cell)));
                    }
                }
            } else {
                if (cell == null) {
                    field.set(object, "");
                } else {
                    field.set(object, Units.getStringCellValue(cell));
                }

            }
        }

        result.add(object);
    }

    return result;
}