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

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

Introduction

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

Prototype

Sheet getSheet(String name);

Source Link

Document

Get sheet with the given name

Usage

From source file:org.eclipse.emfforms.internal.spreadsheet.core.renderer.table.EMFFormsSpreadsheetTableControlRenderer_ITest.java

License:Open Source License

@Test
public void test() throws DatatypeConfigurationException, DatabindingFailedException, IOException {
    // write data
    @SuppressWarnings("restriction")
    final EMFFormsSpreadsheetExporter viewRenderer = new org.eclipse.emfforms.internal.spreadsheet.core.transfer.EMFFormsSpreadsheetExporterImpl(
            new org.eclipse.emfforms.internal.spreadsheet.core.transfer.EMFFormsSpreadsheetExporterImpl.ViewProvider() {
                @Override/*from   w  w  w . j ava2 s . c  o  m*/
                public VView getViewModel(EObject viewEobject, VViewModelProperties properties) {
                    return getView(DetailEditing.NONE);
                }
            });
    final EObject domainModel = getDomainModel();
    final EObject domainModel2 = getDomainModel();
    final Workbook workbook = viewRenderer.render(Arrays.asList(domainModel, domainModel2), null, null);

    final Sheet sheet = workbook.getSheet("root"); //$NON-NLS-1$
    assertEquals(4, sheet.getLastRowNum()); // the rows 0,1,2 are fix and then 3,4 are added
    assertEquals(22, sheet.getRow(0).getLastCellNum());// there are 22 rows, (21 from the view model + 1 for the id)
    // read data

    final EMFFormsSpreadsheetImporter spreadsheetImport = EMFFormsSpreadsheetImporter.INSTANCE;
    final Collection<EObject> domainModels = spreadsheetImport
            .importSpreadsheet(workbook, TaskPackage.eINSTANCE.getTask()).getImportedEObjects();
    assertEquals(2, domainModels.size());
    for (final EObject model : domainModels) {
        assertTrue(EcoreUtil.equals(model, domainModel));
    }
}

From source file:org.eclipse.emfforms.internal.spreadsheet.core.renderer.table.EMFFormsSpreadsheetTableControlRenderer_ITest.java

License:Open Source License

@Test
public void testWithDialogDetail()
        throws DatatypeConfigurationException, DatabindingFailedException, IOException {
    // write data
    @SuppressWarnings("restriction")
    final EMFFormsSpreadsheetExporter viewRenderer = new org.eclipse.emfforms.internal.spreadsheet.core.transfer.EMFFormsSpreadsheetExporterImpl(
            new org.eclipse.emfforms.internal.spreadsheet.core.transfer.EMFFormsSpreadsheetExporterImpl.ViewProvider() {
                @Override//from w  w w  .  j  av  a  2  s .  c  o  m
                public VView getViewModel(EObject viewEobject, VViewModelProperties properties) {
                    return getView(DetailEditing.WITH_DIALOG);
                }
            });
    final EObject domainModel = getDomainModel();
    final EObject domainModel2 = getDomainModel();
    final Workbook workbook = viewRenderer.render(Arrays.asList(domainModel, domainModel2), null, null);

    final Sheet sheet = workbook.getSheet("root"); //$NON-NLS-1$
    assertEquals(4, sheet.getLastRowNum()); // the rows 0,1,2 are fix and then 3,4 are added
    assertEquals(22, sheet.getRow(0).getLastCellNum());// there are 22 rows
    // read data

    final EMFFormsSpreadsheetImporter spreadsheetImport = EMFFormsSpreadsheetImporter.INSTANCE;
    final Collection<EObject> domainModels = spreadsheetImport
            .importSpreadsheet(workbook, TaskPackage.eINSTANCE.getTask()).getImportedEObjects();

    assertEquals(2, domainModels.size());

    for (final EObject model : domainModels) {
        assertTrue(EcoreUtil.equals(model, domainModel));
    }
}

From source file:org.eclipse.lyo.samples.excel.adapter.dao.internal.ExcelDaoImpl.java

License:Open Source License

public Model parseFile(String fileName) {
    if (relationshipUri == null) {
        return null;
    }//  w  w w. j  ava 2s  .  c  om

    FileInputStream in = null;
    Workbook wb = null;

    try {
        in = new FileInputStream(fileName);
        wb = WorkbookFactory.create(in);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Model model = ModelFactory.createDefaultModel();
    model.setNsPrefixes(ConfigSingleton.getInstance().getNsPrefixes());

    HashMap<Sheet, Object[]> sheetResourceMap = new HashMap<Sheet, Object[]>();

    // Loop for Resources defined in Mapper file
    for (String en : mapperTable.getNameList()) {
        MapperEntry e = mapperTable.getEntry(en);
        String type = e.getType();
        String line = e.getLine();
        String uri = e.getUri();

        // parse line definition in Mapper file
        String[] ls = line.split(",");
        if (ls.length < 3) {
            System.err.println("line must has at least sheet, start row, and end row information");
            continue;
        }
        String ssheet = ls[0].trim();
        String sstart = ls[1].trim();
        String send = ls[2].trim();
        Sheet sheet = null;
        try {
            sheet = wb.getSheetAt(Integer.parseInt(ssheet));
        } catch (NumberFormatException ex) {
            sheet = wb.getSheet(ssheet);
        }
        if (sheet == null) {
            System.err.println("target sheet is not found");
            continue;
        }

        int start = Integer.parseInt(sstart);
        int end = sheet.getLastRowNum();
        if (!send.equals("*")) {
            end = Integer.parseInt(send);
        }
        String cond_cellstring = null;
        boolean exist = true;
        if (ls.length > 3) {
            String scond = ls[3].trim();
            if (scond.startsWith("exist")) {
                cond_cellstring = scond.substring(6, scond.length() - 1).trim();
            } else if (scond.startsWith("notexist")) {
                exist = false;
                cond_cellstring = scond.substring(9, scond.length() - 1).trim();
            }
        }

        // map to find referenced resource later
        Object[] resourceMap = sheetResourceMap.get(sheet);
        if (resourceMap == null) {
            resourceMap = new Object[sheet.getLastRowNum() + 1];
            Arrays.fill(resourceMap, null);
            sheetResourceMap.put(sheet, resourceMap);
        }

        // Loop of excel table rows to find the resource 
        for (int j = start; j <= end; j++) {
            if (sheet.getRow(j) == null) {
                continue;
            }
            if (cond_cellstring != null) {
                Cell cell = getCell(sheet, cond_cellstring, j);
                String value = getCellValue(cell);
                if (value == null && exist || value != null && !exist) {
                    continue;
                }
            }
            // generate URI for this resource
            String[] uris = uri.split(",");
            String format = uris[0].trim();
            String uriString = format;
            if (uris.length == 3) {
                Cell cell = getCell(sheet, uris[1].trim(), j);
                String value1 = getCellValue(cell);
                cell = getCell(sheet, uris[2].trim(), j);
                String value2 = getCellValue(cell);
                uriString = String.format(format, value1, value2);
            } else if (uris.length == 2) {
                Cell cell = getCell(sheet, uris[1].trim(), j);
                String value = getCellValue(cell);
                uriString = String.format(format, value);
            }

            // create a Resource in RDF model with URI and resource type defined in Mapper file
            Resource resource = null;
            try {
                resource = model.createResource(relationshipUri + URLEncoder.encode(uriString, "UTF-8"));

                type = getNameUri(type.trim(), model);
                resource.addProperty(RDF.type, model.createResource(type));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            if (resource == null) {
                continue;
            }

            // Keep resource map for current row which will be used to generate reference URI later
            Map<String, Resource> curResMap = (Map<String, Resource>) resourceMap[j];
            if (curResMap == null) {
                curResMap = new HashMap<String, Resource>();
                resourceMap[j] = curResMap;
            }
            curResMap.put(en, resource);

            // Loop for Properties for this resource defined in Mapper file
            for (String propName : e.getPropertyNameList()) {
                MapperEntry.Property prop = e.getProperty(propName);
                if (prop == null) {
                    continue;
                }
                String propType = prop.getType();
                if (propType == null) {
                    continue;
                }
                if (propType.equalsIgnoreCase("resource")) {
                    // assume that prop contains "reference" information in Mapper file
                    String reference = prop.getReference();
                    if (reference != null) {
                        processReference(model, resource, propName, reference, resourceMap, j);
                    }
                } else {
                    // assume that prop contains "column" information in Mapper file
                    String[] tokens = prop.getColumn().trim().split(",");
                    String fmt = null;
                    String column = tokens[0];
                    if (tokens.length > 1) {
                        fmt = tokens[0];
                        column = tokens[1];
                    }
                    Cell cell = getCell(sheet, column, j);
                    if (cell != null) {
                        String value = getCellValue(cell);
                        if (value != null) {
                            if (fmt != null) {
                                value = String.format(fmt, value);
                            }
                            String qpname = propName.trim();
                            qpname = getNameUri(qpname, model);
                            Property property = model.createProperty(qpname);
                            Literal literal = model.createLiteral(value);
                            resource.addLiteral(property, literal);
                        }
                    }
                }
            }
        }
    }
    return model;
}

From source file:org.eclipse.rcptt.ecl.data.apache.poi.impl.internal.commands.ReadExcelFileService.java

License:Open Source License

public IStatus service(Command command, IProcess context) throws InterruptedException, CoreException {
    ReadExcelFile ref = (ReadExcelFile) command;
    EList<String> sheetNames = ref.getSheets();
    String uri = ref.getUri();/*ww  w  .  j av  a 2  s .co m*/
    EclFile file = FileResolver.resolve(uri);
    Workbook book = ExcelFileService.readBook(file);

    if (sheetNames != null && !sheetNames.isEmpty()) {
        // try to read sheets
        for (String sheetName : sheetNames) {
            if (book.getSheet(sheetName) == null) {
                return EclDataApachePOIImplPlugin.createErr("Sheet %s does not persist in file %s", sheetName,
                        file.toURI());
            }
            Table table = readTable(book, book.getSheetIndex(sheetName));
            context.getOutput().write(table);
        }
    } else {
        // read all the sheets
        int sheetnum = 0;
        while (sheetnum < book.getNumberOfSheets()) {
            Table table = readTable(book, sheetnum);
            context.getOutput().write(table);
            sheetnum++;
        }
    }

    return Status.OK_STATUS;
}

From source file:org.eclipse.rcptt.ecl.data.apache.poi.impl.internal.commands.WriteExcelFileService.java

License:Open Source License

public IStatus service(Command command, IProcess context) throws InterruptedException, CoreException {
    WriteExcelFile wef = (WriteExcelFile) command;
    EList<Table> tables = wef.getTables();

    String uri = wef.getUri();//from  w w w. j a  v  a  2  s . co  m
    EclFile file = FileResolver.resolve(uri);

    boolean isAppend = wef.isAppend();
    isAppend &= file.toFile().exists();

    Workbook book;
    if (isAppend) {
        book = ExcelFileService.readBook(file);
    } else {
        book = ExcelFileService.createBook(file, uri);
    }

    int sheetnum = 1;
    for (Table table : tables) {
        String sheetName = table.getPageName();
        if (sheetName == null || sheetName.equals("")) {
            sheetName = String.format(SHEET_NAME_PATTERN, sheetnum);
        }
        Sheet sheet = book.getSheet(sheetName);
        if (sheet == null) {
            sheet = book.createSheet(sheetName);
        }
        writeTable(sheet, table);
        if (!isAppend) {
            autoSizeColumns(sheet);
        }
        context.getOutput().write(table);
        sheetnum++;
    }

    ExcelFileService.writeBook(book, file);
    return Status.OK_STATUS;
}

From source file:org.forzaframework.util.ExcelUtils.java

License:Apache License

public static Sheet getSheet(Workbook wb, String sheetName, Boolean createNewSheet, Integer indexSheet) {
    Sheet sheet = null;//Revisamos si vamos a crear una hoja nueva o con una ya existente.
    if ((createNewSheet != null && createNewSheet) || wb.getNumberOfSheets() == 0) {
        //Creamos una hoja nueva
        if (sheetName != null) {
            sheet = wb.createSheet(sheetName);
        } else {//from   ww w  .  j a  v  a  2s.c  om
            sheet = wb.createSheet();
        }
    } else {
        //Revisamos si existe la hoja con el nombre especificado
        if (indexSheet == null && sheetName != null) {
            sheet = wb.getSheet(sheetName);
        }

        if (sheet == null) {
            //Trabajamos con una hoja ya existente
            if (indexSheet == null) {
                indexSheet = 0;
            }
            if (sheetName != null) {
                wb.setSheetName(indexSheet, sheetName);
            }
            sheet = wb.getSheetAt(indexSheet);
        }
    }
    return sheet;
}

From source file:org.geoserver.wfs.response.ExcelOutputFormatTest.java

License:Open Source License

private void testExcelOutputFormat(Workbook wb) throws IOException {
    Sheet sheet = wb.getSheet("PrimitiveGeoFeature");
    assertNotNull(sheet);/*w  w w  .  jav a2 s .  c  o m*/

    FeatureSource fs = getFeatureSource(MockData.PRIMITIVEGEOFEATURE);

    // check the number of rows in the output
    final int feautureRows = fs.getCount(Query.ALL);
    assertEquals(feautureRows + 1, sheet.getPhysicalNumberOfRows());

    // check the header is what we expect
    final SimpleFeatureType schema = (SimpleFeatureType) fs.getSchema();
    final Row header = sheet.getRow(0);
    assertEquals("FID", header.getCell(0).getRichStringCellValue().toString());
    for (int i = 0; i < schema.getAttributeCount(); i++) {
        assertEquals(schema.getDescriptor(i).getLocalName(),
                header.getCell(i + 1).getRichStringCellValue().toString());
    }

    // check some selected values to see if the content and data type is the one
    // we expect
    FeatureIterator fi = fs.getFeatures().features();
    SimpleFeature sf = (SimpleFeature) fi.next();
    fi.close();

    // ... a string cell
    Cell cell = sheet.getRow(1).getCell(1);
    assertEquals(Cell.CELL_TYPE_STRING, cell.getCellType());
    assertEquals(sf.getAttribute(0), cell.getRichStringCellValue().toString());
    // ... a geom cell
    cell = sheet.getRow(1).getCell(4);
    assertEquals(Cell.CELL_TYPE_STRING, cell.getCellType());
    assertEquals(sf.getAttribute(3).toString(), cell.getRichStringCellValue().toString());
    // ... a number cell
    cell = sheet.getRow(1).getCell(6);
    assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
    assertEquals(((Number) sf.getAttribute(5)).doubleValue(), cell.getNumericCellValue());
    // ... a date cell (they are mapped as numeric in xms?)
    cell = sheet.getRow(1).getCell(10);
    assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
    assertEquals(sf.getAttribute(9), cell.getDateCellValue());
    // ... a boolean cell (they are mapped as numeric in xms?)
    cell = sheet.getRow(1).getCell(12);
    assertEquals(Cell.CELL_TYPE_BOOLEAN, cell.getCellType());
    assertEquals(sf.getAttribute(11), cell.getBooleanCellValue());
    // ... an empty cell (original value is null -> no cell)
    cell = sheet.getRow(1).getCell(3);
    assertNull(cell);
}

From source file:org.geoserver.wfs.response.ExcelOutputFormatTest.java

License:Open Source License

private void testMultipleFeatureTypes(Workbook wb) throws IOException {
    // check we have the expected sheets
    Sheet sheet = wb.getSheet("PrimitiveGeoFeature");
    assertNotNull(sheet);/*  w ww . j  ava 2  s .  c  o m*/

    // check the number of rows in the output
    FeatureSource fs = getFeatureSource(MockData.PRIMITIVEGEOFEATURE);
    assertEquals(fs.getCount(Query.ALL) + 1, sheet.getPhysicalNumberOfRows());

    sheet = wb.getSheet("GenericEntity");
    assertNotNull(sheet);

    // check the number of rows in the output
    fs = getFeatureSource(MockData.GENERICENTITY);
    assertEquals(fs.getCount(Query.ALL) + 1, sheet.getPhysicalNumberOfRows());
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

License:Apache License

/**
 * parse excel file data to java object//  ww w . java2 s .  c  o m
 * 
 * @param workbookInputStream
 * @param sheetProcessors
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void read(InputStream workbookInputStream, ExcelReadSheetProcessor<?>... sheetProcessors) {
    Assert.isTrue(workbookInputStream != null, "workbookInputStream can't be null");
    Assert.isTrue(sheetProcessors != null && sheetProcessors.length != 0, "sheetProcessor can't be null");
    try {
        Workbook workbook = WorkbookFactory.create(workbookInputStream);
        for (ExcelReadSheetProcessor<?> sheetProcessor : sheetProcessors) {
            ExcelReadContext context = new ExcelReadContext();
            try {
                Class clazz = sheetProcessor.getTargetClass();
                Integer sheetIndex = sheetProcessor.getSheetIndex();
                String sheetName = sheetProcessor.getSheetName();
                context.setCurSheetIndex(sheetIndex);
                context.setCurSheetName(sheetName);

                Sheet sheet = null;
                if (sheetName != null) {
                    try {
                        sheet = workbook.getSheet(sheetName);
                    } catch (IllegalArgumentException e) {
                        // ignore
                    }
                    if (sheet != null && sheetIndex != null
                            && !sheetIndex.equals(workbook.getSheetIndex(sheet))) {
                        throw new IllegalArgumentException(
                                "sheetName[" + sheetName + "] and sheetIndex[" + sheetIndex + "] not match.");
                    }
                } else if (sheetIndex != null) {
                    try {
                        sheet = workbook.getSheetAt(sheetIndex);
                    } catch (IllegalArgumentException e) {
                        // ignore
                    }
                } else {
                    throw new IllegalArgumentException("sheetName or sheetIndex can't be null");
                }
                if (sheet == null) {
                    ExcelReadException e = new ExcelReadException(
                            "Sheet Not Found Exception. for sheet name:" + sheetName);
                    e.setCode(ExcelReadException.CODE_OF_SHEET_NOT_EXSIT);
                    throw e;
                }

                if (sheetIndex == null) {
                    sheetIndex = workbook.getSheetIndex(sheet);
                }
                if (sheetName == null) {
                    sheetName = sheet.getSheetName();
                }
                // do check
                Map<Integer, Map<String, ExcelReadFieldMappingAttribute>> fieldMapping = new HashMap<Integer, Map<String, ExcelReadFieldMappingAttribute>>();
                Map<String, Map<String, ExcelReadFieldMappingAttribute>> src = null;
                if (sheetProcessor.getFieldMapping() != null) {
                    src = sheetProcessor.getFieldMapping().export();
                }
                convertFieldMapping(sheet, sheetProcessor, src, fieldMapping);
                if (sheetProcessor.getTargetClass() != null && sheetProcessor.getFieldMapping() != null
                        && !Map.class.isAssignableFrom(sheetProcessor.getTargetClass())) {
                    readConfigParamVerify(sheetProcessor, fieldMapping);
                }

                // proc sheet
                context.setCurSheet(sheet);
                context.setCurSheetIndex(sheetIndex);
                context.setCurSheetName(sheet.getSheetName());
                context.setCurRow(null);
                context.setCurRowData(null);
                context.setCurRowIndex(null);
                context.setCurColIndex(null);
                context.setCurColIndex(null);
                // beforeProcess
                sheetProcessor.beforeProcess(context);

                if (sheetProcessor.getPageSize() != null) {
                    context.setDataList(new ArrayList(sheetProcessor.getPageSize()));
                } else {
                    context.setDataList(new ArrayList());
                }

                Integer pageSize = sheetProcessor.getPageSize();
                int startRow = sheetProcessor.getStartRowIndex();
                Integer rowEndIndex = sheetProcessor.getEndRowIndex();
                int actLastRow = sheet.getLastRowNum();
                if (rowEndIndex != null) {
                    if (rowEndIndex > actLastRow) {
                        rowEndIndex = actLastRow;
                    }
                } else {
                    rowEndIndex = actLastRow;
                }

                ExcelProcessControllerImpl controller = new ExcelProcessControllerImpl();
                if (pageSize != null) {
                    int total = rowEndIndex - startRow + 1;
                    int pageCount = (total + pageSize - 1) / pageSize;
                    for (int i = 0; i < pageCount; i++) {
                        int start = startRow + pageSize * i;
                        int size = pageSize;
                        if (i == pageCount - 1) {
                            size = rowEndIndex - start + 1;
                        }
                        read(controller, context, sheet, start, size, fieldMapping, clazz,
                                sheetProcessor.getRowProcessor(), sheetProcessor.isTrimSpace());
                        sheetProcessor.process(context, context.getDataList());
                        context.getDataList().clear();
                        if (controller.isDoBreak()) {
                            controller.reset();
                            break;
                        }
                    }
                } else {
                    read(controller, context, sheet, startRow, rowEndIndex - startRow + 1, fieldMapping, clazz,
                            sheetProcessor.getRowProcessor(), sheetProcessor.isTrimSpace());
                    sheetProcessor.process(context, context.getDataList());
                    context.getDataList().clear();
                }
            } catch (RuntimeException e) {
                sheetProcessor.onException(context, e);
            } finally {
                sheetProcessor.afterProcess(context);
            }
        }
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

License:Apache License

@SuppressWarnings("unchecked")
private static void write(boolean useTemplate, Workbook workbook, OutputStream outputStream,
        ExcelWriteSheetProcessor<?>... sheetProcessors) {

    for (@SuppressWarnings("rawtypes")
    ExcelWriteSheetProcessor sheetProcessor : sheetProcessors) {
        @SuppressWarnings("rawtypes")
        ExcelWriteContext context = new ExcelWriteContext();

        try {//from ww  w  . j  a  v  a2  s  . c o  m
            if (sheetProcessor == null) {
                continue;
            }
            String sheetName = sheetProcessor.getSheetName();
            Integer sheetIndex = sheetProcessor.getSheetIndex();
            Sheet sheet = null;
            if (sheetProcessor.getTemplateStartRowIndex() == null
                    && sheetProcessor.getTemplateEndRowIndex() == null) {
                sheetProcessor.setTemplateRows(sheetProcessor.getStartRowIndex(),
                        sheetProcessor.getStartRowIndex());
            }
            // sheetName priority,
            if (useTemplate) {
                if (sheetName != null) {
                    try {
                        sheet = workbook.getSheet(sheetName);
                    } catch (IllegalArgumentException e) {
                        // ignore
                    }
                    if (sheet != null && sheetIndex != null
                            && !sheetIndex.equals(workbook.getSheetIndex(sheet))) {
                        throw new IllegalArgumentException(
                                "sheetName[" + sheetName + "] and sheetIndex[" + sheetIndex + "] not match.");
                    }
                } else if (sheetIndex != null) {
                    try {
                        sheet = workbook.getSheetAt(sheetIndex);
                    } catch (IllegalArgumentException e) {
                        // ignore
                    }
                } else {
                    throw new IllegalArgumentException("sheetName or sheetIndex can't be null");
                }
                if (sheet == null) {
                    ExcelWriteException e = new ExcelWriteException(
                            "Sheet Not Found Exception. for sheet name:" + sheetName);
                    e.setCode(ExcelWriteException.CODE_OF_SHEET_NOT_EXSIT);
                    throw e;
                }
            } else {
                if (sheetName != null) {
                    sheet = workbook.getSheet(sheetName);
                    if (sheet != null) {
                        if (sheetIndex != null && !sheetIndex.equals(workbook.getSheetIndex(sheet))) {
                            throw new IllegalArgumentException("sheetName[" + sheetName + "] and sheetIndex["
                                    + sheetIndex + "] not match.");
                        }
                    } else {
                        sheet = workbook.createSheet(sheetName);
                        if (sheetIndex != null) {
                            workbook.setSheetOrder(sheetName, sheetIndex);
                        }
                    }
                } else if (sheetIndex != null) {
                    sheet = workbook.createSheet();
                    workbook.setSheetOrder(sheet.getSheetName(), sheetIndex);
                } else {
                    throw new IllegalArgumentException("sheetName or sheetIndex can't be null");
                }
            }

            if (sheetIndex == null) {
                sheetIndex = workbook.getSheetIndex(sheet);
            }
            if (sheetName == null) {
                sheetName = sheet.getSheetName();
            }

            // proc sheet
            context.setCurSheet(sheet);
            context.setCurSheetIndex(sheetIndex);
            context.setCurSheetName(sheet.getSheetName());
            context.setCurRow(null);
            context.setCurRowIndex(null);
            context.setCurCell(null);
            context.setCurColIndex(null);
            // beforeProcess
            sheetProcessor.beforeProcess(context);
            // write head
            writeHead(useTemplate, sheet, sheetProcessor);
            // sheet
            ExcelProcessControllerImpl controller = new ExcelProcessControllerImpl();
            int writeRowIndex = sheetProcessor.getStartRowIndex();
            boolean isBreak = false;
            Map<Integer, InnerRow> cacheForTemplateRow = new HashMap<Integer, InnerRow>();

            List<?> dataList = sheetProcessor.getDataList(); //
            if (dataList != null && !dataList.isEmpty()) {
                for (Object rowData : dataList) {
                    // proc row
                    Row row = sheet.getRow(writeRowIndex);
                    if (row == null) {
                        row = sheet.createRow(writeRowIndex);
                    }
                    InnerRow templateRow = getTemplateRow(cacheForTemplateRow, sheet, sheetProcessor,
                            writeRowIndex);
                    if (templateRow != null) {
                        row.setHeight(templateRow.getHeight());
                        row.setHeightInPoints(templateRow.getHeightInPoints());
                        row.setRowStyle(templateRow.getRowStyle());
                        row.setZeroHeight(templateRow.isZeroHeight());
                    }
                    context.setCurRow(row);
                    context.setCurRowIndex(writeRowIndex);
                    context.setCurColIndex(null);
                    context.setCurCell(null);
                    //
                    try {
                        controller.reset();
                        if (sheetProcessor.getRowProcessor() != null) {
                            sheetProcessor.getRowProcessor().process(controller, context, rowData, row);
                        }
                        if (!controller.isDoSkip()) {
                            writeRow(context, templateRow, row, rowData, sheetProcessor);
                            writeRowIndex++;
                        }
                        if (controller.isDoBreak()) {
                            isBreak = true;
                            break;
                        }
                    } catch (RuntimeException e) {
                        if (e instanceof ExcelWriteException) {
                            ExcelWriteException ewe = (ExcelWriteException) e;
                            // ef.setColIndex(null); user may want to set this value,
                            ewe.setRowIndex(writeRowIndex);
                            throw ewe;
                        } else {
                            ExcelWriteException ewe = new ExcelWriteException(e);
                            ewe.setColIndex(null);
                            ewe.setCode(ExcelWriteException.CODE_OF_PROCESS_EXCEPTION);
                            ewe.setRowIndex(writeRowIndex);
                            throw ewe;
                        }
                    }
                }
                if (isBreak) {
                    break;
                }
            }
            if (sheetProcessor.getTemplateStartRowIndex() != null
                    && sheetProcessor.getTemplateEndRowIndex() != null) {
                writeDataValidations(sheet, sheetProcessor);
                writeStyleAfterFinish(useTemplate, sheet, sheetProcessor);
            }
        } catch (RuntimeException e) {
            sheetProcessor.onException(context, e);
        } finally {
            sheetProcessor.afterProcess(context);
        }
    }

    try {
        workbook.write(outputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}