List of usage examples for org.apache.poi.ss.usermodel Sheet getSheetName
String getSheetName();
From source file:com.dataart.spreadsheetanalytics.engine.PoiWorkbookConverters.java
License:Apache License
private PoiProxySheet makeSheet(Workbook wb, FormulaParsingWorkbook ewb) { Sheet wbSheet = wb.getSheetAt(0); PoiProxySheet sheet = new PoiProxySheet(wbSheet.getSheetName()); for (int r = 0; r <= wbSheet.getLastRowNum(); r++) { Row wbSheetRow = wbSheet.getRow(r); if (wbSheetRow == null) { continue; }/*from w ww .ja v a 2 s . c o m*/ for (int c = 0; c <= wbSheetRow.getLastCellNum(); c++) { Cell wbSheetRowCell = wbSheetRow.getCell(c); if (wbSheetRowCell == null) { continue; } final Ptg[] tokens = CELL_TYPE_FORMULA == wbSheetRowCell.getCellType() ? FormulaParser.parse(wbSheetRowCell.getCellFormula(), ewb, FormulaType.CELL, 0) : null; sheet.setCell(PoiProxyCell.makeCell(sheet, wbSheetRowCell, tokens)); } } return sheet; }
From source file:com.devnexus.ting.web.controller.admin.RegistrationController.java
License:Apache License
private void createTicketTypeDropDown(Sheet formSheet, Sheet ticketTypeSheet, String[] ticketTypes) { XSSFDataValidationHelper validationHelper = new XSSFDataValidationHelper((XSSFSheet) formSheet); CellRangeAddressList ticketCellAddress = new CellRangeAddressList(7, 100, 6, 7); DataValidationConstraint constraint = validationHelper .createFormulaListConstraint(ticketTypeSheet.getSheetName() + "!$A$1:$A$" + ticketTypes.length); // constraint = validationHelper.createExplicitListConstraint(ticketTypes); DataValidation dataValidation = validationHelper.createValidation(constraint, ticketCellAddress); dataValidation.setSuppressDropDownArrow(true); formSheet.addValidationData(dataValidation); }
From source file:com.dickimawbooks.datatooltk.io.DatatoolExcel.java
License:Open Source License
public DatatoolDb importData(File file) throws DatatoolImportException { DatatoolDb db = new DatatoolDb(settings); try {/* ww w . jav a2s. c om*/ if (!file.exists()) { throw new IOException(DatatoolTk.getLabelWithValue("error.io.file_not_found", "" + file)); } if (file.getName().toLowerCase().endsWith(".xlsx")) { throw new IOException(DatatoolTk.getLabel("error.xlsx_not_supported")); } Workbook workBook = WorkbookFactory.create(file); Sheet sheet; String sheetRef = settings.getSheetRef(); int sheetIdx = 0; String sheetName = null; try { sheetIdx = Integer.parseInt(sheetRef); } catch (NumberFormatException e) { sheetName = sheetRef; } if (sheetName == null) { sheet = workBook.getSheetAt(sheetIdx); db.setName(sheet.getSheetName()); } else { sheet = workBook.getSheet(sheetName); db.setName(sheetName); } Iterator<Row> rowIter = sheet.rowIterator(); int rowIdx = 0; if (!rowIter.hasNext()) { return db; } Row row = rowIter.next(); if (settings.hasCSVHeader()) { // First row is header boolean empty = true; while (empty) { for (Cell cell : row) { DatatoolHeader header = new DatatoolHeader(db, cell.toString()); db.addColumn(header); empty = false; } if (empty) { if (!rowIter.hasNext()) { return db; } row = rowIter.next(); } } } else { // First row of data int cellIdx = 0; for (Cell cell : row) { DatatoolHeader header = new DatatoolHeader(db, DatatoolTk.getLabelWithValue("default.field", (cellIdx + 1))); db.addColumn(header); db.addCell(rowIdx, cellIdx, getCellValue(cell)); cellIdx++; } if (cellIdx > 0) { rowIdx++; } } while (rowIter.hasNext()) { row = rowIter.next(); int cellIdx = 0; for (Cell cell : row) { db.addCell(rowIdx, cellIdx, getCellValue(cell)); cellIdx++; } if (cellIdx > 0) { rowIdx++; } } } catch (Exception e) { throw new DatatoolImportException(DatatoolTk.getLabelWithValue("error.import.failed", file.toString()), e); } return db; }
From source file:com.diversityarrays.kdxplore.importdata.excelio.KdxploreWorksheet.java
License:Open Source License
protected <T> DataError processWorksheet(Sheet sheet, Class<T> tClass, EntityProcessor<T> entityProcessor, WorkbookReadResult wrr) {//from w w w . j av a2 s. co m HeadingRow headingRow = null; int nRows = ExcelUtil.getRowCount(sheet); for (int rowIndex = 0; rowIndex < nRows; ++rowIndex) { Row row = sheet.getRow(rowIndex); if (row == null) { continue; } List<String> cellValues = getCellValuesIfAnyNonBlank(row); if (cellValues == null) { continue; } if (headingRow == null) { Either<List<Pair<Integer, String>>, HeadingRow> either = worksheetInfo.scanHeadingRow(cellValues); if (either.isLeft()) { String errmsg = either.left().stream().map(pair -> pair.first + ":" + pair.second) .collect(Collectors.joining(",")); return new DataError(rowIndex, errmsg); } headingRow = either.right(); if (headingRow.importFieldByColumnIndex.isEmpty()) { return new DataError(rowIndex, "No Column Headings found in worksheet '" + sheet.getSheetName() + "'"); } } else { RowData rowData = worksheetInfo.collectImportFields(headingRow.importFieldByColumnIndex, cellValues); Either<DataError, T> pEither = entityProcessor.createEntity(rowIndex); if (pEither.isLeft()) { return pEither.left(); } T entity = pEither.right(); for (Pair<ImportField, String> pair : rowData.importFieldsAndCellValues) { ImportField importField = pair.first; String cellValue = pair.second; Either<String, Object> either = KDSmartDbUtil.convertValueOrError(tClass, importField.field, cellValue); if (either.isLeft()) { return new DataError(rowIndex, either.left()); } try { importField.field.set(entity, either.right()); } catch (IllegalArgumentException | IllegalAccessException e) { String msg = e.getClass().getSimpleName() + ": " + e.getMessage(); return new DataError(rowIndex, msg); } } DataError error = entityProcessor.handleRemainingColumns(rowIndex, entity, headingRow, rowData, wrr); if (error != null) { return error; } } } return null; }
From source file:com.diversityarrays.kdxplore.importdata.excelio.TraitsWorksheet.java
License:Open Source License
@Override public DataError processWorksheet(Sheet sheet, WorkbookReadResult wrr) { int nRows = ExcelUtil.getRowCount(sheet); HeadingRow headingRow = null;//from ww w. ja va 2 s .com int lastColumnIndex = -1; for (int rowIndex = 0; rowIndex < nRows; ++rowIndex) { Row rrow = sheet.getRow(rowIndex); if (rrow == null) { continue; } List<String> cellValues = getCellValuesIfAnyNonBlank(rrow); if (cellValues == null) { continue; } if (headingRow == null) { Either<List<Pair<Integer, String>>, HeadingRow> either = worksheetInfo.scanHeadingRow(cellValues); if (either.isLeft()) { String errmsg = either.left().stream().map(pair -> pair.first + ":" + pair.second) .collect(Collectors.joining(",")); return new DataError(rowIndex, errmsg); } headingRow = either.right(); if (headingRow.importFieldByColumnIndex.isEmpty()) { return new DataError(rowIndex, "No Column Headings found in worksheet '" + sheet.getSheetName() + "'"); } List<Integer> columnIndices = new ArrayList<>(headingRow.importFieldByColumnIndex.keySet()); Collections.sort(columnIndices, Collections.reverseOrder()); ImportField lastImportField = headingRow.importFieldByColumnIndex.get(lastColumnIndex); if (!"traitValRule".equals(lastImportField.fieldName)) { return new DataError(rowIndex, "Last Column Heading must be '" + HDG_TRAIT_VALIDATION + "'"); } } else { Either<DataError, Trait> either = getTraitFromCellValues(worksheetInfo, headingRow, rowIndex, cellValues, lastColumnIndex); if (either.isLeft()) { return either.left(); } String errmsg = wrr.addTrait(either.right()); if (!Check.isEmpty(errmsg)) { return new DataError(rowIndex, errmsg); } } } return null; }
From source file:com.eurodyn.qlack2.fuse.lexicon.impl.LanguageServiceImpl.java
License:EUPL
@Override @Transactional(TxType.REQUIRED)//from w w w . j a v a 2 s . c o m public void uploadLanguage(String languageID, byte[] lgXL) { Map<String, String> translations = new HashMap<>(); try { Workbook wb = WorkbookFactory.create(new BufferedInputStream(new ByteArrayInputStream(lgXL))); for (int si = 0; si < wb.getNumberOfSheets(); si++) { Sheet sheet = wb.getSheetAt(si); String groupName = sheet.getSheetName(); String groupID = null; if (StringUtils.isNotBlank(groupName)) { groupID = Group.findByName(groupName, em).getId(); } // Skip first row (the header of the Excel file) and start // parsing translations. for (int i = 1; i <= sheet.getLastRowNum(); i++) { String keyName = sheet.getRow(i).getCell(0).getStringCellValue(); String keyValue = sheet.getRow(i).getCell(1).getStringCellValue(); translations.put(keyName, keyValue); } keyService.updateTranslationsForLanguageByKeyName(languageID, groupID, translations); } } catch (IOException | InvalidFormatException ex) { // Convert to a runtime exception in order to roll back transaction LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex); throw new QLanguageProcessingException("Error reading Excel file for language " + languageID); } }
From source file:com.evidon.areweprivateyet.Aggregator.java
License:Open Source License
private void createContent(Workbook wb, Sheet s, String map) { Map<String, String> out = new HashMap<String, String>(); int rownum = 2; int cellnum = 0; // create a merged list of domains. domains.clear();// w w w . j a v a 2 s .c om for (String database : results.keySet()) { if (database.equals("baseline")) { Analyzer ra = results.get(database); Map<String, Integer> mapToUse = this.getMap(map, ra); for (String domain : mapToUse.keySet()) { if ((!domains.contains(domain)) && !exclusions.contains(domain)) { domains.add(domain); out.put(domain, ""); } } } } CellStyle numberStyle = wb.createCellStyle(); numberStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("number")); s.setColumnWidth(0, 5000); for (String domain : domains) { cellnum = 0; Row r = s.createRow(rownum); Cell c = r.createCell(cellnum); c.setCellValue(domain); cellnum++; for (String database : results.keySet()) { Analyzer ra = results.get(database); Map<String, Integer> mapToUse = this.getMap(map, ra); c = r.createCell(cellnum); try { if (mapToUse.containsKey(domain)) { c.setCellValue(mapToUse.get(domain)); } else { c.setCellValue(0); } } catch (Exception e) { c.setCellValue(0); } c.setCellStyle(numberStyle); cellnum++; } rownum++; } // Totals. rownum++; cellnum = 1; Row r = s.createRow(rownum); Cell c = r.createCell(0); c.setCellValue("Totals:"); for (int i = 0; i < results.keySet().size(); i++) { c = r.createCell(cellnum); c.setCellType(Cell.CELL_TYPE_FORMULA); c.setCellFormula("SUM(" + getCellLetter(i) + "3:" + getCellLetter(i) + (domains.size() + 2) + ")"); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); evaluator.evaluateFormulaCell(c); if (!totals.containsKey(s.getRow(1).getCell(i + 1).getStringCellValue())) { Map<String, String> contents = new LinkedHashMap<String, String>(); contents.put(s.getSheetName(), c.getNumericCellValue() + ""); totals.put(s.getRow(1).getCell(i + 1).getStringCellValue(), contents); } else { Map<String, String> contents = totals.get(s.getRow(1).getCell(i + 1).getStringCellValue()); contents.put(s.getSheetName(), c.getNumericCellValue() + ""); totals.put(s.getRow(1).getCell(i + 1).getStringCellValue(), contents); } cellnum++; } // Delta/Reduction rownum++; cellnum = 1; r = s.createRow(rownum); c = r.createCell(0); c.setCellValue("Tracking Decrease:"); for (int i = 0; i < results.keySet().size(); i++) { c = r.createCell(cellnum); c.setCellType(Cell.CELL_TYPE_FORMULA); c.setCellFormula("ROUND((100-(" + getCellLetter(i) + (rownum) + "*100/B" + (rownum) + ")),0)"); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); evaluator.evaluateFormulaCell(c); if (!decrease.containsKey(s.getRow(1).getCell(i + 1).getStringCellValue())) { Map<String, String> contents = new LinkedHashMap<String, String>(); contents.put(s.getSheetName(), c.getNumericCellValue() + ""); decrease.put(s.getRow(1).getCell(i + 1).getStringCellValue(), contents); } else { Map<String, String> contents = decrease.get(s.getRow(1).getCell(i + 1).getStringCellValue()); contents.put(s.getSheetName(), c.getNumericCellValue() + ""); decrease.put(s.getRow(1).getCell(i + 1).getStringCellValue(), contents); } cellnum++; } }
From source file:com.evidon.areweprivateyet.Aggregator.java
License:Open Source License
public void createSpreadSheet() throws Exception { int row = 2, cell = 0, sheet = 0; FileOutputStream file = new FileOutputStream(path + "analysis.xls"); Workbook wb = new HSSFWorkbook(); // content: total content length sheet. Sheet s = wb.createSheet(); wb.setSheetName(sheet, "Content Length"); this.createHeader(wb, s, "Total Content Length in MB", 0); Row r = s.createRow(row);/* ww w . j a v a2 s . c o m*/ for (String database : results.keySet()) { Cell c = r.createCell(cell); c.setCellValue(results.get(database).totalContentLength / 1024 / 1024); cell++; } row++; cell = 0; r = s.createRow(row); for (String database : results.keySet()) { Cell c = r.createCell(cell); if (database.equals("baseline")) { c.setCellValue("Decrease:"); Map<String, String> contents = new LinkedHashMap<String, String>(); contents.put(s.getSheetName(), "0"); decrease.put(database, contents); } else { c = r.createCell(cell); c.setCellType(Cell.CELL_TYPE_FORMULA); c.setCellFormula("ROUND((100-(" + getCellLetter(cell - 1) + "3*100/A3)),0)"); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); evaluator.evaluateFormulaCell(c); Map<String, String> contents = new LinkedHashMap<String, String>(); contents.put(s.getSheetName(), c.getNumericCellValue() + ""); decrease.put(database, contents); } cell++; } sheet++; // When content is created, baseline is used as a base for every entry. For example, // if baseline contained doubleclick.com, this will be output and each other analyzer's // map, like ghosterys analyzer is then asked for the content's mapping for doubleclick. // So, if baseline does not contain blah.com, yet ghostery map does, this entry is never // shown in the spreadsheet or any other results. // so this means if we have tracker/whatever URLs in a non-baseline profile // and these URLs are NOT in the baseline profile, // we wouldn't see those trackers/whatever in the final comparison. // content: HTTP Requests s = wb.createSheet(); wb.setSheetName(sheet, "HTTP Requests"); this.createHeader(wb, s, "Pages with One or More HTTP Requests to the Public Suffix", 1); this.createContent(wb, s, "requestCountPerDomain"); sheet++; // content: HTTP Set-Cookie Responses s = wb.createSheet(); wb.setSheetName(sheet, "HTTP Set-Cookie Responses"); this.createHeader(wb, s, "Pages with One or More HTTP Responses from the Public Suffix That Include a Set-Cookie Header", 1); this.createContent(wb, s, "setCookieResponses"); sheet++; // content: Cookie Added - Cookie Deleted s = wb.createSheet(); wb.setSheetName(sheet, "Cookies Added-Deleted"); this.createHeader(wb, s, "Cookies Added - Cookies Deleted Per Domain", 1); this.createContent(wb, s, "cookieTotals"); sheet++; // content: Local Storage counts per domain s = wb.createSheet(); wb.setSheetName(sheet, "Local Storage"); this.createHeader(wb, s, "Local Storage counts per domain", 1); this.createContent(wb, s, "localStorageContents"); sheet++; // content: Pretty Chart s = wb.createSheet(); wb.setSheetName(sheet, "Overall"); int rownum = 0, cellnum = 0; // Header r = s.createRow(rownum); Cell c = r.createCell(0); s.setColumnWidth(0, 8000); c.setCellValue( "Overall effectiveness measured by percentage of decrease vs baseline (0 for any negative effect)"); rownum++; r = s.createRow(rownum); cellnum++; for (String database : decrease.keySet()) { if (database.equals("baseline")) { continue; } c = r.createCell(cellnum); c.setCellValue(database); CellStyle cs = wb.createCellStyle(); Font f = wb.createFont(); f.setBoldweight(Font.BOLDWEIGHT_BOLD); cs.setFont(f); c.setCellStyle(cs); cellnum++; } CellStyle numberStyle = wb.createCellStyle(); numberStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("number")); // Content for (String type : decrease.get("baseline").keySet()) { cellnum = 0; rownum++; r = s.createRow(rownum); c = r.createCell(cellnum); c.setCellValue(type); cellnum++; for (String database : decrease.keySet()) { if (database.equals("baseline")) { continue; } c = r.createCell(cellnum); c.setCellStyle(numberStyle); double decreaseValue = Double.parseDouble(decrease.get(database).get(type)); if (decreaseValue < 0) decreaseValue = 0; c.setCellValue(decreaseValue); cellnum++; } } /* for (String database : decrease.keySet()) { for (String type : decrease.get(database).keySet()) { System.out.println(database + "|" + type + "|" + decrease.get(database).get(type)); } } */ wb.write(file); file.close(); }
From source file:com.exilant.exility.core.XLSReader.java
License:Open Source License
/** * Purpose of this method to read an Microsoft Workbook in DataCollection dc * supplied along with workbook. Each sheet will be a grid in dc with the * same name as sheet name.// ww w .jav a 2 s. c o m * * @param wb * This is an instance of MS excel workbook(i.e .xls or .xlsx) * created by POI WorkbookFactory. * @param dc */ public void readAWorkbook(Workbook wb, DataCollection dc) { if (wb == null || dc == null) { throw new IllegalArgumentException(XLSReader.ILLEGAL_ARGUMENT); } int nbrSheets = wb.getNumberOfSheets(); String sheetName = null; String gridName = dc.getTextValue("gridName", null); Sheet sheet = null; int nbrColumns = -1; int nbrPhysicalRows = 0; for (int k = 0; k < nbrSheets; k++) { sheet = wb.getSheetAt(k); sheetName = sheet.getSheetName(); nbrPhysicalRows = sheet.getPhysicalNumberOfRows(); if (nbrPhysicalRows < 2) { Spit.out(sheetName + XLSReader.INSUFFICIENT_DATA_ROWS); // dc.addMessage(XLSReader.INSUFFICIENT_ROWS, sheetName + // XLSReader.INSUFFICIENT_DATA_ROWS); continue; } try { nbrColumns = this.readASheet(sheet); /** * swallow all the exceptions during excel sheet reading and put * appropriate message. While reading excel following exceptions * can come: 1. IllegalStateExcetion if column data type * mismatch in excel sheet. 2. ExilityException etc. */ } catch (ExilityException e) { String msg = this.replaceMessageParams(XLSReader.EXCEPTION_MSG, new String[] { sheetName, e.getMessage() }); dc.addError(msg); Spit.out(e); } if (nbrColumns == -1) { continue; } /** * This is for little more flexibility to user if they have only one * sheet to be read and has supplied a gridName along with service * then let set first sheet one as given gridName(In case of simple * file upload and read content as grid) */ if (gridName != null) { sheetName = gridName; gridName = null; } dc.addGrid(sheetName, this.getGrid()); Spit.out(sheetName + " added to dc with " + this.rows.size() + " row(s)"); this.columnsData.clear(); this.rows.clear(); // this.printXlSRec(dc.getGrid(sheetName).getRawData()); } }
From source file:com.exilant.exility.core.XLSReader.java
License:Open Source License
/** * Purpose of this method to read rows from given Excel Sheet. * //from ww w. ja v a2 s. c om * @param sheet * an Instance of .ss.usermodel.Sheet class from POI apache. * @return -1 if fail to read sheet else number of columns read successfully * from the sheet. * @throws ExilityException */ public int readASheet(Sheet sheet) throws ExilityException { int nonEmptyFirstRowIdx = 0; int lastRowIdx = 0; int nbrPhysicalRows = sheet.getPhysicalNumberOfRows(); String sheetName = sheet.getSheetName(); if (nbrPhysicalRows < 2) { Spit.out(sheetName + XLSReader.INSUFFICIENT_DATA_ROWS); return -1; } try { nonEmptyFirstRowIdx = sheet.getFirstRowNum(); lastRowIdx = sheet.getLastRowNum(); /* * For checking to valid header.First row must be header. */ Row headerRow = sheet.getRow(nonEmptyFirstRowIdx); int nbrCol = headerRow.getPhysicalNumberOfCells(); for (int colIdx = 0; colIdx < nbrCol; colIdx++) { Cell hCell = headerRow.getCell(colIdx); if (hCell == null || hCell.getCellType() == Cell.CELL_TYPE_BLANK) { Spit.out("Error--->Found blank column " + (colIdx + 1) + " in Sheet " + sheetName + XLSReader.INVALID_HEADER); this.columnsData.clear(); return -1; } String columnName = hCell.getStringCellValue(); this.setDataType(columnName, colIdx); } } catch (Exception e) { Spit.out(sheetName + XLSReader.INVALID_HEADER); Spit.out(e); return -1; } int nbrColumnsInARow = this.columnsData.size(); /* * Loop starts with second data row that is first row(header as column * name) excluded. */ Spit.out(sheetName + ":\n"); for (int rowIdx = (nonEmptyFirstRowIdx + 1); rowIdx <= lastRowIdx; rowIdx++) { Row row = sheet.getRow(rowIdx); if (row == null) { Spit.out(XLSReader.SKIP_BLANK_ROW + rowIdx); continue; } /** * readARow() will throws ExilityException if something goes wrong. */ this.readARow(row, nbrColumnsInARow); } return this.columnsData.size(); }