List of usage examples for org.apache.poi.ss.usermodel Row getCell
Cell getCell(int cellnum);
From source file:com.hack23.cia.service.external.vdem.impl.VdemServiceImpl.java
License:Apache License
@Override public List<Question> getQuestions() { final List<Question> list = new ArrayList<>(); try {//w w w.j a v a 2 s. co m final XSSFWorkbook myWorkBook = new XSSFWorkbook( VdemServiceImpl.class.getResourceAsStream("/V-DemQuestionIDsv5(2016).xlsx")); final XSSFSheet mySheet = myWorkBook.getSheetAt(0); final Iterator<Row> rowIterator = mySheet.iterator(); rowIterator.next(); while (rowIterator.hasNext()) { final Row row = rowIterator.next(); final Question question = new Question(); if (row.getCell(0) == null) { question.setTag(row.getCell(1).toString()); question.setName(row.getCell(2).toString()); } else { question.setQuestionId(row.getCell(0).toString()); question.setTag(row.getCell(1).toString()); question.setName(row.getCell(2).toString()); } list.add(question); } myWorkBook.close(); } catch (final IOException e) { LOGGER.warn("Problem loading", e); } return list; }
From source file:com.heimaide.server.common.utils.excel.ImportExcel.java
License:Open Source License
/** * ??//from w w w .j a v a2 s .co m * @param row ? * @param column ??? * @return ? */ public Object getCellValue(Row row, int column) { Object val = ""; try { Cell cell = row.getCell(column); if (cell != null) { if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { val = cell.getNumericCellValue(); } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) { val = cell.getStringCellValue(); } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { try { if (HSSFDateUtil.isCellDateFormatted(cell)) { val = cell.getDateCellValue(); } else { val = String.valueOf(cell.getNumericCellValue()); } } catch (IllegalStateException e) { val = String.valueOf(cell.getRichStringCellValue()); } } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { val = cell.getBooleanCellValue(); } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) { val = cell.getErrorCellValue(); } } } catch (Exception e) { return val; } return val; }
From source file:com.heimaide.server.common.utils.excel.ImportExcel.java
License:Open Source License
/** * //from w w w.j av a2 s. c o m */ public static void main(String[] args) throws Throwable { ImportExcel ei = new ImportExcel("target/a.xlsx", 1); File file = new File(""); for (Row row : ei.getSheet()) { for (int i = 0; i < row.getLastCellNum(); i++) { Cell cell = row.getCell(i); CellStyle style = cell.getCellStyle(); System.out.println(style); } } for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) { Row row = ei.getRow(i); for (int j = 0; j < ei.getLastCellNum(); j++) { Object val = ei.getCellValue(row, j); System.out.print(val + ", "); } System.out.print("\n"); } }
From source file:com.helger.masterdata.tools.MainReadCountry2Continent.java
License:Apache License
public static void main(final String[] args) { final IReadableResource aRes = new ClassPathResource("country2continent.xlsx"); final Workbook aWB = ExcelReadUtils.readWorkbookFromInputStream(aRes); final Sheet aSheet = aWB.getSheetAt(0); // Skip one row int nRow = 1; int nNotFound = 0; final Map<Locale, EContinent> aMap = new TreeMap<Locale, EContinent>(new ComparatorLocaleCountry(LOC)); while (true) { final Row aRow = aSheet.getRow(nRow); if (aRow == null) break; final String sContinent = ExcelReadUtils.getCellValueString(aRow.getCell(0)); if (StringHelper.hasNoText(sContinent)) break; final EContinent eContinent = _findContinent(sContinent); final String sCountryName = ExcelReadUtils.getCellValueString(aRow.getCell(1)); final Locale aCountry = _findCountryComplex(sCountryName); if (aCountry == null) { System.out.println("No such country: '" + sCountryName + "'"); ++nNotFound;//from ww w . j a v a2 s . c om } else { final EContinent eOld = aMap.put(aCountry, eContinent); if (eOld != null) System.out.println("Country " + aCountry.getDisplayCountry() + " is assigned to " + eContinent.getDisplayText(LOC) + " and " + eOld.getDisplayText(LOC)); } ++nRow; } System.out.println("Countries not found: " + nNotFound); for (final Map.Entry<Locale, EContinent> e : aMap.entrySet()) { System.out.println("s_aMap.put (CountryCache.getCountry (\"" + e.getKey().getCountry() + "\"), EContinent." + e.getValue().name() + "),"); } }
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 a 2 s . c o 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"); 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();//w w w . j ava 2 s .com 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 ww .j av 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"); 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.hp.idc.resm.util.ExcelUtil.java
License:Open Source License
/** * ,// w ww .java 2 s . c om * * @param fileName * excel, getModelExcel * @return * @throws FileNotFoundException */ public Map<String, String> readModelExcel(File file, String modelId) { if (modelId == null) return null; Map<String, String> m = new HashMap<String, String>(); try { InputStream in = new FileInputStream(file); Workbook wb; try { wb = new HSSFWorkbook(in); } catch (IllegalArgumentException e) { wb = new XSSFWorkbook(in); } Sheet sheet = wb.getSheetAt(0); int total = sheet.getLastRowNum(); Row row0 = sheet.getRow(0); String[] head = new String[row0.getLastCellNum()]; for (int j = 0; j < row0.getLastCellNum(); j++) { String[] str = row0.getCell(j).getStringCellValue().split("/"); if (str.length == 2) { head[j] = str[1]; } else { head[j] = ""; } System.out.println(head[j]); } Row row = null; Cell cell = null; for (int i = 1; i < total; i++) { m.clear(); row = sheet.getRow(i); for (int j = 0; j < row.getLastCellNum(); j++) { cell = row.getCell(j); m.put(head[j], cell.getStringCellValue()); System.out.println(head[j] + "--" + cell.getStringCellValue()); } // ServiceManager.getResourceUpdateService().addResource(modelId, // m, 1); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { file.delete(); } return m; }
From source file:com.huawei.gsm.controller.AdminController.java
private void parseExcelFile(File file) throws IOException, InvalidFormatException { XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); Map<String, Site> sites = new HashMap<>(); Set<Cell> cells = new HashSet<>(); if (rowIterator.hasNext()) { rowIterator.next();// w w w.j a v a 2 s . c om } int i = 0; while (rowIterator.hasNext()) { Row row = rowIterator.next(); String siteId; String cellIndex; String cellId; try { row.getCell(1).getStringCellValue(); } catch (NullPointerException ex) { break; } if (row.getCell(0).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { double sId = row.getCell(0).getNumericCellValue(); siteId = String.valueOf(sId).replaceAll("\\.?0*$", ""); } else { siteId = row.getCell(0).getStringCellValue(); } if (row.getCell(6).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { double cId = row.getCell(6).getNumericCellValue(); cellIndex = String.valueOf(cId).replaceAll("\\.?0*$", ""); } else { cellIndex = row.getCell(6).getStringCellValue(); } if (row.getCell(8).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { double ceId = row.getCell(8).getNumericCellValue(); cellId = String.valueOf(ceId).replaceAll("\\.?0*$", ""); } else { cellId = row.getCell(8).getStringCellValue(); } Site site = new Site(); site.setAddress(row.getCell(2).getStringCellValue()); site.setGroup((row.getCell(5).getStringCellValue().toLowerCase().equalsIgnoreCase("GOLDEN_SITE") ? SiteGroup.GOLDEN_SITE : SiteGroup.EVENT_SITE)); site.setSiteId(siteId); site.setSiteName(row.getCell(1).getStringCellValue()); site.setLatitude(row.getCell(4).getNumericCellValue()); site.setLongitude(row.getCell(3).getNumericCellValue()); site.setCells(new ArrayList<>()); sites.put(siteId, site); Cell cell = new Cell(); cell.setCellId(cellId); cell.setCellIndex(cellIndex); cell.setCellName(row.getCell(7).getStringCellValue()); cell.setFrequency(row.getCell(9).getStringCellValue()); cell.setSite(site); cells.add(cell); i++; } Iterator<Site> iter = sites.values().iterator(); while (iter.hasNext()) { Site site = iter.next(); cells.stream().filter((Cell s) -> { return s.getSite().getSiteId().equalsIgnoreCase(site.getSiteId()); }).forEach(s -> { site.getCells().add(s); }); } List<Site> sitesX = new ArrayList<>(sites.values()); siteService.saveSiteBatch(sitesX); }
From source file:com.hurry.excel.html.Excel2Html.java
License:Apache License
private void printSheetContent(Sheet sheet) { printColumnHeads();//from w w w .j a v a2 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"); }