List of usage examples for org.apache.poi.ss.usermodel Row getCell
Cell getCell(int cellnum);
From source file:biz.webgate.dominoext.poi.component.kernel.WorkbookProcessor.java
License:Apache License
public void findAndReplaceAll(Sheet sheet, String find, Object replace) { if (replace == null) { replace = ""; }//from w w w . ja v a 2 s . c o m int iLastRow = sheet.getLastRowNum(); for (int i1 = 0; i1 < iLastRow; i1++) { Row currentRow = sheet.getRow(i1); if (currentRow != null) { int iLastCell = currentRow.getLastCellNum(); for (int i = 0; i < iLastCell; i++) { Cell currentCell = currentRow.getCell(i); if (currentCell != null && currentCell.getCellType() == Cell.CELL_TYPE_STRING) { if (currentCell.getStringCellValue().contains(find)) { currentCell.setCellValue(currentCell.getStringCellValue().replace(find, "" + replace)); } } } } } }
From source file:blanco.commons.calc.parser.AbstractBlancoCalcParser.java
License:Open Source License
/** * ???// ww w . ja v a2 s.co m * * @param sheet * * @throws SAXException * SAX???? */ private final void parseSheet(final Sheet sheet) throws SAXException { // ????? AttributesImpl attrImpl = new AttributesImpl(); attrImpl.addAttribute("", "name", "name", "CDATA", sheet.getSheetName()); getContentHandler().startElement("", (String) getProperty(URI_PROPERTY_NAME_SHEET), (String) getProperty(URI_PROPERTY_NAME_SHEET), attrImpl); startSheet(sheet.getSheetName()); //getLastRowNum()??0???? +1? int maxRows = sheet.getLastRowNum() + 1; for (int row = 0; row < maxRows; row++) { startRow(row + 1); Row line = sheet.getRow(row); if (line != null) { for (int column = 0; column < line.getLastCellNum(); column++) { startColumn(column + 1); Cell cell = line.getCell(column); // ?trim()?????????????? String value = getCellValue(cell); fireCell(column + 1, row + 1, value); endColumn(column + 1); } } endRow(row + 1); } endSheet(sheet); // ????? getContentHandler().endElement("", (String) getProperty(URI_PROPERTY_NAME_SHEET), (String) getProperty(URI_PROPERTY_NAME_SHEET)); }
From source file:bo.com.offercruzmail.LectorBandejaCorreo.java
private Multipart procesarPorAdjunto(Message mensaje, Integer idUsuario) throws MessagingException { adjunto = null;//from www. jav a 2 s. c om try { //No se pudo procesar por asunto, leer el adjunto si tiene adjunto = UtilitariosMensajes.bajarPrimerAdjunto(mensaje); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); return FormadorMensajes.getMensajeUsuarioAyuda(); } if (adjunto == null) { return FormadorMensajes.getMensajeUsuarioAyuda(); } FileInputStream fis = null; try { Workbook libro; fis = new FileInputStream(adjunto); libro = WorkbookFactory.create(fis); Sheet hoja = libro.getSheetAt(0); Row fila = hoja.getRow(0); if (fila == null) { return FormadorMensajes.getMensajeUsuarioAyuda(); } Cell celda = fila.getCell(0); if (celda == null) { return FormadorMensajes.getMensajeUsuarioAyuda(); } String nombreEntidad = HojaExcelHelper.getValorCelda(celda).toLowerCase(); interprete = InterpretadorMensajeGenerico.getMapaObjetos().get(nombreEntidad); if (interprete == null) { return FormadorMensajes.getMensajeUsuarioAyuda(); } interprete.setLectorBandejaCorreo(this); interprete.setIdUsuario(idUsuario); interprete.setNombreEntidad(nombreEntidad); return interprete.interpretarHojaExcel(hoja); } catch (IOException | InvalidFormatException ex) { LOG.log(Level.SEVERE, "Error Leyendo adjunto", ex); return FormadorMensajes.getMensajeUsuarioAyuda(); } finally { if (fis != null) { try { fis.close(); } catch (IOException ex) { Logger.getLogger(LectorBandejaCorreo.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:bo.com.offercruzmail.utils.HojaExcelHelper.java
public Cell getCelda(int rowIndex, int colIndex) { Row fila = hoja.getRow(rowIndex); if (fila == null) { fila = hoja.createRow(rowIndex); }//from w w w .ja v a2 s .c o m Cell celda = fila.getCell(colIndex); if (celda == null) { celda = fila.createCell(colIndex); } return celda; }
From source file:bouttime.fileinput.ExcelFileInput.java
License:Open Source License
/** * Input wrestlers from a MS Excel formatted file. * * @param file File to read data from// ww w . j av a2 s . c o m * @param config Map of config parameters for column indexes, start and stop * row indexes, and the sheet number * @param dao Data access object * * @return A FileInputResult object with the results of the input operation */ private FileInputResult addWrestlersFromFile(File file, Map config, Dao dao) { Integer recordsProcessed = Integer.valueOf(0); Integer recordsAccepted = Integer.valueOf(0); Integer recordsRejected = Integer.valueOf(0); List<String> rejects = new ArrayList<String>(); try { int sheetNumber = Integer.parseInt((String) config.get("sheet")) - 1; int startRow = Integer.parseInt((String) config.get("startRow")) - 1; int endRow = Integer.parseInt((String) config.get("endRow")); int fNameCol = Integer.parseInt((String) config.get("firstName")) - 1; int lNameCol = Integer.parseInt((String) config.get("lastName")) - 1; int tNameCol = Integer.parseInt((String) config.get("teamName")) - 1; int gNameCol = Integer.parseInt((String) config.get("geo")) - 1; int classCol = Integer.parseInt((String) config.get("classification")) - 1; int divCol = Integer.parseInt((String) config.get("division")) - 1; int wtClassCol = Integer.parseInt((String) config.get("weightClass")) - 1; int actWtCol = Integer.parseInt((String) config.get("actualWeight")) - 1; int levelCol = Integer.parseInt((String) config.get("level")) - 1; int idCol = Integer.parseInt((String) config.get("serialNumber")) - 1; InputStream inp = new FileInputStream(file); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(sheetNumber); logger.info("Excel File Input configuration :" + "\n sheet=" + sheetNumber + "\n startRow=" + startRow + "\n endRow=" + endRow + "\n first=" + fNameCol + "\n last=" + lNameCol + "\n team=" + tNameCol + "\n geo=" + gNameCol + "\n class=" + classCol + "\n div=" + divCol + "\n" + "\n wtClass=" + wtClassCol + "\n actWt=" + actWtCol + "\n level=" + levelCol + "\n id=" + idCol); int i = startRow; while (i < endRow) { Wrestler w = new Wrestler(); Row row = sheet.getRow(i); if (row == null) { logger.warn("Row is null : " + i); i++; continue; } if (fNameCol >= 0) { String fName = row.getCell(fNameCol).getRichStringCellValue().getString(); // Should always have a first name, so this is a // reasonable check for the end of data. if (fName.isEmpty()) break; // found end of data w.setFirstName(fName.trim()); } if (lNameCol >= 0) { String lName = row.getCell(lNameCol).getRichStringCellValue().getString(); // Should always have a last name, so this is a // reasonable check for the end of data. if (lName.isEmpty()) break; // found end of data w.setLastName(lName.trim()); } if (divCol >= 0) { String div; if (row.getCell(divCol).getCellType() == Cell.CELL_TYPE_STRING) { div = row.getCell(divCol).getRichStringCellValue().getString(); } else { div = Long.valueOf(Double.valueOf(row.getCell(divCol).getNumericCellValue()).longValue()) .toString(); } w.setAgeDivision(div.trim()); } if (wtClassCol >= 0) { String wtClass; if (row.getCell(wtClassCol).getCellType() == Cell.CELL_TYPE_STRING) { wtClass = row.getCell(wtClassCol).getRichStringCellValue().getString(); } else { wtClass = Long .valueOf(Double.valueOf(row.getCell(wtClassCol).getNumericCellValue()).longValue()) .toString(); } w.setWeightClass(wtClass.trim()); } if (actWtCol >= 0) { String actWt; if (row.getCell(actWtCol).getCellType() == Cell.CELL_TYPE_STRING) { actWt = row.getCell(actWtCol).getRichStringCellValue().getString(); } else { actWt = Long .valueOf(Double.valueOf(row.getCell(actWtCol).getNumericCellValue()).longValue()) .toString(); } w.setActualWeight(actWt.trim()); } if (classCol >= 0) { String classification; if (row.getCell(classCol).getCellType() == Cell.CELL_TYPE_STRING) { classification = row.getCell(classCol).getRichStringCellValue().getString(); } else { classification = Long .valueOf(Double.valueOf(row.getCell(classCol).getNumericCellValue()).longValue()) .toString(); } w.setClassification(classification.trim()); } if (tNameCol >= 0) { String tName; if (row.getCell(tNameCol).getCellType() == Cell.CELL_TYPE_STRING) { tName = row.getCell(tNameCol).getRichStringCellValue().getString(); } else { tName = Long .valueOf(Double.valueOf(row.getCell(tNameCol).getNumericCellValue()).longValue()) .toString(); } w.setTeamName(tName.trim()); } if (gNameCol >= 0) { String gName; if (row.getCell(gNameCol).getCellType() == Cell.CELL_TYPE_STRING) { gName = row.getCell(gNameCol).getRichStringCellValue().getString(); } else { gName = Long .valueOf(Double.valueOf(row.getCell(gNameCol).getNumericCellValue()).longValue()) .toString(); } w.setGeo(gName.trim()); } if (idCol >= 0) { String id; if (row.getCell(idCol).getCellType() == Cell.CELL_TYPE_STRING) { id = row.getCell(idCol).getRichStringCellValue().getString(); } else { id = Long.valueOf(Double.valueOf(row.getCell(idCol).getNumericCellValue()).longValue()) .toString(); } w.setSerialNumber(id.trim()); } if (levelCol >= 0) { String level; if (row.getCell(levelCol).getCellType() == Cell.CELL_TYPE_STRING) { level = row.getCell(levelCol).getRichStringCellValue().getString(); } else { level = Long .valueOf(Double.valueOf(row.getCell(levelCol).getNumericCellValue()).longValue()) .toString(); } w.setLevel(level.trim()); } recordsProcessed++; if (dao.addWrestler(w)) { recordsAccepted++; logger.debug("Added wrestler : " + w); } else { recordsRejected++; rejects.add(String.format("%s %s", w.getFirstName(), w.getLastName())); logger.warn("Duplicate: " + w.getFirstName() + " " + w.getLastName()); } i++; } } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException ife) { JFrame mainFrame = BoutTimeApp.getApplication().getMainFrame(); JOptionPane.showMessageDialog(mainFrame, "Error while handling the spreadsheet file.\n\n" + "This is not a file in an Excel file.", "Spreadsheet file error", JOptionPane.ERROR_MESSAGE); logger.error(ife.getLocalizedMessage() + "\n" + Arrays.toString(ife.getStackTrace())); } catch (Exception e) { JFrame mainFrame = BoutTimeApp.getApplication().getMainFrame(); JOptionPane.showMessageDialog(mainFrame, "Error while handling the spreadsheet file.\n\n" + e, "Spreadsheet file error", JOptionPane.ERROR_MESSAGE); logger.error(e.getLocalizedMessage() + "\n" + Arrays.toString(e.getStackTrace())); } return (new FileInputResult(recordsProcessed, recordsAccepted, recordsRejected, rejects)); }
From source file:br.com.gartech.nfse.integrador.util.ExcelHelper.java
private String workbook2xml(org.apache.poi.ss.usermodel.Workbook workbook) { String result = null;/*w ww .ja v a2 s . co m*/ StringBuffer sb = null; Sheet sheet = null; if (workbook != null && workbook.getSheetAt(0) != null) { String newLine = System.getProperty("line.separator"); sb = new StringBuffer(); sb.append("<?xml version=\"1.0\" ?>"); sb.append(newLine); sb.append("<!DOCTYPE workbook SYSTEM \"workbook.dtd\">"); sb.append(newLine); sb.append(newLine); sb.append("<workbook>"); sb.append(newLine); for (int i = 0; i < workbook.getNumberOfSheets(); ++i) { sheet = workbook.getSheetAt(i); if (sheet != null && sheet.rowIterator().hasNext()) { sb.append("\t"); sb.append("<sheet>"); sb.append(newLine); sb.append("\t\t"); sb.append("<name><![CDATA[" + sheet.getSheetName() + "]]></name>"); sb.append(newLine); int j = 0; for (Iterator<Row> iterator = sheet.rowIterator(); iterator.hasNext();) { Row row = (Row) iterator.next(); int k = 0; if (row.getCell(0) != null && row.getCell(0).getStringCellValue() != null && row.getCell(0).getStringCellValue().trim().length() > 0) { sb.append("\t\t"); sb.append("<row number=\"" + j + "\">"); sb.append(newLine); for (Cell cell : row) { sb.append("\t\t\t"); sb.append("<col number=\"" + k + "\">"); sb.append("<![CDATA[" + cellToString(cell) + "]]>"); sb.append("</col>"); sb.append(newLine); k++; } sb.append("\t\t"); sb.append("</row>"); sb.append(newLine); } j++; } sb.append("\t"); sb.append("</sheet>"); sb.append(newLine); } } sb.append("</workbook>"); sb.append(newLine); result = sb.toString(); } return result; }
From source file:br.com.gartech.nfse.integrador.util.ExcelHelper.java
public Workbook bindXml(Document document, Workbook workbook) throws XPathExpressionException { XPath xPath = XPathFactory.newInstance().newXPath(); NodeList cellValueList = (NodeList) xPath.evaluate("//cellValue", document, XPathConstants.NODESET); NodeList rowNodeList = (NodeList) xPath.evaluate("//row", document, XPathConstants.NODESET); Node rowsNode = (Node) xPath.evaluate("//rows", document, XPathConstants.NODE); Sheet sheet = workbook.getSheetAt(0); for (int i = 0; i < cellValueList.getLength(); i++) { Node cellValue = cellValueList.item(i); String cellName = cellValue.getAttributes().getNamedItem("ref").getTextContent(); String type = cellValue.getAttributes().getNamedItem("type").getTextContent(); String value = cellValue.getTextContent(); CellReference cellRef = new CellReference(cellName); Row row = sheet.getRow(cellRef.getRow()); Cell cell = row.getCell(cellRef.getCol()); if ("number".equals(type)) { double doubleValue = Double.valueOf(value); cell.setCellValue(doubleValue); } else if ("date".equals(type)) { Date dateValue = new Date(Long.valueOf(value)); cell.setCellValue(dateValue); } else if ("bool".equals(type)) { boolean boolValue = Boolean.valueOf(value); cell.setCellValue(boolValue); } else if ("formula".equals(type)) { cell.setCellFormula(value);//from w w w. jav a2 s. co m } else { cell.setCellValue(value); } } if (rowsNode != null && rowNodeList != null && rowNodeList.getLength() > 0) { CellReference startCellRef = new CellReference( rowsNode.getAttributes().getNamedItem("startRef").getTextContent()); CellReference endCellRef = new CellReference( rowsNode.getAttributes().getNamedItem("endRef").getTextContent()); int startRowIndex = startCellRef.getRow(); int startColIndex = startCellRef.getCol(); int endColIndex = endCellRef.getCol(); CellStyle[] cellStyles = new CellStyle[endColIndex + 1]; Row firstRow = sheet.getRow(startRowIndex); for (int i = startColIndex; i <= endColIndex; i++) { cellStyles[i] = firstRow.getCell(i).getCellStyle(); } for (int i = startRowIndex; i <= sheet.getLastRowNum(); i++) { Row templeteRow = sheet.getRow(i); if (templeteRow != null) { sheet.removeRow(templeteRow); } } int rowNodeIndex = 0; for (int i = startRowIndex; i < startRowIndex + rowNodeList.getLength(); i++) { Row row = sheet.createRow(i); int cellNodeIndex = 0; Node rowNode = rowNodeList.item(rowNodeIndex); NodeList rowValueNodeList = rowNode.getChildNodes(); ArrayList<Node> nodes = new ArrayList<Node>(); for (int idx = 0; idx < rowValueNodeList.getLength(); idx++) { Node currentNode = rowValueNodeList.item(idx); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { nodes.add(currentNode); } } for (int j = startColIndex; j <= endColIndex; j++) { Cell cell = row.createCell(j); Node cellNode = nodes.get(cellNodeIndex); String type = cellNode.getAttributes().getNamedItem("type").getTextContent(); String value = cellNode.getTextContent(); CellStyle cellStyle = cellStyles[j]; cell.setCellStyle(cellStyle); if ("number".equals(type)) { double doubleValue = Double.valueOf(value); cell.setCellValue(doubleValue); } else if ("date".equals(type)) { Date dateValue = new Date(Long.valueOf(value)); cell.setCellValue(dateValue); } else if ("bool".equals(type)) { boolean boolValue = Boolean.valueOf(value); cell.setCellValue(boolValue); } else if ("formula".equals(type)) { cell.setCellType(HSSFCell.CELL_TYPE_FORMULA); cell.setCellFormula(value); } else if ("string".equals(type)) { if (value != null && value.length() > 0) { cell.setCellValue(value); } else { cell.setCellValue(""); } } else { cell.setCellValue(""); } cellNodeIndex++; } rowNodeIndex++; } } return workbook; }
From source file:br.com.tecsinapse.dataio.importer.parser.SpreadsheetParser.java
License:LGPL
private List<T> parseCurrentSheet() throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { List<T> list = new ArrayList<>(); workbook = getWorkbook();// ww w. java 2 s . com Sheet sheet = workbook.getSheetAt(this.sheetNumber); final FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); Map<Method, TableCellMapping> cellMappingByMethod = ImporterUtils.getMappedMethods(clazz, group); final Constructor<T> constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); int i = 0; Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); i++; if (i <= headersRows) { continue; } T instance = constructor.newInstance(); for (Entry<Method, TableCellMapping> methodTcm : cellMappingByMethod.entrySet()) { TableCellMapping tcm = methodTcm.getValue(); ImporterUtils.parseSpreadsheetCell(tcm.converter(), evaluator, row.getCell(tcm.columnIndex()), methodTcm.getKey(), instance, exporterFormatter, useFormatterToParseValueAsString); } list.add(instance); } return list; }
From source file:br.com.tecsinapse.exporter.importer.parser.SpreadsheetParser.java
License:LGPL
private List<T> parseCurrentSheet() throws IllegalAccessException, InstantiationException, InvocationTargetException, IOException, InvalidFormatException, NoSuchMethodException { List<T> list = new ArrayList<>(); workbook = getWorkbook();// ww w .jav a 2 s . co m Sheet sheet = workbook.getSheetAt(this.sheetNumber); final FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); Map<Method, TableCellMapping> cellMappingByMethod = ImporterUtils.getMappedMethods(clazz, group); final Constructor<T> constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); int i = 0; Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); i++; if (i <= headersRows) { continue; } T instance = constructor.newInstance(); for (Entry<Method, TableCellMapping> methodTcm : cellMappingByMethod.entrySet()) { TableCellMapping tcm = methodTcm.getValue(); ImporterUtils.parseSpreadsheetCell(tcm.converter(), evaluator, row.getCell(tcm.columnIndex()), methodTcm.getKey(), instance, exporterFormatter, useFormatterToParseValueAsString); } list.add(instance); } return list; }
From source file:br.sp.telesul.service.ExportServiceImpl.java
public void writeExcel(String templateHead, String[] columns, HSSFWorkbook workbook) { try {// w w w . j a v a2 s . c om List<Funcionario> funcionarios = funcionarioService.search(); HSSFSheet sheet = workbook.createSheet(templateHead); Row rowHeading = sheet.createRow(0); for (int i = 0; i < columns.length; i++) { rowHeading.createCell(i).setCellValue(columns[i]); } for (int i = 0; i < columns.length; i++) { CellStyle stylerowHeading = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBold(true); font.setFontName(HSSFFont.FONT_ARIAL); font.setFontHeightInPoints((short) 11); font.setColor(HSSFColor.WHITE.index); stylerowHeading.setFont(font); stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER); stylerowHeading.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index); stylerowHeading.setFillPattern(CellStyle.SOLID_FOREGROUND); rowHeading.getCell(i).setCellStyle(stylerowHeading); } int r = 1; for (Funcionario f : funcionarios) { Row row = sheet.createRow(r); Cell Nome = row.createCell(0); Nome.setCellValue(f.getNome()); Cell cargo = row.createCell(1); cargo.setCellValue(f.getCargo()); Cell dtAdmissao = row.createCell(2); dtAdmissao.setCellValue(f.getDtAdmissao()); CellStyle styleDate = workbook.createCellStyle(); HSSFDataFormat dfAdmissao = workbook.createDataFormat(); styleDate.setDataFormat(dfAdmissao.getFormat("dd/mm/yyyy")); dtAdmissao.setCellStyle(styleDate); Cell area = row.createCell(3); area.setCellValue(f.getArea()); Cell gestor = row.createCell(4); gestor.setCellValue(f.getGestor()); try { Cell email = row.createCell(5); email.setCellValue(f.getEmail()); } catch (NullPointerException ne) { } try { Cell telefone = row.createCell(6); telefone.setCellValue(f.getTelefone()); } catch (NullPointerException e) { } try { Cell celular = row.createCell(7); celular.setCellValue(f.getCelular()); } catch (NullPointerException e) { } r++; } for (int i = 0; i < columns.length; i++) { sheet.autoSizeColumn(i); } } catch (Exception e) { logger.error("Error gerate Report: " + e); System.out.println("Error" + e); } }