Example usage for org.apache.poi.hssf.usermodel HSSFRow getLastCellNum

List of usage examples for org.apache.poi.hssf.usermodel HSSFRow getLastCellNum

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFRow getLastCellNum.

Prototype

@Override
public short getLastCellNum() 

Source Link

Document

Gets the index of the last cell contained in this row PLUS ONE.

Usage

From source file:com.cn.util.ExcelImport.java

/**
* ?2003excel/*w ww  .  j a  va 2  s .  c  o m*/
* @param file
* @return
*/
private static List<List<Object>> read2003Excel(InputStream inputStream) throws IOException {
    List<List<Object>> dataList = new ArrayList<>();
    HSSFWorkbook wb = new HSSFWorkbook(inputStream);
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row = null;
    HSSFCell cell = null;
    Object val = null;
    DecimalFormat df = new DecimalFormat("0");// ?
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// ?

    for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
        row = sheet.getRow(i);
        if (row == null) {
            continue;
        }
        List<Object> objList = new ArrayList<>();
        for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
            cell = row.getCell(j);
            if (cell == null) {
                val = null;
                objList.add(val);
                continue;
            }
            switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_STRING:
                val = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_NUMERIC:
                if ("@".equals(cell.getCellStyle().getDataFormatString())) {
                    val = df.format(cell.getNumericCellValue());
                } else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    val = df.format(cell.getNumericCellValue());
                } else {
                    val = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                }
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                val = cell.getBooleanCellValue();
                break;
            case HSSFCell.CELL_TYPE_BLANK:
                val = "";
                break;
            default:
                val = cell.toString();
                break;
            }
            objList.add(val);
        }
        dataList.add(objList);
    }
    return dataList;
}

From source file:com.cn.util.ExcelImport.java

/**
 * ?excel/*from  w ww .  j  a  va2  s. co m*/
 * @param file
 * @return
 * @throws IOException
 */
public static String[] readExcelHead(File file) throws IOException {
    HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row = null;
    HSSFCell cell = null;
    row = sheet.getRow(0);
    String[] buff = new String[row.getLastCellNum()];
    for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
        cell = row.getCell(i);
        buff[i] = cell.getStringCellValue();
    }
    return buff;
}

From source file:com.codequicker.quick.templates.source.adapters.ExcelSourceAdapter.java

License:Apache License

private void readOleBasedData(BufferedInputStream bufferedStream, Map<String, List<Map<String, String>>> data) {

    try {/*  ww  w. ja  va2 s  . c  o  m*/
        HSSFWorkbook workbook = new HSSFWorkbook(bufferedStream);

        int sheetCount = workbook.getNumberOfSheets();

        for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) {
            HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
            Cell cell = null;

            List<Map<String, String>> sheetData = new ArrayList<Map<String, String>>();

            int lastRowNumber = sheet.getLastRowNum();

            for (int rowIndex = 0; rowIndex <= lastRowNumber; rowIndex++) {
                HSSFRow row = sheet.getRow(rowIndex);
                if (row == null) {
                    continue;
                }

                Map<String, String> columnData = new HashMap<String, String>();

                for (int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) {
                    cell = row.getCell(cellIndex, Row.CREATE_NULL_AS_BLANK);
                    columnData.put("column" + (cellIndex + 1), cell.toString());
                }

                sheetData.add(columnData);
            }

            data.put("sheet" + (sheetIndex + 1), sheetData);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.dtrules.compiler.excel.util.ImportRuleSets.java

License:Apache License

/**
 * Looks for the value in some column, and returns that index.  This way we can be a bit more 
 * flexible in our format of the EDD./*from  w ww. j ava  2 s  .  c om*/
 * @param value
 * @param sheet
 * @param row
 * @return  the Index of the value, or -1 if not found.
 */
private int findvalue(String value, HSSFSheet sheet, int row) {
    HSSFRow theRow = sheet.getRow(row);
    if (theRow == null)
        return -1;
    for (int i = 0; i < theRow.getLastCellNum(); i++) {
        String v = getCellValue(sheet, row, i).trim();
        v = v.replaceAll(" ", "");
        if (v.equalsIgnoreCase(value))
            return i;
    }
    return -1;
}

From source file:com.efficio.fieldbook.web.nursery.service.impl.ExcelImportStudyServiceImpl.java

License:Open Source License

private int findColumn(HSSFSheet sheet, String cellValue) {
    int result = -1;
    if (cellValue != null) {
        HSSFRow row = sheet.getRow(0); //Encabezados
        int cells = row.getLastCellNum();
        for (int i = 0; i < cells; i++) {
            HSSFCell cell = row.getCell(i);
            if (cell.getStringCellValue().equals(cellValue)) {
                return i;
            }//from w ww . j a  va  2s .  c  o m
        }
    }
    return result;
}

From source file:com.eryansky.core.excelTools.ExcelUtils.java

License:Apache License

public static void copyRow(HSSFWorkbook destwb, HSSFRow dest, HSSFWorkbook srcwb, HSSFRow src) {
    if (src == null || dest == null)
        return;//  w  ww .  j a  v a  2  s.  co  m
    for (int i = 0; i <= src.getLastCellNum(); i++) {
        if (src.getCell(i) != null) {
            HSSFCell cell = dest.createCell(i);
            copyCell(destwb, cell, srcwb, src.getCell(i));
        }
    }

}

From source file:com.esd.cs.common.HExcelSheetParser.java

License:Open Source License

public List<List<Object>> getDatasInSheet(int sheetNumber) {
    List<List<Object>> result = new ArrayList<List<Object>>();
    // sheet//from   w  w w . ja v  a 2  s . c  o m
    HSSFSheet sheet = workbook.getSheetAt(sheetNumber);
    // sheet
    int rowCount = sheet.getLastRowNum();
    logger.info("found excel rows count:" + rowCount);
    if (rowCount < 1) {
        return result;
    }
    // ??row
    for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
        // 
        HSSFRow row = sheet.getRow(rowIndex);
        if (null != row) {
            List<Object> rowData = new ArrayList<Object>();
            // ?
            int cellCount = row.getLastCellNum();
            // ??cell
            for (int cellIndex = 0; cellIndex < cellCount; cellIndex++) {
                HSSFCell cell = row.getCell(cellIndex);
                // ??
                Object cellStr = this.getCellString(cell);

                rowData.add(cellStr);
            }
            result.add(rowData);
        }
    }

    return result;
}

From source file:com.etest.view.tq.itemanalysis.FileUploadWindow.java

void readContentFromExcelFile(File excelFile) {
    try {/*from   w  w  w.j a v a  2  s  .  c  om*/
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(excelFile));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(wb.getActiveSheetIndex());
        HSSFRow row;
        HSSFCell cell;

        boolean stop = false;
        boolean nonBlankRowFound;
        int s;
        HSSFRow lastRow = null;

        while (stop == false) {
            nonBlankRowFound = false;
            lastRow = sheet.getRow(sheet.getLastRowNum());
            for (s = lastRow.getFirstCellNum(); s <= lastRow.getLastCellNum(); s++) {
                cell = lastRow.getCell(s);
                if (cell != null && lastRow.getCell(s).getCellType() != HSSFCell.CELL_TYPE_BLANK) {
                    nonBlankRowFound = true;
                }
            }
            if (nonBlankRowFound == true) {
                stop = true;
            } else {
                sheet.removeRow(lastRow);
            }
        }

        int rows; // No of rows
        rows = sheet.getPhysicalNumberOfRows();

        int cols = 0; // No of columns
        int tmp = 0;

        // This trick ensures that we get the data properly even if it doesn't start from first few rows
        for (int i = 0; i < 10 || i < rows; i++) {
            row = sheet.getRow(i);
            if (row != null) {
                tmp = sheet.getRow(i).getPhysicalNumberOfCells();
                if (tmp > cols)
                    cols = tmp;
            }
        }

        List<ItemAnalysis> itemAnalysisList = new ArrayList<>();
        List<Character> answer;
        ItemAnalysis itemAnalysis = null;

        for (int c = 0; c < cols; c++) {
            itemAnalysis = new ItemAnalysis();
            answer = new ArrayList<>();
            for (int r = 0; r < rows; r++) {
                row = sheet.getRow(r);
                if (row == null || row.toString().isEmpty()) {
                    ShowErrorNotification.error("Remove all blank/empty rows after the last Item!");
                    return;
                } else {
                    //                   if(row != null){
                    cell = row.getCell(c);
                    if (cell == null || cell.toString().isEmpty()) {
                        ShowErrorNotification.error("Remove all blank/empty columns after the last student!");
                        return;
                    } else {
                        //                       if(cell != null){                           
                        if (c != 0) {
                            if (r == 0) {
                                itemAnalysis.setStudentNumber(cell.toString().trim());
                            } else {
                                answer.add(cell.toString().trim().charAt(0));
                            }
                        } else {
                            if (r != 0) {
                                totalItems++;
                            }
                        }
                    }
                }
            }
            if (c != 0) {
                itemAnalysis.setAnswer(answer);
                itemAnalysisList.add(itemAnalysis);
            }
        }

        if (tq.getCellItemIdByTQCoverageId(getTqCoverageId()).size() != totalItems) {
            ShowErrorNotification.error("Total Items do not MATCH!");
            totalItems = 0;
            return;
        }

        studentNoAndTotalScore = new HashMap<>();
        studentNoAndAnswer = new HashMap<>();
        totalItems = 1;
        new Thread() {

            @Override
            public void run() {
                totalData = itemAnalysisList.size();
                for (ItemAnalysis i : itemAnalysisList) {
                    try {
                        Thread.sleep(50);
                        studentNoAndTotalScore.put(i.getStudentNumber(), ItemAnalysisInterpretation
                                .getTotalScoresOfAllStudent(tqCoverageId, i.getAnswer()));
                        studentNoAndAnswer.put(i.getStudentNumber(), i.getAnswer());

                        getUI().access(new Runnable() {

                            @Override
                            public void run() {
                                if (totalItems < itemAnalysisList.size()) {
                                    analyze.setValue("Analyzing data.. "
                                            + CommonUtilities.roundOffToTwoDecimal((current / totalData) * 100)
                                            + "%");
                                    current++;
                                } else {
                                    analyze.setValue("Data analyzed... 100%");
                                    getLowerAndUpperGroupStudent(studentNoAndTotalScore);

                                    HorizontalLayout h = new HorizontalLayout();
                                    h.setWidth("100%");

                                    h.addComponent(viewTableProportion());
                                    h.addComponent(viewStudentsTotalScore());
                                    h.addComponent(approveItemAnalysis());
                                    v.addComponent(h);

                                    v.addComponent(itemAnalysisGridPanel());
                                }
                            }

                        });

                        totalItems++;
                    } catch (InterruptedException ex) {
                        Logger.getLogger(FileUploadWindow.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }

        }.start();
        UI.getCurrent().setPollInterval(500);
    } catch (IOException ex) {
        Logger.getLogger(TQItemAnalysisUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.frameworkset.platform.sanylog.util.POIExcelUtil.java

License:Open Source License

/**
 * ?Excel?MapList?Excel??Java.// www .ja v a2  s  .co  m
 * 
 * @param file
 * @return
 * @throws IOException
 */
public static List<Map<String, Object>> parseHSSFMapList(MultipartFile file) throws IOException {//
    POIFSFileSystem poiFs = new POIFSFileSystem(file.getInputStream());
    HSSFWorkbook wb = new HSSFWorkbook(poiFs);

    HSSFSheet sheet = wb.getSheetAt(0);

    int rowNum = sheet.getLastRowNum();
    HSSFRow titleRow = sheet.getRow(0);

    int colNum = titleRow.getLastCellNum();

    //?17
    List<String> titleList = new ArrayList<String>();
    for (int i = 0; i < colNum; i++) {
        String title = titleRow.getCell(i).getStringCellValue();
        titleList.add(trimTitle(title));
    }

    List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
    for (int i = 1; i <= rowNum; i++) {
        HSSFRow row = sheet.getRow(i);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        for (int j = 0; j < colNum; j++) {
            HSSFCell cell = row.getCell(j);
            if (cell != null) {
                switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC:
                    double d = cell.getNumericCellValue();
                    CellStyle style = cell.getCellStyle();
                    //?
                    if (HSSFDateUtil.isCellDateFormatted(cell) || (style != null
                            && (style.getDataFormat() == 57 || style.getDataFormat() == 58))) {
                        map.put(titleList.get(j), HSSFDateUtil.getJavaDate(d));
                    } else {
                        map.put(titleList.get(j), d);
                    }
                    break;

                default:
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    map.put(titleList.get(j), row.getCell(j).getStringCellValue());
                    break;
                }
            } else {
                map.put(titleList.get(j), null);
            }
        }
        mapList.add(map);
    }

    return mapList;
}

From source file:com.frameworkset.platform.util.POIExcelUtil.java

License:Open Source License

/**
 * ?/*from  w  w  w  .  j ava  2s . c o  m*/
 * 
 * @param uploadFileName
 * @return
 *         2015112
 */
public static List<String> getTitlesList(InputStream inputStream) throws Exception {
    // ?excel2003
    POIFSFileSystem poiFs = new POIFSFileSystem(inputStream);
    HSSFWorkbook wb = new HSSFWorkbook(poiFs);

    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow titleRow = sheet.getRow(0);
    int colNum = titleRow.getLastCellNum();

    // ?
    List<String> titleList = new ArrayList<String>();
    for (int i = 0; i < colNum; i++) {
        String title = titleRow.getCell(i).getStringCellValue();
        titleList.add(trimTitle(title));
    }

    return titleList;
}