Example usage for org.apache.poi.xssf.usermodel XSSFSheet removeRow

List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet removeRow

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFSheet removeRow.

Prototype

@Override
public void removeRow(Row row) 

Source Link

Document

Remove a row from this sheet.

Usage

From source file:com.photon.phresco.framework.commons.FrameworkUtil.java

License:Apache License

public boolean deleteTestSuitesFromXLSX(String filePath, String testSuiteName) {
    boolean hasTrue = false;
    Iterator<Row> rowIterator;
    try {//from   w  w w  .  jav  a  2  s. com
        FileInputStream myInput = new FileInputStream(filePath);

        OPCPackage opc = OPCPackage.open(myInput);

        XSSFWorkbook myWorkBook = new XSSFWorkbook(opc);
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
        rowIterator = mySheet.rowIterator();
        for (int i = 0; i <= 2; i++) {
            rowIterator.next();
        }

        while (rowIterator.hasNext()) {
            Row next = rowIterator.next();
            if (getValue(next.getCell(2)).equalsIgnoreCase(testSuiteName)) {
                mySheet.removeRow(next);
                int rowNum = next.getRowNum();
                int newNum = rowNum + 1;
                mySheet.shiftRows(newNum, mySheet.getLastRowNum(), -1);
                int numberOfSheets = myWorkBook.getNumberOfSheets();
                for (int j = 0; j < numberOfSheets; j++) {
                    XSSFSheet mySheet1 = myWorkBook.getSheetAt(j);
                    if (mySheet1.getSheetName().equalsIgnoreCase(testSuiteName)) {
                        myWorkBook.removeSheetAt(j);
                        hasTrue = true;
                        break;
                    }
                }
                myInput.close();
                FileOutputStream outFile = new FileOutputStream(filePath);
                myWorkBook.write(outFile);
                outFile.close();
                break;
            }
        }
    } catch (Exception e) {

    }

    return hasTrue;
}

From source file:com.photon.phresco.framework.commons.FrameworkUtil.java

License:Apache License

public boolean deleteTestCasesFromXLSX(String filePath, String testSuiteName, String testCaseId) {
    boolean hasTrue = false;
    List<TestCase> testCases = new ArrayList<TestCase>();
    TestCase tstCase = new TestCase();
    Iterator<Row> rowIterator;
    try {/* www . j a v a2 s  .co  m*/
        FileInputStream myInput = new FileInputStream(filePath);

        OPCPackage opc = OPCPackage.open(myInput);

        XSSFWorkbook myWorkBook = new XSSFWorkbook(opc);
        int numberOfSheets = myWorkBook.getNumberOfSheets();
        for (int j = 0; j < numberOfSheets; j++) {
            XSSFSheet mySheet = myWorkBook.getSheetAt(j);
            if (mySheet.getSheetName().equals(testSuiteName)) {
                rowIterator = mySheet.rowIterator();
                for (int i = 0; i <= 23; i++) {
                    rowIterator.next();
                }
                while (rowIterator.hasNext()) {
                    Row next = rowIterator.next();
                    if (testCaseId.equalsIgnoreCase(getValue(next.getCell(3)))) {
                        mySheet.removeRow(next);
                        int rowNum = next.getRowNum();
                        int newNum = rowNum + 1;
                        XSSFRow row = mySheet.getRow(newNum);
                        if (row != null) {
                            mySheet.shiftRows(newNum, mySheet.getLastRowNum(), -1);
                        }
                        hasTrue = true;
                        break;
                    }
                }
            }
        }
        if (hasTrue) {
            for (int j = 0; j < numberOfSheets; j++) {
                XSSFSheet myXSSFSheet = myWorkBook.getSheetAt(j);
                if (myXSSFSheet.getSheetName().equals(testSuiteName)) {
                    rowIterator = myXSSFSheet.rowIterator();
                    for (int i = 0; i <= 23; i++) {
                        rowIterator.next();
                    }
                    while (rowIterator.hasNext()) {
                        Row next = rowIterator.next();
                        TestCase createObject = readTest(next);
                        testCases.add(createObject);
                    }
                    float totalPass = 0;
                    float totalFail = 0;
                    float totalNotApplicable = 0;
                    float totalBlocked = 0;
                    int totalTestCases = testCases.size();
                    for (TestCase testCase : testCases) {
                        String testCaseStatus = testCase.getStatus();
                        if (testCaseStatus.equalsIgnoreCase("success")) {
                            totalPass = totalPass + 1;
                        } else if (testCaseStatus.equalsIgnoreCase("failure")) {
                            totalFail = totalFail + 1;
                        } else if (testCaseStatus.equalsIgnoreCase("notApplicable")) {
                            totalNotApplicable = totalNotApplicable + 1;
                        } else if (testCaseStatus.equalsIgnoreCase("blocked")) {
                            totalBlocked = totalBlocked + 1;
                        }
                    }

                    if (tstCase.getStatus().equalsIgnoreCase("success")) {
                        totalPass = totalPass - 1;
                    } else if (tstCase.getStatus().equalsIgnoreCase("failure")) {
                        totalFail = totalFail - 1;
                    } else if (tstCase.getStatus().equalsIgnoreCase("notApplicable")) {
                        totalNotApplicable = totalNotApplicable - 1;
                    } else if (tstCase.getStatus().equalsIgnoreCase("blocked")) {
                        totalBlocked = totalBlocked - 1;
                    }

                    XSSFSheet mySheet1 = myWorkBook.getSheetAt(0);
                    rowIterator = mySheet1.rowIterator();
                    for (int i = 0; i <= 2; i++) {
                        rowIterator.next();
                    }
                    while (rowIterator.hasNext()) {
                        Row next1 = rowIterator.next();
                        if (StringUtils.isNotEmpty(getValue(next1.getCell(2)))
                                && !getValue(next1.getCell(2)).equalsIgnoreCase("Total")) {
                            TestSuite createObject = createObject(next1);
                            if (StringUtils.isNotEmpty(tstCase.getTestCaseId())
                                    && createObject.getName().equals(testSuiteName)) {
                                updateIndex(totalPass, totalFail, totalNotApplicable, totalBlocked, next1,
                                        totalTestCases, "delete");
                            }
                        }
                    }
                }
            }

            myInput.close();
            FileOutputStream outFile = new FileOutputStream(filePath);
            myWorkBook.write(outFile);
            outFile.close();
        }
    } catch (Exception e) {

    }

    return hasTrue;
}

From source file:ik1004labb5.DAOHundExcel.java

@Override
public void delete(int id) {
    XSSFWorkbook workbook = getExcelWorkbook();
    XSSFSheet worksheet = workbook.getSheetAt(0);
    DataFormatter df = new DataFormatter();
    //Loopa igenom nollkolumnen fr att frska hitta en matchning p ID

    for (Row row : worksheet) {
        if (df.formatCellValue(row.getCell(0)).equalsIgnoreCase(Integer.toString(id))) {
            if (row.getRowNum() == worksheet.getLastRowNum()) {
                worksheet.removeRow(row);
                break;
            } else {
                worksheet.shiftRows(row.getRowNum() + 1, worksheet.getLastRowNum(), -1);
            }/* w ww  . java  2  s  .c om*/
            break;
        }
    }
    saveToExcel(workbook);
}

From source file:org.openelis.bean.DataViewReportBean.java

License:Open Source License

/**
 * Creates and returns a workbook that gets converted to an Excel file; each
 * row in the workbook shows fields from some part of a sample and analytes
 * and values//from  w w  w.j a  va2  s.  c o  m
 * 
 * @param results
 *        the list of VOs containing result info to be shown
 * @param auxiliary
 *        the list of VOs containing aux data info to be shown
 * @param noResAux
 *        the list of VOs containing info to be shown when both results and
 *        aux data are excluded
 * @param testAnaResMap
 *        the map containing result analytes and values selected by the
 *        user; if an analyte or value is not in the map, the result is not
 *        shown
 * @param auxFieldValMap
 *        the map containing aux data analytes and values selected by the
 *        user; if an analyte or value is not in the map, the aux data is
 *        not shown
 * @param moduleName
 *        the name of a security module for the logged in user; the module's
 *        clause is used to restrict the fetched data to specific records
 *        e.g. organizations
 * @param showReportableColumnsOnly
 *        if true, only reportable column analytes are shown
 * @param headers
 *        the list of labels for the column headers
 * @param data
 *        the VO containing the user's choices for the data shown e.g. the
 *        meta keys for selected columns and "include" and "exclude" flags
 * @param smMap
 *        the map that provides the data for the columns belonging to
 *        various parts of a sample e.g. domain, organization, project etc.
 * @param status
 *        the percent completion in this ReportStatus is updated every time
 *        a new row is added to the workbook
 */
private XSSFWorkbook getWorkbook(List<DataViewResultVO> results, List<DataViewResultVO> auxiliary,
        List<DataViewResultVO> noResAux, HashMap<Integer, HashSet<String>> testAnaResMap,
        HashMap<Integer, HashSet<String>> auxFieldValMap, String moduleName, boolean showReportableColumnsOnly,
        ArrayList<String> headers, DataView1VO data, HashMap<Integer, SampleManager1> smMap,
        ReportStatus status) throws Exception {
    boolean excludeOverride, excludeRes, excludeAux, samOverridden, anaOverridden, addRow;
    int i, j, resIndex, auxIndex, noResAuxIndex, rowIndex, numRes, numAux, numNoResAux, lastCol, currCol;
    Integer samId, prevSamId, resAccNum, auxAccNum, itemId, anaId, prevAnaId, anaIndex;
    String value;
    SampleManager1 sm;
    XSSFWorkbook wb;
    XSSFSheet sheet;
    DataViewResultVO res;
    ResultViewDO rowRes, colRes;
    Row currRow, prevRow;
    RowData rd;
    Cell cell;
    ArrayList<Integer> maxChars;
    ArrayList<ResultViewDO> smResults;
    HashMap<String, Integer> colAnaMap;
    HashMap<Integer, HashSet<String>> anaValMap;

    numRes = results == null ? 0 : results.size();
    numAux = auxiliary == null ? 0 : auxiliary.size();
    numNoResAux = noResAux == null ? 0 : noResAux.size();
    excludeOverride = "Y".equals(data.getExcludeResultOverride());
    excludeRes = "Y".equals(data.getExcludeResults());
    excludeAux = "Y".equals(data.getExcludeAuxData());

    resIndex = 0;
    auxIndex = 0;
    noResAuxIndex = 0;
    lastCol = 0;
    currCol = 0;
    rowIndex = 1;
    prevSamId = null;
    prevAnaId = null;
    anaIndex = null;
    samOverridden = false;
    anaOverridden = false;
    currRow = null;
    prevRow = null;
    sm = null;
    wb = new XSSFWorkbook();
    sheet = wb.createSheet();
    colAnaMap = new HashMap<String, Integer>();
    maxChars = new ArrayList<Integer>();
    rd = new RowData();

    status.setMessage(Messages.get().report_genDataView());
    status.setPercentComplete(0);
    session.setAttribute("DataViewReportStatus", status);

    /*
     * the lists of results and aux data are iterated through until there
     * are no more elements left in each of them to read from
     */
    while (resIndex < numRes || auxIndex < numAux || noResAuxIndex < numNoResAux) {
        /*
         * the user wants to stop the report
         */
        if (ReportStatus.Status.CANCEL.equals(status.getStatus())) {
            status.setMessage(Messages.get().report_stopped());
            return null;
        }

        status.setPercentComplete(
                100 * (resIndex + auxIndex + noResAuxIndex) / (numRes + numAux + numNoResAux));
        res = null;
        anaValMap = null;
        value = null;
        if (excludeRes && excludeAux) {
            res = noResAux.get(noResAuxIndex++);
        } else {
            if (resIndex < numRes && auxIndex < numAux) {
                resAccNum = results.get(resIndex).getSampleAccessionNumber();
                auxAccNum = auxiliary.get(auxIndex).getSampleAccessionNumber();
                /*
                 * if this result's accession number is less than or equal
                 * to this aux data's, add a row for this result, otherwise
                 * add a row for the aux data; this makes sure that the
                 * results for a sample are shown before the aux data;
                 * accession numbers are compared instead of sample ids
                 * because the former is the field shown in the report and
                 * not the latter
                 */
                if (resAccNum <= auxAccNum) {
                    res = results.get(resIndex++);
                    anaValMap = testAnaResMap;
                } else {
                    res = auxiliary.get(auxIndex++);
                    anaValMap = auxFieldValMap;
                }
            } else if (resIndex < numRes) {
                /*
                 * no more aux data left to show
                 */
                res = results.get(resIndex++);
                anaValMap = testAnaResMap;
            } else if (auxIndex < numAux) {
                /*
                 * no more results left to show
                 */
                res = auxiliary.get(auxIndex++);
                anaValMap = auxFieldValMap;
            }
        }

        samId = res.getSampleId();
        itemId = res.getSampleItemId();
        anaId = res.getAnalysisId();

        if (!samId.equals(prevSamId)) {
            /*
             * don't show any data for this sample if it's overridden and
             * such samples are excluded; whether the sample is overridden
             * is checked even if such samples are not excluded because
             * overridden result values are not shown in the report
             */
            sm = smMap.get(samId);
            samOverridden = false;
            if ((getSampleQAs(sm) != null)) {
                for (SampleQaEventViewDO sqa : getSampleQAs(sm)) {
                    if (Constants.dictionary().QAEVENT_OVERRIDE.equals(sqa.getTypeId())) {
                        samOverridden = true;
                        if (excludeOverride)
                            prevSamId = samId;
                        break;
                    }
                }
            }
        }

        if (samOverridden && excludeOverride) {
            prevSamId = samId;
            continue;
        }

        /*
         * don't show any data for this analysis if it's overridden and such
         * analyses are excluded; whether the analysis is overridden is
         * checked even if such analyses are not excluded because overridden
         * values are not shown in the report
         */
        if (anaId != null) {
            if (!anaId.equals(prevAnaId)) {
                anaOverridden = false;
                if ((getAnalysisQAs(sm) != null)) {
                    for (AnalysisQaEventViewDO aqa : getAnalysisQAs(sm)) {
                        if (aqa.getAnalysisId().equals(anaId)
                                && Constants.dictionary().QAEVENT_OVERRIDE.equals(aqa.getTypeId())) {
                            anaOverridden = true;
                            if (excludeOverride)
                                break;
                        }
                    }
                }
            }
            if (anaOverridden && excludeOverride) {
                prevSamId = samId;
                prevAnaId = anaId;
                continue;
            }
        }

        if (anaValMap != null) {
            /*
             * show this result or aux data only if its value was selected
             * by the user
             */
            value = getValue(anaValMap, res.getAnalyteId(), res.getValue(), res.getTypeId());
            if (value == null) {
                prevSamId = samId;
                prevAnaId = anaId;
                continue;
            }
        }

        currRow = sheet.createRow(rowIndex++);

        /*
         * fill the passed row's cells for all columns except the ones for
         * analytes and values
         */
        setBaseCells(sm, itemId, anaId, rd, data.getColumns(), moduleName != null, wb, currRow, maxChars);

        if (value != null) {
            /*
             * this row is for either a result or aux data; show the analyte
             */
            cell = currRow.createCell(currRow.getPhysicalNumberOfCells());
            setCellValue(cell, res.getAnalyteName(), null);
            setMaxChars(cell.getColumnIndex(), res.getAnalyteName(), maxChars, null);
            cell = currRow.createCell(currRow.getPhysicalNumberOfCells());
            if (anaId != null && !excludeRes) {
                /*
                 * this row is for a result; show the value only if the
                 * analysis and sample are not overridden
                 */
                if (!anaOverridden && !samOverridden)
                    setCellValue(cell, value, null);
                setMaxChars(cell.getColumnIndex(), cell.getStringCellValue(), maxChars, null);

                /*
                 * if this analyte has column analytes, show them in the
                 * header and their values in the columns; results for a
                 * sample can be null if it has no results with values but
                 * has aux data with values and aux data is not excluded
                 */
                smResults = getResults(sm);
                if (smResults != null) {
                    for (i = 0; i < smResults.size(); i++) {
                        rowRes = smResults.get(i);
                        if (!res.getId().equals(rowRes.getId()))
                            continue;
                        j = i + 1;
                        if (j < smResults.size() && "Y".equals(smResults.get(j).getIsColumn())) {
                            /*
                             * this analyte has column analytes; "lastCol"
                             * is the right-most column in the workbook; if
                             * an analyte doesn't have a column yet, that
                             * column will be added after "lastCol";
                             * "currCol" keeps track of the current column
                             */
                            if (lastCol == 0)
                                lastCol = currRow.getPhysicalNumberOfCells();

                            currCol = currRow.getPhysicalNumberOfCells();
                            while (j < smResults.size()) {
                                colRes = smResults.get(j++);
                                if ("N".equals(colRes.getIsColumn()))
                                    break;
                                if (showReportableColumnsOnly && "N".equals(colRes.getIsReportable()))
                                    continue;
                                anaIndex = colAnaMap.get(colRes.getAnalyte());

                                /*
                                 * if this column analyte's name is not
                                 * found in the map, create a new column and
                                 * start adding values in it; set the value
                                 * in this cell if the analyte is shown in
                                 * this column; if the analyte is not shown
                                 * in this column, find the column in which
                                 * it is shown and set the value
                                 */
                                if (anaIndex == null) {
                                    anaIndex = lastCol++;
                                    colAnaMap.put(colRes.getAnalyte(), anaIndex);
                                    headers.add(colRes.getAnalyte());
                                    setMaxChars(cell.getColumnIndex(), colRes.getAnalyte(), maxChars, null);
                                    cell = currRow.createCell(anaIndex);
                                } else if (anaIndex == currCol) {
                                    cell = currRow.createCell(currCol++);
                                } else {
                                    cell = currRow.createCell(anaIndex);
                                }

                                /*
                                 * set the value if the analysis and sample
                                 * are not overridden
                                 */
                                if (!anaOverridden && !samOverridden)
                                    setCellValue(cell, getValue(colRes.getValue(), colRes.getTypeId()), null);
                                setMaxChars(cell.getColumnIndex(), cell.getStringCellValue(), maxChars, null);
                            }
                        }
                    }
                }
            } else {
                /*
                 * this row is for an aux data; show the value
                 */
                setCellValue(cell, value, null);
                setMaxChars(cell.getColumnIndex(), value, maxChars, null);
            }
        }

        prevAnaId = anaId;
        prevSamId = samId;

        /*
         * an empty row can't be created and then added to the sheet, it has
         * to be obtained from the sheet; thus it has to be removed if it
         * shouldn't be shown because it has the same data as the previous
         * row in all cells; this can happen if e.g. a user selects only
         * container and sample type but all sample items in a sample have
         * the same values for these fields
         */
        if (isSameDataInRows(currRow, prevRow)) {
            sheet.removeRow(currRow);
            rowIndex--;
        } else {
            prevRow = currRow;
        }
    }

    /*
     * add the header row and set the header labels for all columns
     */
    setHeaderCells(sheet, wb, headers, maxChars);

    /*
     * make each column wide enough to show the longest string in it; the
     * width for each column is set as the maximum number of characters in
     * that column multiplied by 256; this is because the default width of
     * one character is 1/256 units in Excel
     */
    for (i = 0; i < maxChars.size(); i++)
        sheet.setColumnWidth(i, maxChars.get(i) * 256);

    return wb;
}