List of usage examples for org.apache.poi.ss.usermodel Cell getStringCellValue
String getStringCellValue();
For numeric cells we throw an exception.
From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java
License:Open Source License
private static Chunk getChunk(Workbook wb, Cell cell) { Chunk phrase = null;//from ww w . j a v a 2 s. c o m switch (cell.getCellType() == Cell.CELL_TYPE_FORMULA ? cell.getCachedFormulaResultType() : cell.getCellType()) { case Cell.CELL_TYPE_STRING: phrase = new Chunk("" + cell.getStringCellValue()); break; case Cell.CELL_TYPE_NUMERIC: String format = cell.getCellStyle().getDataFormatString(); if (cell.getCellStyle().getDataFormat() > 0) { try { if (format.contains("0")) { //Decimal DecimalFormat df = new DecimalFormat(format); phrase = new Chunk(df.format(cell.getNumericCellValue())); } else if (format.contains("h:")) { phrase = new Chunk(FormatterUtils.formatDateTimeShort(cell.getDateCellValue())); } else if (format.contains("yy")) { phrase = new Chunk(FormatterUtils.formatDate(cell.getDateCellValue())); } } catch (Exception e) { System.err.println(e); } } if (phrase == null) { phrase = new Chunk("" + (int) cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BLANK: phrase = new Chunk(""); break; default: phrase = new Chunk("" + cell.getCellType()); } Font font = wb.getFontAt(cell.getCellStyle().getFontIndex()); short[] rgb = HSSFColor.getIndexHash().get((int) font.getColor()).getTriplet(); phrase.setFont(new com.lowagie.text.Font(phrase.getFont().getBaseFont(), font.getFontHeightInPoints() - 3, (font.getBold() ? com.lowagie.text.Font.BOLD : com.lowagie.text.Font.NORMAL), new Color(rgb[0], rgb[1], rgb[2]))); return phrase; }
From source file:com.actelion.research.spiritapp.ui.util.POIUtils.java
License:Open Source License
public static void autoSizeColumns(Sheet sheet, int maxColWidth, boolean resizeHeight) { ListHashMap<Integer, Integer> col2lens = new ListHashMap<>(); for (int row = sheet.getFirstRowNum(); row <= sheet.getLastRowNum(); row++) { Row r = sheet.getRow(row);//from ww w .ja v a2 s . c o m if (r == null || r.getFirstCellNum() < 0) continue; short maxH = 0; for (int col = r.getFirstCellNum(); col <= r.getLastCellNum(); col++) { Cell c = r.getCell(col); if (c == null || (c.getCellType() != Cell.CELL_TYPE_STRING && c.getCellType() != Cell.CELL_TYPE_NUMERIC)) continue; Font font = sheet.getWorkbook().getFontAt(c.getCellStyle().getFontIndex()); String s = c.getCellType() == Cell.CELL_TYPE_STRING ? c.getStringCellValue() : "" + c.getNumericCellValue(); String[] lines = MiscUtils.split(s, "\n"); int maxLen = 1; for (int i = 0; i < lines.length; i++) { maxLen = Math.max(lines[i].length(), maxLen); } if (font.getFontHeightInPoints() < 12) { col2lens.add(col, 700 + maxLen * (font.getFontHeightInPoints() + (font.getBoldweight() > 500 ? 1 : 0)) * 20); } maxH = (short) Math.max(maxH, 50 + lines.length * (font.getFontHeight() * 1.2)); } if (resizeHeight) r.setHeight(maxH); } for (int col : col2lens.keySet()) { List<Integer> lens = col2lens.get(col); Collections.sort(lens); int len = lens.get(lens.size() - 1); if (lens.size() > 10 && lens.get(lens.size() - 1) > 2 * lens.get(lens.size() - 2)) { len = lens.get(lens.size() - 2); } sheet.setColumnWidth(col, Math.max(Math.min((int) (len * 1.25), maxColWidth > 0 ? maxColWidth : 300000), 1500)); } }
From source file:com.adobe.acs.commons.data.Variant.java
License:Apache License
private void setValue(Cell cell) { int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_FORMULA) { cellType = cell.getCachedFormulaResultType(); }//from w w w. java2 s .c o m switch (cellType) { case Cell.CELL_TYPE_BOOLEAN: setValue(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: double number = cell.getNumericCellValue(); if (Math.floor(number) == number) { setValue((long) number); } else { setValue(number); } if (DateUtil.isCellDateFormatted(cell)) { setValue(cell.getDateCellValue()); } DataFormatter dataFormatter = new DataFormatter(); if (cellType == Cell.CELL_TYPE_FORMULA) { setValue(dataFormatter.formatCellValue(cell)); } else { CellStyle cellStyle = cell.getCellStyle(); setValue(dataFormatter.formatRawCellContents(cell.getNumericCellValue(), cellStyle.getDataFormat(), cellStyle.getDataFormatString())); } break; case Cell.CELL_TYPE_STRING: setValue(cell.getStringCellValue().trim()); break; case Cell.CELL_TYPE_BLANK: default: clear(); break; } }
From source file:com.adobe.acs.commons.mcp.impl.processes.AssetFolderCreator.java
License:Apache License
/** * Parse a single cell from an Excel row. * * @param cell the cell to process from the Excel row. * @param previousAssetFolderPath the node path of the previous * @return the asset folder path to the asset folder represented by {@param cell} * @throws IllegalArgumentException//from ww w . j a v a 2s . c o m */ private String parseAssetFolderCell(final Cell cell, final String previousAssetFolderPath) throws IllegalArgumentException { final String cellValue = StringUtils.trimToNull(cell.getStringCellValue()); if (StringUtils.isNotBlank(cellValue)) { // Generate a asset folder definition that will in turn be used to drive the asset folder definition creation AssetFolderDefinition assetFolderDefinition = getAssetFolderDefinition(primary, cellValue, previousAssetFolderPath); // Try using the fallback converter if the primary convert could not resolve to a valid definition. if (assetFolderDefinition == null) { assetFolderDefinition = getAssetFolderDefinition(fallback, cellValue, previousAssetFolderPath); } if (assetFolderDefinition == null) { log.warn("Could not find a Asset Folder Converter that accepts value [ {} ]; skipping...", cellValue); // Record parse failure record(ReportRowStatus.FAILED_TO_PARSE, "", cellValue); throw new IllegalArgumentException(String.format( "Unable to parse value [ %s ]. Skipping rest of row to prevent undesired structured from being created.", cellValue)); } else { /* Prepare for next Cell */ if (assetFolderDefinitions.get(assetFolderDefinition.getId()) == null) { assetFolderDefinitions.put(assetFolderDefinition.getId(), assetFolderDefinition); } return assetFolderDefinition.getPath(); } } else { // If cell is blank then treat as it it is empty. return previousAssetFolderPath; } }
From source file:com.adobe.acs.commons.mcp.impl.processes.TagCreator.java
License:Apache License
/** * Parses the input Excel file and creates a list of TagDefinition objects to process. * * @param manager the action manager//from w w w . j a v a 2s .co m * @throws IOException */ @SuppressWarnings({ "squid:S3776", "squid:S1141" }) public void parseTags(ActionManager manager) throws Exception { manager.withResolver(rr -> { final XSSFWorkbook workbook = new XSSFWorkbook(excelFile); final XSSFSheet sheet = workbook.getSheetAt(0); final Iterator<Row> rows = sheet.rowIterator(); final String tagsRootPath = new TagRootResolver(rr).getTagsLocationPath(); if (tagsRootPath == null) { record(ReportRowSatus.FAILED_TO_PARSE, "Abandoning Tag parsing. Unable to determine AEM Tags root (/content/cq:tags vs /etc/tags). Please ensure the path exists and is accessible by the user running Tag Creator.", "N/A", "N/A"); return; } while (rows.hasNext()) { final Row row = rows.next(); final Iterator<Cell> cells = row.cellIterator(); int cellIndex = 0; // The previousTagId is reset on each new row. String previousTagId = null; while (cells.hasNext()) { final Cell cell = cells.next(); final String cellValue = StringUtils.trimToNull(cell.getStringCellValue()); if (StringUtils.isBlank(cellValue)) { // Hitting a blank cell means its the end of this row; don't process anything past this break; } // Generate a tag definition that will in turn be used to drive the tag creation TagDefinition tagDefinition = getTagDefinition(primary, cellIndex, cellValue, previousTagId, tagsRootPath); if (tagDefinition == null) { tagDefinition = getTagDefinition(fallback, cellIndex, cellValue, previousTagId, tagsRootPath); } if (tagDefinition == null) { log.warn("Could not find a Tag Data Converter that accepts value [ {} ]; skipping...", cellValue); // Record parse failure record(ReportRowSatus.FAILED_TO_PARSE, cellValue, "", ""); // Break to next Row break; } else { /* Prepare for next Cell */ cellIndex++; previousTagId = tagDefinition.getId(); if (tagDefinitions.get(tagDefinition.getId()) == null) { tagDefinitions.put(tagDefinition.getId(), tagDefinition); } } } } log.info("Finished Parsing and collected [ {} ] tags for import.", tagDefinitions.size()); }); }
From source file:com.adobe.acs.commons.mcp.util.Spreadsheet.java
License:Apache License
private String getStringValueFromCell(Cell cell) { if (cell == null) { return null; }/*from w w w . j ava 2s .c om*/ int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_FORMULA) { cellType = cell.getCachedFormulaResultType(); } switch (cellType) { case Cell.CELL_TYPE_BOOLEAN: return Boolean.toString(cell.getBooleanCellValue()); case Cell.CELL_TYPE_BLANK: return null; case Cell.CELL_TYPE_NUMERIC: double number = cell.getNumericCellValue(); if (Math.floor(number) == number) { return Integer.toString((int) number); } else { return Double.toString(cell.getNumericCellValue()); } case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); default: return "???"; } }
From source file:com.adobe.ags.curly.controller.DataImporterController.java
License:Apache License
private String getStringValueFromCell(Cell cell) { if (cell == null) { return null; }//from w w w . j ava 2 s . c o m int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_FORMULA) { cellType = cell.getCachedFormulaResultType(); } switch (cellType) { case Cell.CELL_TYPE_BOOLEAN: return Boolean.toString(cell.getBooleanCellValue()); case Cell.CELL_TYPE_BLANK: return null; case Cell.CELL_TYPE_NUMERIC: double num = cell.getNumericCellValue(); if (num == Math.floor(num)) { return Integer.toString((int) num); } else { return Double.toString(cell.getNumericCellValue()); } case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); default: return "???"; } }
From source file:com.AllenBarr.CallSheetGenerator.CallSheetGeneratorControllerController.java
License:Open Source License
private void populateContributorList() { if (excelSheet.exists()) { try {// w ww . j av a 2s.c o m wb = WorkbookFactory.create(excelSheet); wbSheet = wb.getSheetAt(0); Row wbRow = wbSheet.getRow(0); Integer vanIDColumnIndex = 0; Integer fNameColumnIndex = 0; Integer lNameColumnIndex = 0; for (Cell cell : wbRow) { if (null != cell.getStringCellValue()) { switch (cell.getStringCellValue()) { case "VANID": vanIDColumnIndex = cell.getColumnIndex(); break; case "LastName": lNameColumnIndex = cell.getColumnIndex(); break; case "FirstName": fNameColumnIndex = cell.getColumnIndex(); break; } } } final ObservableList<String> names = FXCollections.observableArrayList(); for (Row row : wbSheet) { switch (row.getCell(vanIDColumnIndex).getCellType()) { case Cell.CELL_TYPE_STRING: names.add(row.getCell(vanIDColumnIndex).getStringCellValue() + " " + row.getCell(fNameColumnIndex).getStringCellValue() + " " + row.getCell(lNameColumnIndex).getStringCellValue()); break; case Cell.CELL_TYPE_NUMERIC: names.add((int) row.getCell(vanIDColumnIndex).getNumericCellValue() + " " + row.getCell(fNameColumnIndex).getStringCellValue() + " " + row.getCell(lNameColumnIndex).getStringCellValue()); break; } } contributorSelector.setItems(names); contributorSelector.getSelectionModel().select(0); } catch (IOException | InvalidFormatException ex) { Logger.getLogger(CallSheetGeneratorControllerController.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.AllenBarr.CallSheetGenerator.CallSheetGeneratorControllerController.java
License:Open Source License
private Contributor makeContributor() { Contributor contributor = new Contributor(); Row contribRow = wbSheet.getRow(contributorSelector.getSelectionModel().getSelectedIndex()); Row headerRow = wbSheet.getRow(0);// www . j a v a 2 s .c om Integer vanIDColumnIndex = 0; Integer lNameColumnIndex = 0; Integer fNameColumnIndex = 0; Integer mNameColumnIndex = 0; Integer suffixColumnIndex = 0; Integer salutationColumnIndex = 0; Integer spouseColumnIndex = 0; Integer mAddressColumnIndex = 0; Integer mCityColumnIndex = 0; Integer mStateColumnIndex = 0; Integer mZipColumnIndex = 0; Integer sexColumnIndex = 0; Integer ageColumnIndex = 0; Integer occupationColumnIndex = 0; Integer employerColumnIndex = 0; Integer phoneColumnIndex = 0; Integer homePhoneColumnIndex = 0; Integer cellPhoneColumnIndex = 0; Integer workPhoneColumnIndex = 0; Integer extColumnIndex = 0; Integer emailColumnIndex = 0; Integer notesColumnIndex = 0; Integer partyColumnIndex = 0; for (Cell cell : headerRow) { if (null != cell.getStringCellValue()) { switch (cell.getStringCellValue()) { case "VANID": vanIDColumnIndex = cell.getColumnIndex(); break; case "LastName": lNameColumnIndex = cell.getColumnIndex(); break; case "FirstName": fNameColumnIndex = cell.getColumnIndex(); break; case "MiddleName": mNameColumnIndex = cell.getColumnIndex(); break; case "Suffix": suffixColumnIndex = cell.getColumnIndex(); break; case "Salutation": salutationColumnIndex = cell.getColumnIndex(); break; case "Spouse": spouseColumnIndex = cell.getColumnIndex(); break; case "mAddress": mAddressColumnIndex = cell.getColumnIndex(); break; case "mCity": mCityColumnIndex = cell.getColumnIndex(); break; case "mState": mStateColumnIndex = cell.getColumnIndex(); break; case "mZip5": mZipColumnIndex = cell.getColumnIndex(); break; case "Sex": sexColumnIndex = cell.getColumnIndex(); break; case "Age": ageColumnIndex = cell.getColumnIndex(); break; case "Occupation": occupationColumnIndex = cell.getColumnIndex(); break; case "Employer": employerColumnIndex = cell.getColumnIndex(); break; case "Phone": phoneColumnIndex = cell.getColumnIndex(); break; case "CellPhone": cellPhoneColumnIndex = cell.getColumnIndex(); break; case "HomePhone": homePhoneColumnIndex = cell.getColumnIndex(); break; case "WorkPhone": workPhoneColumnIndex = cell.getColumnIndex(); break; case "WorkPhoneExt": extColumnIndex = cell.getColumnIndex(); break; case "Email": emailColumnIndex = cell.getColumnIndex(); break; case "Notes": notesColumnIndex = cell.getColumnIndex(); break; case "Party": partyColumnIndex = cell.getColumnIndex(); break; } } } try { contributor.setVANID((int) contribRow.getCell(vanIDColumnIndex).getNumericCellValue()); } catch (NullPointerException ex) { } catch (IllegalStateException ex) { contributor.setVANID(Integer.parseInt(contribRow.getCell(vanIDColumnIndex).getStringCellValue())); } String name = ""; try { name = name.concat(contribRow.getCell(fNameColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { name = name.concat(" " + contribRow.getCell(mNameColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { name = name.concat(" " + contribRow.getCell(lNameColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { name = name.concat(" " + contribRow.getCell(suffixColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } contributor.setName(name); try { contributor.setSalutation(contribRow.getCell(salutationColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setSex(contribRow.getCell(sexColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setParty(contribRow.getCell(partyColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setPhone(contribRow.getCell(phoneColumnIndex).getNumericCellValue()); } catch (NullPointerException ex) { } catch (IllegalStateException ex) { contributor.setPhone(Double.parseDouble(contribRow.getCell(phoneColumnIndex).getStringCellValue())); } try { contributor.setHomePhone(contribRow.getCell(homePhoneColumnIndex).getNumericCellValue()); } catch (NullPointerException ex) { } catch (IllegalStateException ex) { contributor.setHomePhone( Double.parseDouble(contribRow.getCell(homePhoneColumnIndex).getStringCellValue())); } try { contributor.setCellPhone(contribRow.getCell(cellPhoneColumnIndex).getNumericCellValue()); } catch (NullPointerException ex) { } catch (IllegalStateException ex) { contributor.setCellPhone( Double.parseDouble(contribRow.getCell(cellPhoneColumnIndex).getStringCellValue())); } try { contributor.setWorkPhone(contribRow.getCell(workPhoneColumnIndex).getNumericCellValue()); } catch (NullPointerException ex) { } catch (IllegalStateException ex) { contributor.setWorkPhone( Double.parseDouble(contribRow.getCell(workPhoneColumnIndex).getStringCellValue())); } try { contributor.setWorkExtension(contribRow.getCell(extColumnIndex).getNumericCellValue()); } catch (NullPointerException ex) { } catch (IllegalStateException ex) { contributor .setWorkExtension(Double.parseDouble(contribRow.getCell(extColumnIndex).getStringCellValue())); } try { contributor.setEmail(contribRow.getCell(emailColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setEmployer(contribRow.getCell(employerColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setOccupation(contribRow.getCell(occupationColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setAge((int) contribRow.getCell(ageColumnIndex).getNumericCellValue()); } catch (NullPointerException ex) { } catch (IllegalStateException ex) { contributor.setAge(Integer.parseInt(contribRow.getCell(ageColumnIndex).getStringCellValue())); } try { contributor.setSpouse(contribRow.getCell(spouseColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setStreetAddress(contribRow.getCell(mAddressColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setCity(contribRow.getCell(mCityColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setState(contribRow.getCell(mStateColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } try { contributor.setZip((int) contribRow.getCell(mZipColumnIndex).getNumericCellValue()); } catch (NullPointerException ex) { } catch (IllegalStateException ex) { contributor.setZip(Integer.parseInt(contribRow.getCell(mZipColumnIndex).getStringCellValue())); } try { contributor.setNotes(contribRow.getCell(notesColumnIndex).getStringCellValue()); } catch (NullPointerException ex) { } ICsvListReader listReader = null; try { try { listReader = new CsvListReader( new FileReader(contributionDirectory.getPath() + "/" + ((String) contributorSelector.getItems() .get(contributorSelector.getSelectionModel().getSelectedIndex())) .replaceAll("[\\D]", "") + ".csv"), CsvPreference.STANDARD_PREFERENCE); listReader.getHeader(true); // skip the header (can't be used with CsvListReader) while ((listReader.read()) != null) { // use different processors depending on the number of columns final CellProcessor[] processors; processors = getProcessors(); final List<Object> customerList = listReader.executeProcessors(processors); Matcher date = dateRegex.matcher(customerList.toString()); Matcher des = descRegex.matcher(customerList.toString()); Matcher amt = amtRegex.matcher(customerList.toString()); date.find(); des.find(); amt.find(); contributor.addDonation( new Donation(new Date(date.group(1)), des.group(1), Double.parseDouble(amt.group(1)))); } } catch (FileNotFoundException | NullPointerException ex) { //Logger.getLogger(CallSheetGeneratorControllerController.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { //Logger.getLogger(CallSheetGeneratorControllerController.class.getName()).log(Level.SEVERE, null, ex); } finally { if (listReader != null) { try { listReader.close(); } catch (IOException ex) { //Logger.getLogger(CallSheetGeneratorControllerController.class.getName()).log(Level.SEVERE, null, ex); } } } return contributor; }
From source file:com.alphacell.controller.CargarDatosBean.java
public void handleFileUpload(FileUploadEvent event) { if (event.getFile().equals(null)) { FacesUtil.addInfoMessage("El archivo es null"); }//from www . j av a2 s .co m InputStream file; HSSFWorkbook workbook = null; try { file = event.getFile().getInputstream(); workbook = new HSSFWorkbook(file); } catch (IOException e) { FacesUtil.addErrorMessage("Error Leyendo archivo : " + e); } HSSFSheet sheet = workbook.getSheetAt(1); Iterator<Row> rowIterator = sheet.iterator(); Calendar calendar = new GregorianCalendar(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); //Job job = new Job(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell) || HSSFDateUtil.isCellInternalDateFormatted(cell)) { calendar.setTime(cell.getDateCellValue()); } else { System.out.print(cell.getNumericCellValue() + "\t\t"); } break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "\t\t"); break; } } } }