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

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

Introduction

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

Prototype

void removeSheetAt(int index);

Source Link

Document

Removes sheet at the given index

Usage

From source file:br.ufal.cideei.util.count.SummaryBuilder.java

License:Open Source License

public static void buildSummary(String splShortName)
        throws InvalidFormatException, FileNotFoundException, IOException {

    // final String userHomeFolder = System.getProperty("user.home").substring(3);
    String userHomeFolder = "C:\\tst";
    final String output = userHomeFolder + File.separator + "summ.xls";
    File outputFile = new File(output);
    Workbook outputWorkbook;
    if (!outputFile.exists()) {
        outputFile.createNewFile();// w  w  w  .j ava 2  s .  co m
        outputWorkbook = new HSSFWorkbook();
    } else {
        FileInputStream inputFileStream = new FileInputStream(outputFile);
        outputWorkbook = WorkbookFactory.create(inputFileStream);
    }

    {
        List<String> referencesForRDA3 = new ArrayList<String>();
        List<String> referencesForUVA3 = new ArrayList<String>();
        List<String> referencesForRDA2 = new ArrayList<String>();
        List<String> referencesForUVA2 = new ArrayList<String>();
        String fileName = "fs-" + splShortName + ".xls";
        String filePath = userHomeFolder + File.separator;
        String fullFileName = filePath + File.separator + "fs-" + splShortName + ".xls";
        Workbook workbook = WorkbookFactory.create(new FileInputStream(new File(fullFileName)));
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            Row headerRow = sheet.getRow(0);
            for (Cell cell : headerRow) {
                String stringCellValue = cell.getStringCellValue();
                if (stringCellValue.equals("rd")) {
                    Row sumRow = sheet.getRow(sheet.getLastRowNum() - 1);
                    Cell sumCell = sumRow.getCell(i);
                    CellReference sumCellRef = new CellReference(sumCell);
                    String cellRefForAnotherSheet = "\'" + filePath + "[" + fileName + "]Sheet" + i + "\'!"
                            + sumCellRef.formatAsString();
                    referencesForRDA2.add(cellRefForAnotherSheet);
                } else if (stringCellValue.equals("uv")) {
                    Row sumRow = sheet.getRow(sheet.getLastRowNum() - 1);
                    Cell sumCell = sumRow.getCell(i);
                    CellReference sumCellRef = new CellReference(sumCell);
                    String cellRefForAnotherSheet = "\'" + filePath + "[" + fileName + "]Sheet" + i + "\'!"
                            + sumCellRef.formatAsString();
                    referencesForUVA2.add(cellRefForAnotherSheet);
                } else if (stringCellValue.equals("rd (a3)")) {
                    Row sumRow = sheet.getRow(sheet.getLastRowNum() - 1);
                    Cell sumCell = sumRow.getCell(i);
                    CellReference sumCellRef = new CellReference(sumCell);
                    String cellRefForAnotherSheet = "\'" + filePath + "[" + fileName + "]Sheet" + i + "\'!"
                            + sumCellRef.formatAsString();
                    referencesForRDA3.add(cellRefForAnotherSheet);
                } else if (stringCellValue.equals("uv (a3)")) {
                    Row sumRow = sheet.getRow(sheet.getLastRowNum() - 1);
                    Cell sumCell = sumRow.getCell(i);
                    CellReference sumCellRef = new CellReference(sumCell);
                    String cellRefForAnotherSheet = "\'" + filePath + "[" + fileName + "]Sheet" + i + "\'!"
                            + sumCellRef.formatAsString();
                    referencesForUVA3.add(cellRefForAnotherSheet);
                }
            }
        }
        if (outputWorkbook.getSheet(splShortName) != null) {
            outputWorkbook.removeSheetAt(outputWorkbook.getSheetIndex(splShortName));
        }
        Sheet outputSheet = outputWorkbook.createSheet(splShortName);
        Row RDA2Row = outputSheet.createRow(0);
        RDA2Row.createCell(0).setCellValue("RD A2");
        for (int i = 0; i < referencesForRDA2.size(); i++) {
            Cell createdCell = RDA2Row.createCell(i + 1);
            System.out.println(referencesForRDA2.get(i));
            createdCell.setCellType(Cell.CELL_TYPE_FORMULA);
            createdCell.setCellValue(referencesForRDA2.get(i));
        }
        Row UVA2Row = outputSheet.createRow(1);
        UVA2Row.createCell(0).setCellValue("UV A2");
        for (int i = 0; i < referencesForUVA2.size(); i++) {
            Cell createdCell = UVA2Row.createCell(i + 1);
            createdCell.setCellFormula(referencesForUVA2.get(i));
        }
        Row RDA3Row = outputSheet.createRow(2);
        RDA3Row.createCell(0).setCellValue("RD A3");
        for (int i = 0; i < referencesForRDA3.size(); i++) {
            Cell createdCell = RDA3Row.createCell(i + 1);
            createdCell.setCellFormula(referencesForRDA3.get(i));
        }
        Row UVA3Row = outputSheet.createRow(3);
        UVA3Row.createCell(0).setCellValue("UV A3");
        for (int i = 0; i < referencesForUVA3.size(); i++) {
            Cell createdCell = UVA3Row.createCell(i + 1);
            createdCell.setCellFormula(referencesForUVA3.get(i));
        }
    }
    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
    outputWorkbook.write(fileOutputStream);
    fileOutputStream.close();
}

From source file:cn.afterturn.easypoi.cache.ExcelCache.java

License:Apache License

public static Workbook getWorkbook(String url, Integer[] sheetNums, boolean needAll) {
    InputStream is = null;/*  w ww .ja  v  a 2  s. com*/
    List<Integer> sheetList = Arrays.asList(sheetNums);
    try {
        is = POICacheManager.getFile(url);
        Workbook wb = WorkbookFactory.create(is);
        // sheet
        if (!needAll) {
            for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
                if (!sheetList.contains(i)) {
                    wb.removeSheetAt(i);
                }
            }
        }
        return wb;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return null;
}

From source file:cn.afterturn.easypoi.excel.export.template.ExcelExportOfTemplateUtil.java

License:Apache License

public Workbook createExcelCloneByTemplate(TemplateExportParams params,
        Map<Integer, List<Map<String, Object>>> map) {
    // step 1. ??
    if (params == null || map == null || StringUtils.isEmpty(params.getTemplateUrl())) {
        throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }/*from  www .  j a  v a 2 s. com*/
    Workbook wb = null;
    // step 2. ?Excel,??
    try {
        this.teplateParams = params;
        wb = ExcelCache.getWorkbook(teplateParams.getTemplateUrl(), teplateParams.getSheetNum(), true);
        int oldSheetNum = wb.getNumberOfSheets();
        List<String> oldSheetName = new ArrayList<>();
        for (int i = 0; i < oldSheetNum; i++) {
            oldSheetName.add(wb.getSheetName(i));
        }
        // KEY?
        List<Map<String, Object>> mapList;
        List<Integer> sheetNumList = new ArrayList<>();
        sheetNumList.addAll(map.keySet());
        Collections.sort(sheetNumList);

        //???
        for (Integer sheetNum : sheetNumList) {
            mapList = map.get(sheetNum);
            for (int i = mapList.size(); i > 0; i--) {
                wb.cloneSheet(sheetNum);
            }
        }
        for (int i = 0; i < oldSheetName.size(); i++) {
            wb.removeSheetAt(wb.getSheetIndex(oldSheetName.get(i)));
        }
        // ?
        setExcelExportStyler(
                (IExcelExportStyler) teplateParams.getStyle().getConstructor(Workbook.class).newInstance(wb));
        // step 3. ??
        int sheetIndex = 0;
        for (Integer sheetNum : sheetNumList) {
            mapList = map.get(sheetNum);
            for (int i = mapList.size() - 1; i >= 0; i--) {
                tempCreateCellSet.clear();
                if (mapList.get(i).containsKey(SHEET_NAME)) {
                    wb.setSheetName(sheetIndex, mapList.get(i).get(SHEET_NAME).toString());
                }
                parseTemplate(wb.getSheetAt(sheetIndex), mapList.get(i), params.isColForEach());
                sheetIndex++;
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
    return wb;
}

From source file:com.nc.common.utils.ExcelUtil.java

License:Open Source License

/**
 * <pre>/*w w w  . j a  v a  2s.c o m*/
 * 1.  : POI Util
 * 2.  : Excel ? ? (? ?), ?    ?? ?
 * </pre>
 *
 * @method Name : readWriteExcel
 * @param response, codeList, serviceType, templateFile
 * @return none
 * @throws Exception
 * 
 */
public static void readWriteExcel(HttpServletResponse response, List<Map<String, Object>> codeList,
        String serviceType, String templateFile) throws Exception {
    OutputStream fileOut = null;

    /* ?   ?   */

    File wbfile = new File(templateFile);
    Workbook wb = null;
    FileInputStream file = null;

    try {
        file = new FileInputStream(wbfile);

        wb = new HSSFWorkbook(file); /* WorkbookFactory.create(file); */

        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            wb.removeSheetAt(wb.getNumberOfSheets() - 1);
        }

        /* Sheet ?, ? , ?   ?  ?  */
        /*   ?*/
        /* ?  : wb = createWorkBook(wb, "sheet Name", "dataList", "header column List");*/

    } catch (Exception e) {
        e.printStackTrace();

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= Excel File Reading ... Error : [{}] =", e);
            log.debug(
                    "==========================================================================================");
        }

        throw new NCException("ExcelUtil > readWriteExcel ?");
    } finally {
        /* ? ??  */
        file.close();
        wb.close();
    }

    String fileName = serviceType + ".xlsm";

    /* ?  */
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

    /* , to file */
    fileOut = response.getOutputStream();
    wb.write(fileOut);
    fileOut.close();
    fileOut.flush();
}

From source file:com.opendoorlogistics.core.tables.io.PoiIO.java

License:Open Source License

public static ODLDatastoreAlterable<ODLTableAlterable> importExcel(InputStream stream, ExecutionReport report) {
    //tmpFileBugFix();

    ODLDatastoreAlterable<ODLTableAlterable> ds = ODLFactory.createAlterable();

    Workbook wb = null;
    try {//from   w w  w. j ava2s .  c  om
        wb = WorkbookFactory.create(stream);

        String author = getAuthor(wb);
        if (author != null && Strings.equalsStd(author, AppConstants.ORG_NAME)) {
            ds.setFlags(ds.getFlags() | ODLDatastore.FLAG_FILE_CREATED_BY_ODL);
        }

    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    // look for the schema; remove it from the workbook to simplify the later workbook updating code
    // (the schema gets held by the datastore structure anyway)
    SchemaSheetInformation info = null;
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);
        if (Strings.equalsStd(sheet.getSheetName(), SCHEMA_SHEET_NAME)) {
            info = importSchemaTables(sheet, report);
            wb.removeSheetAt(i);
            break;
        }
    }

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);
        ODLTableAlterable table = ds.createTable(sheet.getSheetName(), -1);
        importSheet(table, sheet, info != null ? info.schema : null, false);
    }

    return ds;
}

From source file:com.opendoorlogistics.studio.LoadedDatastore.java

License:Open Source License

private void updateWorkbookWithModifications(Workbook wb, ExecutionReport report) {
    // parse the original tables; these will be held in the datastore with the same index as the sheet
    int nbOriginal = originalLoadedDs.getTableCount();
    if (nbOriginal != wb.getNumberOfSheets()) {
        throw new RuntimeException();
    }/*from  www.  j a  v  a  2s .c  om*/

    ArrayList<ODLTableReadOnly> oldOnesToReadd = new ArrayList<>();
    for (int i = nbOriginal - 1; i >= 0; i--) {
        ODLTableReadOnly originalTable = originalLoadedDs.getTableAt(i);
        ODLTableReadOnly newTable = ds.getTableByImmutableId(originalTable.getImmutableId());

        if (newTable == null) {
            // table was deleted
            wb.removeSheetAt(i);
        } else if (DatastoreComparer.isSame(originalTable, newTable, DatastoreComparer.CHECK_ALL) == false) {
            Sheet sheet = wb.getSheetAt(i);

            boolean sameStructure = DatastoreComparer.isSameStructure(originalTable, newTable,
                    DatastoreComparer.CHECK_ALL);
            if (sameStructure) {
                // re-write all values but skip the header row
                int nbOversized = 0;
                for (int iRow = 0; iRow < newTable.getRowCount(); iRow++) {
                    int iTargetRow = iRow + 1;
                    Row row = sheet.getRow(iTargetRow);
                    if (row == null) {
                        row = sheet.createRow(iTargetRow);
                    }

                    int nc = newTable.getColumnCount();
                    for (int col = 0; col < nc; col++) {
                        Cell cell = row.getCell(col);
                        if (cell != null && cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                            // don't set the value of formula cells...
                            continue;
                        }
                        if (cell == null) {
                            cell = row.createCell(col);
                        }

                        String sval = TableUtils.getValueAsString(newTable, iRow, col);
                        if (sval != null && sval.length() > PoiIO.MAX_CHAR_COUNT_IN_EXCEL_CELL) {
                            nbOversized++;
                        }
                        cell.setCellValue(sval);
                    }
                }

                // delete any rows after the last row (including 1 for the header)
                int lastOKRow = newTable.getRowCount();
                while (sheet.getLastRowNum() > lastOKRow) {
                    sheet.removeRow(sheet.getRow(sheet.getLastRowNum()));
                }

                if (nbOversized > 0 && report != null) {
                    report.log(PoiIO.getOversizedWarningMessage(nbOversized, newTable.getName()));
                    ;
                }

            } else {
                // delete and replace. replace after parsing all original tables as we can get table name conflicts
                wb.removeSheetAt(i);
                oldOnesToReadd.add(newTable);
            }

        }

    }

    // re-add any totally replaced tables
    for (ODLTableReadOnly table : oldOnesToReadd) {
        Sheet sheet = wb.createSheet(table.getName());
        if (sheet != null) {
            PoiIO.exportTable(sheet, table, report);
        }
    }

    // add new tables at the end
    for (int i = 0; i < ds.getTableCount(); i++) {
        ODLTableReadOnly newTable = ds.getTableAt(i);
        if (originalLoadedDs.getTableByImmutableId(newTable.getImmutableId()) == null) {
            // new table...
            Sheet sheet = wb.createSheet(newTable.getName());
            if (sheet != null) {
                PoiIO.exportTable(sheet, newTable, report);
            }
        }

    }
}

From source file:com.perceptive.epm.perkolcentral.bl.ExcelReportBL.java

public FileInputStream generateAllEmployeeTeamWiseReport(File file, Boolean isScrumTeam)
        throws ExceptionWrapper {
    try {/*from ww  w .j  a va  2 s .  c  o m*/
        FileInputStream inp = new FileInputStream(file);
        //InputStream inp = new FileInputStream("workbook.xlsx");

        Workbook wb = WorkbookFactory.create(inp);
        int iSheetCounter = 1;
        for (Integer groupID : employeeBL.getAllEmployeesKeyedByGroupId().keySet()) {
            GroupBO groupBO = groupsBL.getAllGroups().get(groupID);
            if (isScrumTeam && !groupBO.getRallyGroup())
                continue;
            if (!isScrumTeam && groupBO.getRallyGroup())
                continue;

            Sheet sheet = wb.cloneSheet(0);
            wb.setSheetName(wb.getSheetIndex(sheet), groupBO.getGroupName());
            //wb.setSheetName(iSheetCounter,groupBO.getGroupName());

            int iRowCounter = 1;
            for (EmployeeBO employeeBO : employeeBL.getAllEmployeesKeyedByGroupId().get(groupID)) {
                Row row = sheet.getRow(iRowCounter);
                if (row == null)
                    row = sheet.createRow(iRowCounter);
                Cell cell = row.getCell(0);
                if (cell == null)
                    cell = row.createCell(0);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getEmployeeId());

                cell = row.getCell(1);
                if (cell == null)
                    cell = row.createCell(1);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getEmployeeUid());

                cell = row.getCell(2);
                if (cell == null)
                    cell = row.createCell(2);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getEmployeeName());

                cell = row.getCell(3);
                if (cell == null)
                    cell = row.createCell(3);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getEmail());

                cell = row.getCell(4);
                if (cell == null)
                    cell = row.createCell(4);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getManager());

                cell = row.getCell(5);
                if (cell == null)
                    cell = row.createCell(5);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getMobileNumber());

                cell = row.getCell(6);
                if (cell == null)
                    cell = row.createCell(6);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getExtensionNum());

                cell = row.getCell(7);
                if (cell == null)
                    cell = row.createCell(7);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getWorkspace());

                if (isScrumTeam) {
                    cell = row.getCell(8);
                    if (cell == null)
                        cell = row.createCell(8);
                    setCellBorder(wb, cell);
                    cell.setCellValue(employeeBO.getSpecificRoleInScrumTeam());
                }

                iRowCounter = iRowCounter + 1;
            }
        }
        iSheetCounter = iSheetCounter + 1;
        wb.removeSheetAt(0);
        FileOutputStream fileOut = new FileOutputStream(file);
        wb.write(fileOut);
        fileOut.close();
        return new FileInputStream(file);
    } catch (Exception ex) {
        throw new ExceptionWrapper(ex);
    }

}

From source file:com.perceptive.epm.perkolcentral.bl.ExcelReportBL.java

public FileInputStream generateLicenseReport(File file) throws ExceptionWrapper {
    try {//from  w ww  .  jav a 2 s  .  c  o  m
        FileInputStream inp = new FileInputStream(file);
        //InputStream inp = new FileInputStream("workbook.xlsx");

        Workbook wb = WorkbookFactory.create(inp);
        HashMap<String, ArrayList<String>> licenseInfoKeyedByLicenseName = licensesBL.getLicenseRelatedInfo();
        //Create The Summary Sheet
        Sheet sheetSummary = wb.getSheetAt(1);
        int iSummaryRowCounter = 1;
        for (String licenseType : licenseInfoKeyedByLicenseName.keySet()) {

            Row row = sheetSummary.getRow(iSummaryRowCounter);
            if (row == null)
                row = sheetSummary.createRow(iSummaryRowCounter);
            Cell cell = row.getCell(0);
            if (cell == null)
                cell = row.createCell(0);
            setCellBorder(wb, cell);
            cell.setCellValue(licenseType);

            row = sheetSummary.getRow(iSummaryRowCounter);
            if (row == null)
                row = sheetSummary.createRow(iSummaryRowCounter);
            cell = row.getCell(1);
            if (cell == null)
                cell = row.createCell(1);
            setCellBorder(wb, cell);
            cell.setCellValue(Double.parseDouble(licenseInfoKeyedByLicenseName.get(licenseType).get(0)));
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);

            row = sheetSummary.getRow(iSummaryRowCounter);
            if (row == null)
                row = sheetSummary.createRow(iSummaryRowCounter);
            cell = row.getCell(2);
            if (cell == null)
                cell = row.createCell(2);
            setCellBorder(wb, cell);
            cell.setCellValue(Double.parseDouble(licenseInfoKeyedByLicenseName.get(licenseType).get(1)));
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);

            row = sheetSummary.getRow(iSummaryRowCounter);
            if (row == null)
                row = sheetSummary.createRow(iSummaryRowCounter);
            cell = row.getCell(3);
            if (cell == null)
                cell = row.createCell(3);
            setCellBorder(wb, cell);
            cell.setCellValue(Double.parseDouble(licenseInfoKeyedByLicenseName.get(licenseType).get(0))
                    - Double.parseDouble(licenseInfoKeyedByLicenseName.get(licenseType).get(1)));
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);

            iSummaryRowCounter = iSummaryRowCounter + 1;
        }
        int iSheetCounter = 1;

        for (String licenseType : licenseInfoKeyedByLicenseName.keySet()) {
            Sheet sheet = wb.cloneSheet(0);
            wb.setSheetName(wb.getSheetIndex(sheet), licenseType);
            CellReference cellReference = new CellReference("B1");
            Row row = sheet.getRow(cellReference.getRow());
            Cell cell = row.getCell(cellReference.getCol());
            if (cell == null)
                cell = row.createCell(cellReference.getCol());
            setCellBorder(wb, cell);
            cell.setCellValue(Double.parseDouble(licenseInfoKeyedByLicenseName.get(licenseType).get(0)));
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);

            cellReference = new CellReference("B2");
            row = sheet.getRow(cellReference.getRow());
            cell = row.getCell(cellReference.getCol());
            if (cell == null)
                cell = row.createCell(cellReference.getCol());
            setCellBorder(wb, cell);
            cell.setCellValue(Double.parseDouble(licenseInfoKeyedByLicenseName.get(licenseType).get(1)));
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);

            cellReference = new CellReference("B3");
            row = sheet.getRow(cellReference.getRow());
            cell = row.getCell(cellReference.getCol());
            if (cell == null)
                cell = row.createCell(cellReference.getCol());
            setCellBorder(wb, cell);
            cell.setCellValue(Double.parseDouble(licenseInfoKeyedByLicenseName.get(licenseType).get(0))
                    - Double.parseDouble(licenseInfoKeyedByLicenseName.get(licenseType).get(1)));
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);

            ArrayList<EmployeeBO> allEmployees = new ArrayList<EmployeeBO>(
                    employeeBL.getAllEmployees().values());
            final String selectedLicenseTypeName = licenseType;
            CollectionUtils.filter(allEmployees, new Predicate() {
                @Override
                public boolean evaluate(Object o) {
                    EmployeeBO emp = (EmployeeBO) o;
                    if (CollectionUtils.exists(emp.getLicenses(), new Predicate() {
                        @Override
                        public boolean evaluate(Object o) {
                            return ((LicenseBO) o).getLicenseTypeName()
                                    .equalsIgnoreCase(selectedLicenseTypeName); //To change body of implemented methods use File | Settings | File Templates.
                        }
                    }))
                        return true;
                    else
                        return false;
                }
            });

            int iRowCounter = 5;
            for (EmployeeBO employeeBO : allEmployees) {
                row = sheet.getRow(iRowCounter);
                if (row == null)
                    row = sheet.createRow(iRowCounter);
                cell = row.getCell(0);
                if (cell == null)
                    cell = row.createCell(0);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getEmployeeId());

                cell = row.getCell(1);
                if (cell == null)
                    cell = row.createCell(1);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getEmployeeUid());

                cell = row.getCell(2);
                if (cell == null)
                    cell = row.createCell(2);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getEmployeeName());

                cell = row.getCell(3);
                if (cell == null)
                    cell = row.createCell(3);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getEmail());

                cell = row.getCell(4);
                if (cell == null)
                    cell = row.createCell(4);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getManager());

                cell = row.getCell(5);
                if (cell == null)
                    cell = row.createCell(5);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getMobileNumber());

                cell = row.getCell(6);
                if (cell == null)
                    cell = row.createCell(6);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getExtensionNum());

                cell = row.getCell(7);
                if (cell == null)
                    cell = row.createCell(7);
                setCellBorder(wb, cell);
                cell.setCellValue(employeeBO.getWorkspace());

                iRowCounter = iRowCounter + 1;
            }
        }
        iSheetCounter = iSheetCounter + 1;
        wb.removeSheetAt(0);
        FileOutputStream fileOut = new FileOutputStream(file);
        wb.write(fileOut);
        fileOut.close();
        return new FileInputStream(file);
    } catch (Exception ex) {
        throw new ExceptionWrapper(ex);
    }

}

From source file:com.qihang.winter.poi.cache.ExcelCache.java

License:Apache License

public static Workbook getWorkbook(String url, Integer[] sheetNums, boolean needAll) {
    InputStream is = null;/*from  w  w  w.  j a  v  a2s  . c  o  m*/
    List<Integer> sheetList = Arrays.asList(sheetNums);
    try {
        is = com.qihang.winter.poi.cache.manager.POICacheManager.getFile(url);
        Workbook wb = WorkbookFactory.create(is);
        // sheet
        if (!needAll) {
            for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
                if (!sheetList.contains(i)) {
                    wb.removeSheetAt(i);
                }
            }
        }
        return wb;
    } catch (InvalidFormatException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return null;
}

From source file:com.quanticate.opensource.spreadsheetexcerpt.excerpt.POIExcerpterAndMerger.java

License:Apache License

private void excerpt(Workbook wb, List<Sheet> sheetsToKeep, OutputStream output) throws IOException {
    // Make the requested sheets be read only
    Set<String> keepNames = new HashSet<String>();
    for (Sheet s : sheetsToKeep) {
        keepNames.add(s.getSheetName());
        for (Row r : s) {
            for (Cell c : r) {
                if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
                    switch (c.getCachedFormulaResultType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        double vd = c.getNumericCellValue();
                        c.setCellType(Cell.CELL_TYPE_NUMERIC);
                        c.setCellValue(vd);
                        break;
                    case Cell.CELL_TYPE_STRING:
                        RichTextString vs = c.getRichStringCellValue();
                        c.setCellType(Cell.CELL_TYPE_STRING);
                        c.setCellValue(vs);
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        boolean vb = c.getBooleanCellValue();
                        c.setCellType(Cell.CELL_TYPE_BOOLEAN);
                        c.setCellValue(vb);
                        break;
                    case Cell.CELL_TYPE_ERROR:
                        c.setCellType(Cell.CELL_TYPE_BLANK);
                        break;
                    }/*  www  . j a v  a  2s  . com*/
                }
            }
        }
    }

    // Remove all the other sheets
    // Note - work backwards! Avoids order changing under us
    for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
        String name = wb.getSheetName(i);
        if (!keepNames.contains(name)) {
            wb.removeSheetAt(i);
        }
    }

    // Save
    wb.write(output);
}