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

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

Introduction

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

Prototype

Sheet getSheetAt(int index);

Source Link

Document

Get the Sheet object at the given index.

Usage

From source file:com.vaadin.addon.spreadsheet.CellValueManager.java

License:Open Source License

/**
 * Removes all the cells within the given bounds from the Spreadsheet and
 * the underlying POI model.//  www  . j a v  a 2 s  . c  o m
 *
 * @param firstRow
 *            Starting row index, 1-based
 * @param firstColumn
 *            Starting column index, 1-based
 * @param lastRow
 *            Ending row index, 1-based
 * @param lastColumn
 *            Ending column index, 1-based
 * @param clearRemovedCellStyle
 *            true to also clear styles from the removed cells
 */
protected void removeCells(int firstRow, int firstColumn, int lastRow, int lastColumn,
        boolean clearRemovedCellStyle) {
    final Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    for (int i = firstRow - 1; i < lastRow; i++) {
        Row row = activeSheet.getRow(i);
        if (row != null) {
            for (int j = firstColumn - 1; j < lastColumn; j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    final String key = SpreadsheetUtil.toKey(j + 1, i + 1);
                    if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                        sentFormulaCells.remove(key);
                    } else {
                        sentCells.remove(key);
                    }
                    if (cell.getHyperlink() != null) {
                        removeHyperlink(cell, activeSheet);
                    }
                    if (clearRemovedCellStyle) {
                        // update style to 0
                        cell.setCellStyle(null);
                        spreadsheet.getSpreadsheetStyleFactory().cellStyleUpdated(cell, true);
                    }
                    // need to make protection etc. settings for the cell
                    // won't get effected. deleting the cell would make it
                    // locked
                    if (clearRemovedCellStyle || cell.getCellStyle().getIndex() == 0) {
                        CellData cd = new CellData();
                        cd.col = j + 1;
                        cd.row = i + 1;
                        removedCells.add(cd);
                    } else {
                        markedCells.add(key);
                    }
                    cell.setCellValue((String) null);
                    getFormulaEvaluator().notifyUpdateCell(cell);
                }
            }
        }
    }
}

From source file:com.vaadin.addon.spreadsheet.CellValueManager.java

License:Open Source License

/**
 * Removes an individual cell from the Spreadsheet and the underlying POI
 * model./*w w w. j  a  va 2 s  .c  o m*/
 *
 * @param rowIndex
 *            Row index of target cell, 1-based
 * @param colIndex
 *            Column index of target cell, 1-based
 * @param clearRemovedCellStyle
 *            true to also clear styles from the removed cell
 */
protected void removeCell(int rowIndex, int colIndex, boolean clearRemovedCellStyle) {
    final Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    final Row row = activeSheet.getRow(rowIndex - 1);
    if (row != null) {
        final Cell cell = row.getCell(colIndex - 1);
        if (cell != null) {
            CellData cd = new CellData();
            cd.col = colIndex;
            cd.row = rowIndex;
            final String key = SpreadsheetUtil.toKey(colIndex, rowIndex);
            if (clearRemovedCellStyle || cell.getCellStyle().getIndex() == 0) {
                removedCells.add(cd);
            } else {
                markedCells.add(key);
            }
            if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                sentFormulaCells.remove(key);
            } else {
                sentCells.remove(key);
            }
            // POI (3.9) doesn't have a method for removing a hyperlink !!!
            if (cell.getHyperlink() != null) {
                removeHyperlink(cell, activeSheet);
            }
            if (clearRemovedCellStyle) {
                // update style to 0
                cell.setCellStyle(null);
                spreadsheet.getSpreadsheetStyleFactory().cellStyleUpdated(cell, true);
            }
            cell.setCellValue((String) null);
            getFormulaEvaluator().notifyUpdateCell(cell);
        }
    }
}

From source file:com.vaadin.addon.spreadsheet.SpreadsheetFactory.java

License:Open Source License

/**
 * Clears the given Spreadsheet and loads the given Workbook into it.
 *
 * @param spreadsheet/*  w  w  w.  ja va  2  s.  c o m*/
 *            Target Spreadsheet
 * @param workbook
 *            Workbook to load or null to generate a new workbook with one
 *            sheet.
 * @param rowCount
 *            Number of rows to generate in the first sheet. Only applies
 *            when the workbook parameter is null.
 * @param columnCount
 *            Number of columns to generate in the first sheet. Only applies
 *            when the workbook parameter is null.
 */
static void loadSpreadsheetWith(Spreadsheet spreadsheet, Workbook workbook, int rowCount, int columnCount) {
    spreadsheet.clearSheetServerSide();
    final Sheet sheet;
    if (workbook == null) {
        workbook = new XSSFWorkbook();
        sheet = createNewSheet(workbook);
        spreadsheet.setInternalWorkbook(workbook);
        generateNewSpreadsheet(spreadsheet, sheet, rowCount, columnCount);
    } else {
        int activeSheetIndex = workbook.getActiveSheetIndex();
        if (workbook.isSheetHidden(activeSheetIndex) || workbook.isSheetVeryHidden(activeSheetIndex)) {
            workbook.setActiveSheet(SpreadsheetUtil.getFirstVisibleSheetPOIIndex(workbook));
        }
        sheet = workbook.getSheetAt(activeSheetIndex);
        spreadsheet.setInternalWorkbook(workbook);
        reloadSpreadsheetData(spreadsheet, sheet);
    }
    loadWorkbookStyles(spreadsheet);
}

From source file:com.vaadin.addon.spreadsheet.SpreadsheetFactory.java

License:Open Source License

/**
 * Reloads the Spreadsheet component using the given Workbook as data
 * source./*from   w  w  w.  ja  va  2s  .  com*/
 *
 * @param spreadsheet
 *            Target Spreadsheet
 * @param workbook
 *            Source Workbook
 */
static void reloadSpreadsheetComponent(Spreadsheet spreadsheet, final Workbook workbook) {
    Workbook oldWorkbook = spreadsheet.getWorkbook();
    if (oldWorkbook != null) {
        spreadsheet.clearSheetServerSide();
        if (oldWorkbook instanceof SXSSFWorkbook) {
            ((SXSSFWorkbook) oldWorkbook).dispose();
        }
    }
    final Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    spreadsheet.setInternalWorkbook(workbook);
    reloadSpreadsheetData(spreadsheet, sheet);
    loadWorkbookStyles(spreadsheet);
}

From source file:com.vaadin.addon.spreadsheet.SpreadsheetHandlerImpl.java

@Override
public void onPaste(String text) {
    Workbook workbook = spreadsheet.getWorkbook();
    Sheet activesheet = workbook.getSheetAt(workbook.getActiveSheetIndex());

    CellReference selectedCellReference = spreadsheet.getSelectedCellReference();

    String[] lines;/*from   w w w  .ja  v a  2s . c om*/
    if (text.indexOf("\r\n") > -1) {
        lines = text.split("\r\n");
    } else if (text.indexOf("\n") > -1) {
        lines = text.split("\n");
    } else {
        lines = text.split("\r");
    }

    int pasteHeight = lines.length;
    int pasteWidth = 1;
    for (String line : lines) {
        String[] tokens = splitOnTab(line);
        pasteWidth = Math.max(pasteWidth, tokens.length);
    }

    int rowIndex = selectedCellReference.getRow();
    int colIndex = selectedCellReference.getCol();

    // Check for protected cells at target
    for (int i = 0; i < pasteHeight; i++) {
        Row row = activesheet.getRow(rowIndex + i);
        if (row != null) {
            for (int j = 0; j < pasteWidth; j++) {
                Cell cell = row.getCell(colIndex + j);
                if (spreadsheet.isCellLocked(cell)) {
                    protectedCellWriteAttempted();
                    return;
                }
            }
        }
    }

    CellValueCommand command = new CellValueCommand(spreadsheet);
    CellRangeAddress affectedRange = new CellRangeAddress(rowIndex, rowIndex + pasteHeight - 1, colIndex,
            colIndex + pasteWidth - 1);
    command.captureCellRangeValues(affectedRange);

    for (int i = 0; i < pasteHeight; i++) {
        String line = lines[i];
        Row row = activesheet.getRow(rowIndex + i);
        if (row == null) {
            row = activesheet.createRow(rowIndex + i);
        }
        String[] tokens = splitOnTab(line);
        for (int j = 0; j < pasteWidth; j++) {
            Cell cell = row.getCell(colIndex + j);
            if (cell == null) {
                cell = row.createCell(colIndex + j);
            }
            if (j < tokens.length) {
                String cellContent = tokens[j];
                Double numVal = SpreadsheetUtil.parseNumber(cell, cellContent, spreadsheet.getLocale());
                if (numVal != null) {
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(numVal);
                } else {
                    cell.setCellValue(cellContent);
                }
            } else {
                cell.setCellType(Cell.CELL_TYPE_BLANK);
                spreadsheet.markCellAsDeleted(cell, true);
            }

            spreadsheet.getCellValueManager().markCellForUpdate(cell);
            spreadsheet.getCellValueManager().getFormulaEvaluator().notifyUpdateCell(cell);
        }
    }

    spreadsheet.getSpreadsheetHistoryManager().addCommand(command);
    spreadsheet.updateMarkedCells();
    // re-set selection to copied area
    spreadsheet.setSelectionRange(rowIndex, colIndex, rowIndex + pasteHeight - 1, colIndex + pasteWidth - 1);

    fireCellValueChangeEvent(affectedRange);
}

From source file:com.validation.manager.core.tool.requirement.importer.RequirementImporter.java

License:Apache License

@Override
public List<Requirement> importFile(boolean header) throws RequirementImportException, VMException {
    queue.clear();/*  w w w .  j a  v  a2 s. co m*/
    List<Integer> errors = new ArrayList<>();
    HashMap<String, Object> parameters = new HashMap<>();
    List<Object> result;
    if (toImport == null) {
        throw new RequirementImportException("message.requirement.import.file.null");
    } else if (!toImport.exists()) {
        throw new RequirementImportException("message.requirement.import.file.invalid");
    } else {
        //Excel support
        if (toImport.getName().endsWith(".xls") || toImport.getName().endsWith(".xlsx")) {
            try {
                Workbook wb = loadFile();
                org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);
                int rows = sheet.getPhysicalNumberOfRows();
                int r = 0;
                if (header) {
                    //Skip header row
                    r++;
                }
                for (; r < rows; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    if (row.getCell(0) == null) {
                        LOG.log(Level.WARNING, "Found an empty row on line: {0}. " + "Stopping processing", r);
                        break;
                    }
                    int cells = row.getPhysicalNumberOfCells();
                    if (cells < 2) {
                        LOG.log(Level.INFO, "Processing row: {0}", r);
                        LOG.warning(ResourceBundle
                                .getBundle("com.validation.manager.resources.VMMessages", Locale.getDefault())
                                .getString("message.requirement.import.missing.column")
                                .replaceAll("%c", "" + cells));
                        errors.add(r);
                    } else {
                        Requirement requirement = new Requirement();
                        LOG.log(Level.FINE, "Row: {0}", r);
                        for (int c = 0; c < cells; c++) {
                            Cell cell = row.getCell(c);
                            String value = "";
                            if (cell != null) {
                                switch (cell.getCellTypeEnum()) {
                                case FORMULA:
                                    value = cell.getCellFormula();
                                    break;
                                case NUMERIC:
                                    value = "" + cell.getNumericCellValue();
                                    break;
                                case STRING:
                                    value = cell.getStringCellValue();
                                    break;
                                default:
                                    value = "";
                                    break;
                                }
                            }
                            //Remove any extra spaces.
                            value = value.trim();
                            switch (c) {
                            case 0:
                                //Unique ID
                                LOG.fine("Setting id");
                                requirement.setUniqueId(value);
                                break;
                            case 1:
                                //Description
                                LOG.fine("Setting desc");
                                requirement.setDescription(value);
                                break;
                            case 2:
                                //Optional Requirement type
                                LOG.fine("Setting requirement type");
                                parameters.clear();
                                parameters.put("name", value);
                                result = namedQuery("RequirementType.findByName", parameters);
                                if (result.isEmpty()) {
                                    //Assume a default
                                    parameters.clear();
                                    parameters.put("name", "SW");
                                    result = namedQuery("RequirementType.findByName", parameters);
                                }
                                requirement.setRequirementTypeId((RequirementType) result.get(0));
                                break;
                            case 3:
                                //Optional notes
                                LOG.fine("Setting notes");
                                requirement.setNotes(value);
                                break;
                            default:
                                throw new RequirementImportException("Invalid column detected: " + c);
                            }
                            LOG.fine(value);
                        }
                        //This shouldn't be null
                        assert rsn != null : "Requirement Spec Node is null?";
                        requirement.setRequirementSpecNode(rsn);
                        parameters.clear();
                        parameters.put("status", "general.open");
                        result = namedQuery("RequirementStatus.findByStatus", parameters);
                        requirement.setRequirementStatusId((RequirementStatus) result.get(0));
                        assert requirement.getUniqueId() != null
                                && !requirement.getUniqueId().isEmpty() : "Invalid requirement detected!";
                        try {
                            if (!exists(requirement) && !queue.containsKey(requirement.getUniqueId())) {
                                queue.put(requirement.getUniqueId(), requirement);
                            }
                        } catch (IllegalOrphanException | NonexistentEntityException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                }
            } catch (InvalidFormatException | IOException ex) {
                LOG.log(Level.SEVERE, null, ex);
            } finally {
                try {
                    if (inp != null) {
                        inp.close();
                    }
                } catch (IOException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            }
        } else if (toImport.getName().endsWith(".xml")) {
            throw new RequirementImportException("XML importing not supported yet.");
        } else if (toImport.getName().endsWith(".doc") || toImport.getName().endsWith(".docx")) {
            try {
                TableExtractor te = new TableExtractor(toImport);
                List<DefaultTableModel> tables = te.extractTables();
                Requirement requirement = new Requirement();
                LOG.log(Level.INFO, "Imported {0} tables!", tables.size());
                int count = 1;
                for (DefaultTableModel model : tables) {
                    int rows = model.getRowCount();
                    int cols = model.getColumnCount();
                    LOG.log(Level.INFO, "Processing table {0} with {1} " + "rows and {2} columns.",
                            new Object[] { count, rows, cols });
                    for (int r = 0; r < rows; r++) {
                        for (int c = 0; c < cols; c++) {
                            String value = (String) model.getValueAt(rows, cols);
                            switch (c) {
                            case 0:
                                //Unique ID
                                LOG.fine("Setting id");
                                requirement.setUniqueId(value);
                                break;
                            case 1:
                                //Description
                                LOG.fine("Setting desc");
                                requirement.setDescription(value);
                                break;
                            case 2:
                                //Requirement type
                                LOG.fine("Setting requirement type");
                                parameters.clear();
                                parameters.put("name", value);
                                result = namedQuery("RequirementType.findByName", parameters);
                                if (result.isEmpty()) {
                                    //Assume a default
                                    parameters.clear();
                                    parameters.put("name", "SW");
                                    result = namedQuery("RequirementType.findByName", parameters);
                                }
                                requirement.setRequirementTypeId((RequirementType) result.get(0));
                                break;
                            case 3:
                                //Optional notes
                                LOG.fine("Setting notes");
                                requirement.setNotes(value);
                                break;
                            default:
                                throw new RuntimeException("Invalid column detected: " + c);
                            }
                        }
                    }
                }
            } catch (IOException | ClassNotFoundException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            throw new RequirementImportException("Unsupported file format: " + toImport.getName());
        }
        StringBuilder sb = new StringBuilder("Rows with erros:\n");
        errors.stream().forEach((line) -> {
            sb.append(line).append('\n');
        });
        if (!errors.isEmpty()) {
            getDefault().lookup(MessageHandler.class).info(sb.toString());
        }
        return new ArrayList(queue.values());
    }
}

From source file:com.validation.manager.core.tool.step.importer.StepImporter.java

License:Apache License

@Override
public List<Step> importFile(boolean header) throws TestCaseImportException {
    steps.clear();//from  ww w. ja va 2  s . c  o m
    if (toImport == null) {
        throw new TestCaseImportException("message.step.import.file.null");
    } else if (!toImport.exists()) {
        throw new TestCaseImportException("message.step.import.file.invalid");
    } else {
        //Excel support
        if (toImport.getName().endsWith(".xls") || toImport.getName().endsWith(".xlsx")) {
            InputStream inp = null;
            try {
                inp = new FileInputStream(toImport);
                org.apache.poi.ss.usermodel.Workbook wb = create(inp);
                org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);
                int rows = sheet.getPhysicalNumberOfRows();
                int r = 0;
                if (header) {
                    //Skip header row
                    r++;
                }
                for (; r < rows; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    int cells = row.getPhysicalNumberOfCells();
                    if (row.getCell(0) == null) {
                        LOG.log(Level.WARNING, "Found an empty row on line: {0}. " + "Stopping processing", r);
                        break;
                    }
                    if (cells < 2) {
                        throw new TestCaseImportException(RB.getString("message.step.import.missing.column")
                                .replaceAll("%c", "" + cells));
                    }
                    Step step = new Step();
                    step.setRequirementList(new ArrayList<>());
                    HashMap<String, Object> parameters = new HashMap<>();
                    List<Object> result;
                    LOG.log(Level.FINE, "Row: {0}", r);
                    for (int c = 0; c < cells; c++) {
                        Cell cell = row.getCell(c);
                        String value = null;
                        if (cell != null) {
                            switch (cell.getCellType()) {

                            case Cell.CELL_TYPE_FORMULA:
                                value = cell.getCellFormula();
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                value = "" + cell.getNumericCellValue();
                                break;
                            case Cell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue();
                                break;
                            default:
                                //Do nothing.
                            }
                        }
                        switch (c) {
                        case 0:
                            if (value != null) {
                                //Sequence
                                LOG.fine("Setting sequence");
                                Integer val = value.contains(".")
                                        ? valueOf(value.substring(0, value.indexOf(".")))
                                        : valueOf(value);
                                if (!tc.getStepList().isEmpty()) {
                                    int max = 0;
                                    for (Step s : tc.getStepList()) {
                                        if (s.getStepSequence() > max) {
                                            max = s.getStepSequence();
                                        }
                                    }
                                    //Make sure there isn't one on that sequence already
                                    val += max;
                                }
                                step.setStepSequence(val);
                            }
                            break;
                        case 1:
                            if (value != null) {
                                //Text
                                LOG.fine("Setting text");
                                step.setText(value.getBytes("UTF-8"));
                            }
                            break;
                        case 2:
                            //Optional Related requirements
                            if (value != null && !value.trim().isEmpty()) {
                                LOG.fine("Setting related requirements");
                                StringTokenizer st = new StringTokenizer(value, ",");
                                while (st.hasMoreTokens()) {
                                    String token = st.nextToken().trim();
                                    parameters.clear();
                                    parameters.put("uniqueId", token);
                                    result = namedQuery("Requirement.findByUniqueId", parameters);
                                    if (!result.isEmpty()) {
                                        for (Object o : result) {
                                            step.getRequirementList().add((Requirement) o);
                                        }
                                    }
                                }
                            }
                            break;
                        case 3:
                            if (value != null) {
                                //Optional Expected result
                                LOG.fine("Setting expected result");
                                step.setExpectedResult(value.getBytes("UTF-8"));
                            }
                            break;
                        case 4:
                            if (value != null) {
                                //Optional notes
                                LOG.fine("Setting notes");
                                step.setNotes(value);
                            }
                            break;

                        default:
                            throw new RuntimeException("Invalid column detected: " + c);
                        }
                        LOG.fine(value);
                    }
                    step.setTestCase(tc);
                    steps.add(step);
                }
            } catch (InvalidFormatException | IOException ex) {
                LOG.log(Level.SEVERE, null, ex);
            } finally {
                try {
                    if (inp != null) {
                        inp.close();
                    }
                } catch (IOException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            }
        } else if (toImport.getName().endsWith(".xml")) {
            throw new TestCaseImportException("XML importing not supported yet.");
        } else {
            throw new TestCaseImportException("Unsupported file format: " + toImport.getName());
        }
        return steps;
    }
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Adds the values from excel./*from w w  w .  j a  v a2  s.c  o m*/
 * 
 * @param path
 *            the path
 * @param index
 *            the index
 * @return the string[][]
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws InvalidFormatException
 *             the invalid format exception
 */
public final String[][] addValuesFromExcel(final String path, final String index)
        throws IOException, InvalidFormatException {

    String cellStringValue = null;
    double cellDoubleValue = 0;
    Boolean cellBooleanValue;
    byte cellErrorValue = 0;
    String[][] arrExcelContent;
    FileInputStream file = null;
    Workbook workbook = null;

    Sheet sheet = null;
    try {
        file = new FileInputStream(new File(path));
        workbook = WorkbookFactory.create(file);
        sheet = workbook.getSheetAt(Integer.parseInt(index));
        Iterator<Row> rowIterator = sheet.iterator();
        arrExcelContent = new String[sheet.getPhysicalNumberOfRows()][];
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            int rowNumber = row.getRowNum();
            Iterator<Cell> cellIterator = row.cellIterator();
            arrExcelContent[rowNumber] = new String[sheet.getRow(rowNumber).getPhysicalNumberOfCells()];
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                int cellNumber = cell.getColumnIndex();
                if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                    cellStringValue = cell.getStringCellValue();
                    arrExcelContent[rowNumber][cellNumber] = cellStringValue;
                } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
                    cellBooleanValue = cell.getBooleanCellValue();
                    arrExcelContent[rowNumber][cellNumber] = cellBooleanValue.toString();
                } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
                    cellErrorValue = cell.getErrorCellValue();
                    arrExcelContent[rowNumber][cellNumber] = Byte.toString(cellErrorValue);
                } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                    cellStringValue = cell.getCellFormula();
                    arrExcelContent[rowNumber][cellNumber] = cellStringValue;

                } else {

                    cellDoubleValue = cell.getNumericCellValue();
                    arrExcelContent[rowNumber][cellNumber] = Double.toString(cellDoubleValue);
                }
            }

        }
    } finally {
        if (((InputStream) workbook) != null) {
            ((InputStream) workbook).close();
        }
    }
    return arrExcelContent;
}

From source file:com.wuliu.biz.util.export.strategy.CarIndexExport.java

License:Open Source License

public String export(String folderPath, String templateName, List<WuliuMergedOrderModel> mergedOrders)
        throws Exception {

    List<List<WuliuMergedOrderModel>> mergedOrderLists = split(mergedOrders);

    if (CollectionUtils.isEmpty(mergedOrderLists)) {
        return null;
    }//from w w w .  j ava  2 s  . com

    File template = new File(this.getClass().getClassLoader().getResource(templateName).getFile());
    InputStream inp = new FileInputStream(template);
    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);
    fillSheet(sheet, mergedOrders);

    File file = new File(folderPath, getName(mergedOrders));
    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        wb.write(outputStream);
        outputStream.flush();
        outputStream.close();
        wb.close();
        System.out.println("success");
    } catch (Exception e) {
        System.out.println("It cause Error on WRITTING excel workbook: ");
        e.printStackTrace();
    }
    return file.getAbsolutePath();
}

From source file:com.wuliu.biz.util.export.strategy.WholeOrderExport.java

License:Open Source License

public String export(String folderPath, String templateName, List<WuliuMergedOrderModel> mergedOrders)
        throws Exception {
    File folder = createFolder(folderPath);
    List<List<WuliuMergedOrderModel>> mergedOrderLists = split(mergedOrders);

    if (CollectionUtils.isEmpty(mergedOrderLists)) {
        return null;
    }/*from  w  ww .  j  ava2 s.  c  o  m*/

    for (List<WuliuMergedOrderModel> item : mergedOrderLists) {
        File template = new File(this.getClass().getClassLoader().getResource(templateName).getFile());
        InputStream inp = new FileInputStream(template);
        Workbook wb = WorkbookFactory.create(inp);
        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
        Sheet sheet = wb.getSheetAt(0);
        fillSheet(sheet, item);
        evaluate(sheet, evaluator);

        File file = new File(folder, getName(item));
        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
            wb.close();
            System.out.println("success");
        } catch (Exception e) {
            System.out.println("It cause Error on WRITTING excel workbook: ");
            e.printStackTrace();
        }
    }
    return folder.getAbsolutePath();
}