List of usage examples for org.apache.poi.ss.usermodel Sheet rowIterator
Iterator<Row> rowIterator();
From source file:com.googlecode.testcase.annotation.handle.toexcel.strategy.ToHtmlWithExcel.java
License:Apache License
public void printStyles() { ensureOut();//from w ww . j a v a 2 s. co m // First, copy the base css BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/excelStyle.css"))); String line; while ((line = in.readLine()) != null) { out.format("%s%n", line); } } catch (IOException e) { throw new IllegalStateException("Reading standard css", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { //noinspection ThrowFromFinallyBlock throw new IllegalStateException("Reading standard css", e); } } } // now add css for each used style Set<CellStyle> seen = new HashSet<CellStyle>(); for (int i = 0; i < wb.getNumberOfSheets(); i++) { Sheet sheet = wb.getSheetAt(i); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { Row row = rows.next(); for (Cell cell : row) { CellStyle style = cell.getCellStyle(); if (!seen.contains(style)) { printStyle(style); seen.add(style); } } } } }
From source file:com.googlecode.testcase.annotation.handle.toexcel.strategy.ToHtmlWithExcel.java
License:Apache License
private void printSheetContent(Sheet sheet) { printColumnHeads(sheet);//from w w w . j a v a 2 s.c om out.format("<tbody>%n"); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { Row row = rows.next(); out.format(" <tr>%n"); out.format(" <td class=%s>%d</td>%n", ROW_HEAD_CLASS, row.getRowNum() + 1); for (int i = firstColumn; i < endColumn; i++) { String content = " "; String attrs = ""; CellStyle style = null; if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) { Cell cell = row.getCell(i); if (cell != null) { style = cell.getCellStyle(); attrs = tagStyle(cell, style); //Set the value that is rendered for the cell //also applies the format CellFormat cf = CellFormat.getInstance(style.getDataFormatString()); CellFormatResult result = cf.apply(cell); content = result.text; if (content.equals("")) content = " "; } } out.format(" <td class=%s %s>%s</td>%n", styleName(style), attrs, content); } out.format(" </tr>%n"); } out.format("</tbody>%n"); }
From source file:com.helger.masterdata.tools.MainReadPackageTypeCodeListExcel.java
License:Apache License
public static void main(final String[] args) throws Exception { final String sBaseName = "rec21_Rev9e_2012"; final String sSource = "http://www.unece.org/cefact/recommendations/rec21/" + sBaseName + ".xls"; final String sRevision = "9"; // Ideally don't change anything from here on final File f = new File("src/test/resources/" + sBaseName + ".xls"); final Workbook aWB = new HSSFWorkbook(FileUtils.getInputStream(f)); final Sheet aSheet = aWB.getSheetAt(0); final Iterator<Row> it = aSheet.rowIterator(); // Skip 3 rows for (int i = 0; i < 3; ++i) it.next();/*w w w . ja v a2 s . c om*/ final IMicroDocument aDoc = new MicroDocument(); final IMicroElement eRoot = aDoc.appendElement("root"); final IMicroElement eHeader = eRoot.appendElement("header"); eHeader.appendElement("source").appendText(sSource); eHeader.appendElement("revision").appendText(sRevision); final IMicroElement eBody = eRoot.appendElement("body"); while (it.hasNext()) { final Row aRow = it.next(); final String sStatus = ExcelReadUtils.getCellValueString(aRow.getCell(0)); final EUNCodelistStatus[] aStatus = EUNCodelistStatus.getFromTextOrUnchanged(sStatus); final String sCode = ExcelReadUtils.getCellValueString(aRow.getCell(1)); final String sName = ExcelReadUtils.getCellValueString(aRow.getCell(2)); final String sDescription = ExcelReadUtils.getCellValueString(aRow.getCell(3)); final String sNumericCode = _convertNumericCodes(ExcelReadUtils.getCellValueString(aRow.getCell(4))); // Avoid reading empty lines if (StringHelper.hasText(sCode)) { final IMicroElement eItem = eBody.appendElement("item"); eItem.setAttribute("status", EUNCodelistStatus.getAsString(aStatus)); eItem.setAttribute("code", sCode); eItem.appendElement("name").appendElement("text").setAttribute("locale", "en").appendText(sName); if (StringHelper.hasText(sDescription)) eItem.appendElement("description").appendElement("text").setAttribute("locale", "en") .appendText(sDescription); eItem.setAttribute("numericcodes", sNumericCode); } } MicroWriter.writeToStream(aDoc, FileUtils.getOutputStream("src/main/resources/codelists/" + sBaseName + ".xml")); s_aLogger.info("Done"); }
From source file:com.helger.masterdata.tools.MainReadPostalCodeListExcel.java
License:Apache License
public static void main(final String[] args) throws Exception { final String sSource = "http://en.wikipedia.org/wiki/List_of_postal_codes"; final String sRevision = "20130209"; final File f = new File("src/test/resources/" + sRevision + "PostalCodes.xls"); final Workbook aWB = new HSSFWorkbook(FileUtils.getInputStream(f)); final Sheet aSheet = aWB.getSheetAt(0); final Iterator<Row> it = aSheet.rowIterator(); // Skip 1 row it.next();/*from w ww .j a v a 2 s .c o m*/ final IMicroDocument aDoc = new MicroDocument(); final IMicroElement eRoot = aDoc.appendElement(PostalCodeListReader.ELEMENT_ROOT); final IMicroElement eHeader = eRoot.appendElement(PostalCodeListReader.ELEMENT_HEADER); eHeader.appendElement(PostalCodeListReader.ELEMENT_SOURCE).appendText(sSource); eHeader.appendElement(PostalCodeListReader.ELEMENT_REVISION).appendText(sRevision); final IMicroElement eBody = eRoot.appendElement(PostalCodeListReader.ELEMENT_BODY); final List<Item> aItems = new ArrayList<Item>(); int nRow = 0; while (it.hasNext()) { final Row aRow = it.next(); ++nRow; final String sCountry = ExcelReadUtils.getCellValueString(aRow.getCell(0)); if (StringHelper.hasNoText(sCountry)) { s_aLogger.warn("Line " + nRow + ": No country name present"); continue; } final Cell aDateCell = aRow.getCell(1); Date aIntroducedDate = null; if (aDateCell != null && aDateCell.getCellType() != Cell.CELL_TYPE_BLANK) { final Number aNum = ExcelReadUtils.getCellValueNumber(aDateCell); final int nYear = aNum.intValue(); if (nYear > 1800 && nYear < 3000) aIntroducedDate = PDTFactory.createLocalDate(nYear, DateTimeConstants.JANUARY, 1).toDate(); else aIntroducedDate = ExcelReadUtils.getCellValueJavaDate(aDateCell); } final String sISO = ExcelReadUtils.getCellValueString(aRow.getCell(2)); if (StringHelper.hasNoText(sISO)) { s_aLogger.warn("Line " + nRow + ": No ISO code for " + sCountry); continue; } final String sFormat = ExcelReadUtils.getCellValueString(aRow.getCell(3)); if (NO_CODES.equals(sFormat) || StringHelper.hasNoText(sFormat)) continue; final List<String> aFormats = StringHelper.getExploded("\n", sFormat); final String sNote = ExcelReadUtils.getCellValueString(aRow.getCell(4)); aItems.add(new Item(sCountry, aIntroducedDate, sISO, aFormats, sNote)); } // Convert to map, where the key is the ISO final IMultiMapListBased<String, Item> aMap = new MultiHashMapArrayListBased<String, Item>(); for (final Item aItem : aItems) aMap.putSingle(aItem.getISO(), aItem); // Sort all sub-lists by introduction date for (final List<Item> aSubList : aMap.values()) { ContainerHelper.getSortedInline(aSubList, new ComparatorItemValidFrom()); for (int i = 1; i < aSubList.size(); ++i) { final Item aPrevItem = aSubList.get(i - 1); final Item aThisItem = aSubList.get(i); if (aThisItem.getValidFrom() != null) aPrevItem.setValidTo(aThisItem.getValidFrom().minusDays(1)); } } // Print sorted by ISO code for (final Map.Entry<String, List<Item>> aEntry : ContainerHelper.getSortedByKey(aMap).entrySet()) { IMicroElement eCountry = null; for (final Item aItem : aEntry.getValue()) { if (eCountry == null) { // First item - ISO and name only once eCountry = eBody.appendElement(PostalCodeListReader.ELEMENT_COUNTRY); eCountry.setAttribute(PostalCodeListReader.ATTR_ISO, aItem.getISO()); eCountry.setAttribute(PostalCodeListReader.ATTR_NAME, aItem.getCountry()); } final IMicroElement ePostalCodes = eCountry.appendElement(PostalCodeListReader.ELEMENT_POSTALCODES); if (aItem.getValidFrom() != null) ePostalCodes.setAttribute(PostalCodeListReader.ATTR_VALIDFROM, ISODateTimeFormat.date().print(aItem.getValidFrom())); if (aItem.getValidTo() != null) ePostalCodes.setAttribute(PostalCodeListReader.ATTR_VALIDTO, ISODateTimeFormat.date().print(aItem.getValidTo())); for (final String sSingleFormat : aItem.getFormats()) if (sSingleFormat.startsWith(PREFIX_ONE_CODE)) ePostalCodes.appendElement(PostalCodeListReader.ELEMENT_SPECIFIC) .appendText(sSingleFormat.substring(PREFIX_ONE_CODE.length())); else { ePostalCodes.appendElement(PostalCodeListReader.ELEMENT_FORMAT).appendText(sSingleFormat); } if (StringHelper.hasText(aItem.getNote())) ePostalCodes.appendElement(PostalCodeListReader.ELEMENT_NOTE).appendText(aItem.getNote()); } } MicroWriter.writeToStream(aDoc, FileUtils.getOutputStream("src/main/resources/codelists/postal-codes-" + sRevision + ".xml")); s_aLogger.info("Done"); }
From source file:com.helger.masterdata.tools.MainReadUnitTypeCodeListExcel.java
License:Apache License
public static void main(final String[] args) throws Exception { final String sBaseName = "rec20_Rev8e_2012"; final String sSource = "http://www.unece.org/cefact/recommendations/rec20/" + sBaseName + ".xls"; final String sRevision = "8"; // Ideally don't change anything from here on final File f = new File("src/test/resources/" + sBaseName + ".xls"); final Workbook aWB = new HSSFWorkbook(FileUtils.getInputStream(f)); final Sheet aSheet = aWB.getSheetAt(1); final Iterator<Row> it = aSheet.rowIterator(); // Skip 1 row it.next();/*from w w w.j a v a 2 s. co m*/ final IMicroDocument aDoc = new MicroDocument(); final IMicroElement eRoot = aDoc.appendElement("root"); final IMicroElement eHeader = eRoot.appendElement("header"); eHeader.appendElement("source").appendText(sSource); eHeader.appendElement("revision").appendText(sRevision); final IMicroElement eBody = eRoot.appendElement("body"); final Map<String, String> aSectors = new HashMap<String, String>(); final Map<String, Integer> aQuantities = new HashMap<String, Integer>(); while (it.hasNext()) { final Row aRow = it.next(); final String sGroupNumber = ExcelReadUtils.getCellValueString(aRow.getCell(0)); final String sSector = ExcelReadUtils.getCellValueString(aRow.getCell(1)); final String sGroupID = ExcelReadUtils.getCellValueString(aRow.getCell(2)); final String sQuantity = ExcelReadUtils.getCellValueString(aRow.getCell(3)); final String sLevel = ExcelReadUtils.getCellValueString(aRow.getCell(4)); final int nLevel = StringParser.parseInt(sLevel.substring(0, 1), -1); final String sLevelSuffix = sLevel.length() != 2 ? null : sLevel.substring(1, 2); final String sStatus = ExcelReadUtils.getCellValueString(aRow.getCell(5)); final EUNCodelistStatus[] aStatus = EUNCodelistStatus.getFromTextOrUnchanged(sStatus); final String sCommonCode = ExcelReadUtils.getCellValueString(aRow.getCell(6)); final String sName = ExcelReadUtils.getCellValueString(aRow.getCell(7)); final String sConversionFactor = ExcelReadUtils.getCellValueString(aRow.getCell(8)); final String sSymbol = ExcelReadUtils.getCellValueString(aRow.getCell(9)); final String sDescription = ExcelReadUtils.getCellValueString(aRow.getCell(10)); // Avoid reading empty lines if (StringHelper.hasText(sCommonCode)) { aSectors.put(sGroupNumber, sSector); Integer aQuantityID = aQuantities.get(sQuantity); if (aQuantityID == null) { aQuantityID = Integer.valueOf(aQuantities.size() + 1); aQuantities.put(sQuantity, aQuantityID); } final IMicroElement eItem = eBody.appendElement("item"); eItem.setAttribute("groupnum", sGroupNumber); eItem.setAttribute("groupid", sGroupID); eItem.setAttribute("quantityid", aQuantityID.intValue()); eItem.setAttribute("level", nLevel); if (StringHelper.hasText(sLevelSuffix)) eItem.setAttribute("levelsuffix", sLevelSuffix); eItem.setAttribute("status", EUNCodelistStatus.getAsString(aStatus)); eItem.setAttribute("commoncode", sCommonCode); eItem.appendElement("name").appendElement("text").setAttribute("locale", "en").appendText(sName); eItem.setAttribute("conversion", sConversionFactor); eItem.setAttribute("symbol", sSymbol); if (StringHelper.hasText(sDescription)) eItem.appendElement("description").appendElement("text").setAttribute("locale", "en") .appendText(sDescription); } } // sectors final IMicroElement eSectors = eRoot.appendElement("sectors"); for (final Map.Entry<String, String> aEntry : ContainerHelper.getSortedByKey(aSectors).entrySet()) { final IMicroElement eSector = eSectors.appendElement("sector"); eSector.setAttribute("groupnum", aEntry.getKey()); eSector.appendElement("name").appendElement("text").setAttribute("locale", "en") .appendText(aEntry.getValue()); } // quantities final IMicroElement eQuantities = eRoot.appendElement("quantities"); for (final Map.Entry<String, Integer> aEntry : ContainerHelper.getSortedByValue(aQuantities).entrySet()) { final IMicroElement eSector = eQuantities.appendElement("quantity"); eSector.setAttribute("id", aEntry.getValue().intValue()); eSector.appendElement("name").appendElement("text").setAttribute("locale", "en") .appendText(aEntry.getKey()); } MicroWriter.writeToStream(aDoc, FileUtils.getOutputStream("src/main/resources/codelists/" + sBaseName + ".xml")); s_aLogger.info("Done"); }
From source file:com.hurry.excel.html.Excel2Html.java
License:Apache License
public void printStyles() { ensureOut();//ww w .j a v a 2 s . c o m // First, copy the base css BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("excelStyle.css"))); String line; while ((line = in.readLine()) != null) { out.format("%s%n", line); } } catch (IOException e) { throw new IllegalStateException("Reading standard css", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // noinspection ThrowFromFinallyBlock throw new IllegalStateException("Reading standard css", e); } } } // now add css for each used style Set<CellStyle> seen = new HashSet<CellStyle>(); for (int i = 0; i < wb.getNumberOfSheets(); i++) { Sheet sheet = wb.getSheetAt(i); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { Row row = rows.next(); for (Cell cell : row) { CellStyle style = cell.getCellStyle(); if (!seen.contains(style)) { printStyle(style); seen.add(style); } } } } }
From source file:com.hurry.excel.html.Excel2Html.java
License:Apache License
private void printSheetContent(Sheet sheet) { printColumnHeads();//from w ww.ja v a 2 s .co m out.format("<tbody>%n"); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { Row row = rows.next(); out.format(" <tr>%n"); out.format(" <td class=%s>%d</td>%n", ROW_HEAD_CLASS, row.getRowNum() + 1); for (int i = firstColumn; i < endColumn; i++) { String content = " "; String attrs = ""; CellStyle style = null; if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) { Cell cell = row.getCell(i); if (cell != null) { style = cell.getCellStyle(); attrs = tagStyle(cell, style); // Set the value that is rendered for the cell // also applies the format CellFormat cf = CellFormat.getInstance(style.getDataFormatString()); CellFormatResult result = cf.apply(cell); content = result.text; if (content.equals("")) content = " "; } } out.format(" <td class=%s %s>%s</td>%n", styleName(style), attrs, content); } out.format(" </tr>%n"); } out.format("</tbody>%n"); }
From source file:com.jkoolcloud.tnt4j.streams.inputs.AbstractExcelStream.java
License:Apache License
/** * Gets {@link Sheet} contained data bytes count. * * @param sheet//from www .j av a2s.c om * the sheet * * @return the sheet data bytes count */ static int getSheetBytesCount(Sheet sheet) { int bCount = 0; if (sheet != null) { Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { Row r = rows.next(); bCount += getRowBytesCount(r); } } return bCount; }
From source file:com.jogo.dao.RepositorioDao.java
@Override public List importar() { //arry de usuario para armazenar os meus usuarios que pega do excel na folha 1 List<Usuario> usuarios = new ArrayList<>(); //CAPTURA OS DADOS DO USUARIO NO EXCEL try {//from ww w.j a va 2 s . c o m //capturando o excel para meu wb wb = WorkbookFactory.create(new FileInputStream(patch)); //CAPTURAR A PRIMEIRA FOLHA DO EXCEL Sheet folha = wb.getSheetAt(0); //criO um iterator para interagir com as linhas Iterator filaIterator = folha.rowIterator(); //ENQUANTO HOUVER LINHAS O ITERATOR ME TRAZ. while (filaIterator.hasNext()) { //CAPTURO A LINHA DO EXCEL Row linha = (Row) filaIterator.next(); //CRIO UM INTERATOR PARA INTERAGIR COM AS COLUNAS Iterator colunaIterator = linha.cellIterator(); //CRIOU A CLASSE DE USUARIO E ADD DENTRO DO MEU ARRAY Usuario user = new Usuario(); usuarios.add(user); //ENAUQNTO HOUVER COLUNAS O INTERATOR ME TRAZ. while (colunaIterator.hasNext()) { //COM A LINHA E A COLUNA JA POSSO CRIAR UMA CELULA. Cell celula = (Cell) colunaIterator.next(); //APOS CAPTURAR O VALOR NA CELULA, SETO PARA MINHA CLASSE USUARIO QUE CRIEI LOGO ACIMA. if (celula != null) { //CAPTURO O TIPO DA CELULA, NESSE CASO E STRING E NUMERICO(INT) switch (celula.getCellType()) { case Cell.CELL_TYPE_NUMERIC: //CONVERTENDO O VALOR PARA INTEIRO. user.setPontuacao((int) Math.round(celula.getNumericCellValue())); break; case Cell.CELL_TYPE_STRING: user.setNome(celula.getStringCellValue()); break; } } } } } catch (IOException | InvalidFormatException | EncryptedDocumentException e) { } return usuarios; }
From source file:com.jogo.dao.RepositorioDao.java
@Override public List importarPerguntas(int index) { //CRIO UM ARRAY DE PERGUNTAS PARA ARMAZENAR AS PERGUNTAS BUSCAS DO EXCEL. List<Perguntas> perguntas = new ArrayList<>(); try {// w w w . jav a 2 s . c o m //CAPTURANDO O EXCEL PARA MEU WB. wb = WorkbookFactory.create(new FileInputStream(patch)); //CAPTURO A FOLHA DO EXCEL PASSANDO O INDEX Sheet folha = wb.getSheetAt(index); //CRIO UM ITERATOR PARA INTERAGIR COM AS LINHAS. Iterator filaIterator = folha.rowIterator(); //ENQUANTO HOUVER INTERAO PEGA UMA LINHA. while (filaIterator.hasNext()) { //CAPTURO A LINHA DO EXCEL Row linha = (Row) filaIterator.next(); //CRIO UM ITERATOR PARA PEGAR AS COLUNAS Iterator colunaIterator = linha.cellIterator(); //AQUI DIGO QUE MINHAS COLUNAS NO PODE PASSAR DE 6, COMO TA A MINHA ESTRUTURA PARA O EXCEL //1 - PERGUNTA, 2- ALTERNATIVA, 3- ALTERNATIVA, 4- ATLTERNATIVA, 5- ALTERNATIVA, 6- RESPOSTA //CHEGOU MAIOR QUE 6 SAIU DO LOOP DE COLUNAS. if (linha.getLastCellNum() > 6) { break; } //CRIOU A CLASSE DE PERGUNTAS E ADD DENTRO DO MEU ARRAY Perguntas per = new Perguntas(); perguntas.add(per); //INTERAGIR COM AS COLUNAS, PEGAR AS COLUNAS DO EXCEL while (colunaIterator.hasNext()) { //TENDO A LINHA E COLUNA JA POSSO TER UMA CELULA. Cell celula = (Cell) colunaIterator.next(); //APOS CAPTURAR O VALOR NA CELULA, SETO PARA MINHA CLASSE PERGUNTAS QUE CRIEI LOGO ACIMA. if (celula != null) { //CAPTURAR O TIPO DA CELULA, NO CASO TODAS AS PERGUNTAS E ALTERNATIVAS SO STRINGS. //OBS: OLHE QUE NESSE CASO S POSSO TRAZER STRING'S CASO CONTRARIO NO IR? FUNCIONAR.:/ switch (celula.getCellType()) { case Cell.CELL_TYPE_STRING: switch (celula.getColumnIndex()) { case 0: per.setPergunta(celula.getStringCellValue()); break; case 1: per.setAlt1(celula.getStringCellValue()); break; case 2: per.setAlt2(celula.getStringCellValue()); break; case 3: per.setAlt3(celula.getStringCellValue()); break; case 4: per.setAlt4(celula.getStringCellValue()); break; case 5: per.setResposta(celula.getStringCellValue()); break; default: break; } } } } } } catch (IOException | InvalidFormatException | EncryptedDocumentException e) { } return perguntas; }