List of usage examples for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem
public POIFSFileSystem(InputStream stream) throws IOException
From source file:Login.ventas.fpagosvarios.java
private void readExcelFile(String fileName) { /**//w w w . j a va 2 s. c om * Create a new instance for cellDataList */ cellDataList = new ArrayList(); try { /** * Create a new instance for FileInputStream class */ FileInputStream fileInputStream = new FileInputStream(fileName); /** * Create a new instance for POIFSFileSystem class */ POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream); /* * Create a new instance for HSSFWorkBook Class */ HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem); HSSFSheet hssfSheet = workBook.getSheetAt(0); /** * Iterate the rows and cells of the spreadsheet * to get all the datas. */ Iterator rowIterator = hssfSheet.rowIterator(); rowIterator.next(); while (rowIterator.hasNext()) { HSSFRow hssfRow = (HSSFRow) rowIterator.next(); Iterator iterator = hssfRow.cellIterator(); List cellTempList = new ArrayList(); while (iterator.hasNext()) { HSSFCell hssfCell = (HSSFCell) iterator.next(); cellTempList.add(hssfCell); } cellDataList.add(cellTempList); } } catch (Exception ex) { System.out.println(ex); } }
From source file:mj.ocraptor.extraction.tika.parser.microsoft.ooxml.AbstractOOXMLExtractor.java
License:Apache License
/** * Handles an embedded OLE object in the document *//*from w ww. j a v a 2 s. co m*/ private void handleEmbeddedOLE(PackagePart part, ContentHandler handler, String rel) throws IOException, SAXException { // A POIFSFileSystem needs to be at least 3 blocks big to be valid // TODO: TIKA-1118 Upgrade to POI 4.0 then enable this block of code // if (part.getSize() >= 0 && part.getSize() < 512*3) { // // Too small, skip // return; // } // Open the POIFS (OLE2) structure and process POIFSFileSystem fs = new POIFSFileSystem(part.getInputStream()); try { Metadata metadata = new Metadata(); TikaInputStream stream = null; metadata.set(Metadata.EMBEDDED_RELATIONSHIP_ID, rel); DirectoryNode root = fs.getRoot(); POIFSDocumentType type = POIFSDocumentType.detectType(root); if (root.hasEntry("CONTENTS") && root.hasEntry("\u0001Ole") && root.hasEntry("\u0001CompObj") && root.hasEntry("\u0003ObjInfo")) { // TIKA-704: OLE 2.0 embedded non-Office document? stream = TikaInputStream.get(fs.createDocumentInputStream("CONTENTS")); if (embeddedExtractor.shouldParseEmbedded(metadata)) { embeddedExtractor.parseEmbedded(stream, new EmbeddedContentHandler(handler), metadata, false); } } else if (POIFSDocumentType.OLE10_NATIVE == type) { // TIKA-704: OLE 1.0 embedded document Ole10Native ole = Ole10Native.createFromEmbeddedOleObject(fs); metadata.set(Metadata.RESOURCE_NAME_KEY, ole.getLabel()); byte[] data = ole.getDataBuffer(); if (data != null) { stream = TikaInputStream.get(data); } if (stream != null && embeddedExtractor.shouldParseEmbedded(metadata)) { embeddedExtractor.parseEmbedded(stream, new EmbeddedContentHandler(handler), metadata, false); } } else { handleEmbeddedFile(part, handler, rel); } } catch (FileNotFoundException e) { // There was no CONTENTS entry, so skip this part } catch (Ole10NativeException e) { // Could not process an OLE 1.0 entry, so skip this part } }
From source file:model.bank.BankTransDAO.java
/** * Metodo que permiete importar las transacciones o movimientos de una cuenta bancaria * desde un archivo de excel emitido por el Banco Internacional * @param idBankAccount numero de id de la cuenta a la que se importaran los datos * @param fileXls <b>File</b> del archivo excel con los datos a importar * @param hacerArchivoLog/*w w w . j a va 2 s. co m*/ * @return el numero de registros agregados * @throws java.lang.ClassNotFoundException * @throws java.sql.SQLException */ public static int importExcel(int idBankAccount, File fileXls, boolean hacerArchivoLog) throws ClassNotFoundException, SQLException { int rowsImported = 0; DknConsole.msg(Thread.currentThread().getStackTrace()[1].toString(), "Importando datos desde: " + fileXls.getAbsolutePath() + " - a idcuenta: " + idBankAccount); if (idBankAccount > 0 && fileXls != null) { int numRegImportados = 0; FileTxt archLog = null; if (fileXls.exists()) { // if (hacerArchivoLog) { // String nombreArchLog = fileXls.getAbsolutePath(); // nombreArchLog.replace(".xlsx", ".log"); // nombreArchLog.replace(".xls", ".log"); // archLog = new FileTxt(nombreArchLog); // DknConsole.msg(Thread.currentThread().getStackTrace()[1].toString(), "Importando desde Excel. Archivo: " + archLog.getFile().getAbsolutePath() + "*******************"); // } try { // crear un stream POIFSFileSystem poiFS; poiFS = new POIFSFileSystem(new FileInputStream(fileXls)); // if (hacerArchivoLog) { // archLog.open(FileTxt.OpenMode.WRITE); // } // crear una hoja de excel HSSFWorkbook libro = new HSSFWorkbook(poiFS); HSSFSheet sheet = libro.getSheetAt(0); HSSFRow row; HSSFCell cell; Iterator itr = sheet.rowIterator(); // extraer la informacion a un arrayList int rowsCount = 0; BankTrans trans = new BankTrans(); while (itr.hasNext()) { // reviso fila por fila row = (HSSFRow) itr.next(); if (rowsCount >= 4) { // si la fila es la 4 o mayor importo los datos Iterator itc = row.cellIterator(); trans.setIdBankAccount(idBankAccount); trans.setValue(0.0); trans.setIdRegType(2); // <2> = registro importado int colCount = 0; double value = 0; while (itc.hasNext()) { // reviso celda por celda cell = (HSSFCell) itc.next(); // leo la informacion de la celda if (cell != null) { // si la celda no es nula switch (colCount) { case 0: // columna 0, nada break; case 1: // columna 1, fecha trans.setDate(DateTime.getStringToDateUtil(cell.getStringCellValue(), AppGlobal.getFormatDate())); break; case 2: // columna 2, tipo de transaccion String codTipo = cell.getStringCellValue().trim(); trans.setType(codTipo); Type btt = TypeDAO.get("banktranstypes", codTipo); if (btt != null) { trans.setIdType(btt.getId()); } else { String texto = "Tipo de transanccion bancaria no encontrada: " + codTipo + ". Creandola"; DknConsole.warning(Thread.currentThread().getStackTrace()[1].toString(), texto); VMessage.show(texto); btt = new Type(); btt.setCode(codTipo); btt.setName(codTipo); btt.setDescription(codTipo); btt.setActive(true); if (TypeDAO.update("banktranstypes", btt) > 0) { Type btt1 = TypeDAO.get("banktranstypes", codTipo); if (btt1 != null) { trans.setIdType(btt1.getId()); DknConsole.msg( Thread.currentThread().getStackTrace()[1].toString(), "Creada y utilizando el Tipo de transaccin bancaria id: " + btt1.getId() + " trans.id: " + trans.getIdType()); } } else { DknConsole.error( Thread.currentThread().getStackTrace()[1].toString(), "Tipo de transaccin bancaria No se pudo crear. Cdigo: " + codTipo); } } break; case 3: // columna 3, numero de transaccin trans.setNumber(cell.getStringCellValue().trim()); break; case 4: // columna 4, nada break; case 5: // columna 5, observaciones trans.setObservations(cell.getStringCellValue().trim()); break; case 6: // columna 6, nada break; case 7: // columna 7, valor debito if (cell.getNumericCellValue() > 0) { value = cell.getNumericCellValue(); value *= -1; trans.setValue(value); } break; case 8: // columna 8, valor credito if (cell.getNumericCellValue() > 0) { value = cell.getNumericCellValue(); trans.setValue(value); } break; default: break; } // fin del switch } // Fin celda nula colCount++; } // Fin while de celdas // System.out.println("Agregando: " + trans); String error = BankTransDAO.validate(trans); if (error == null) { if (BankTransDAO.update(trans) >= 0) { numRegImportados++; DknConsole.msg(Thread.currentThread().getStackTrace()[1].toString(), "Agregado: " + trans.getNumber()); if (hacerArchivoLog) { archLog.writeLine("Agregado: " + trans); } } else { DknConsole.warning(Thread.currentThread().getStackTrace()[1].toString(), "NO agregado: " + trans.getNumber()); if (hacerArchivoLog) { archLog.writeLine("NO agregado: " + trans); } } } else { DknConsole.error(Thread.currentThread().getStackTrace()[1].toString(), "NO paso la validacion: " + error + " - " + trans.getNumber()); if (hacerArchivoLog) { archLog.writeLine("NO paso la validacion: " + error + " - " + trans); } } } rowsCount++; } // Fin while de filas rowsImported = numRegImportados; DknConsole.msg(Thread.currentThread().getStackTrace()[1].toString(), "Importacion completa. Total " + numRegImportados + " registros importados."); // grabar los datos en la base de datos } catch (FileNotFoundException ex) { Logger.getLogger(BankTransDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | ParseException ex) { Logger.getLogger(BankTransDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { if (hacerArchivoLog) { try { archLog.close(); } catch (IOException ex) { Logger.getLogger(BankTransDAO.class.getName()).log(Level.SEVERE, null, ex); } } } // JOptionPane.showMessageDialog(this, AppConfig.IMPORTACION_TEXTO, AppConfig.IMPORTACION_TITULO, JOptionPane.INFORMATION_MESSAGE); } else { DknConsole.error(Thread.currentThread().getStackTrace()[1].toString(), "Archivo no existe."); } } else { DknConsole.error(Thread.currentThread().getStackTrace()[1].toString(), "Archivo o cuenta no indicadas."); } return rowsImported; }
From source file:Modelo.EscribirWord.java
public void crearWord(Objeto obj) throws IOException { String filePath = "HojaInventarioTemplate.doc"; String filePathFinal = "HojaInventarioObjeto.doc"; POIFSFileSystem fs = null;//from w ww . j ava2 s. c om try { fs = new POIFSFileSystem(new FileInputStream(filePath)); HWPFDocument doc = new HWPFDocument(fs); doc = replaceText(doc, "$nombreObjeto", obj.getNombreObjeto()); doc = replaceText(doc, "$formaAdquisicion", obj.getFormaAdquisicion()); doc = replaceText(doc, "$fechaIngreso", obj.getFechaIngreso()); doc = replaceText(doc, "$numRegistro", obj.getNumRegistro()); doc = replaceText(doc, "$valorEconomico", obj.getValorEconomico()); doc = replaceText(doc, "$nombreFuente", obj.getNombreFuente()); doc = replaceText(doc, "$fechaInventario", obj.getFechaInventario()); doc = replaceText(doc, "$numCatalogo", obj.getNumCatalogo()); doc = replaceText(doc, "$numInventario", obj.getNumInventario()); doc = replaceText(doc, "$otrosNumeros", obj.getOtrosNumeros()); doc = replaceText(doc, "$direccionFuente", obj.getDireccionFuente()); doc = replaceText(doc, "$fechaCatalogo", obj.getFechaCatalogo()); doc = replaceText(doc, "$espesor", obj.getEspesor()); doc = replaceText(doc, "$alto", obj.getAlto()); doc = replaceText(doc, "$ancho", obj.getAncho()); doc = replaceText(doc, "$largo", obj.getLargo()); doc = replaceText(doc, "$diametro", obj.getDiametro()); doc = replaceText(doc, "$peso", obj.getPeso()); doc = replaceText(doc, "$procedencia", obj.getProcedencia()); doc = replaceText(doc, "$materiaYTecnica", obj.getMateriaYTecnica()); doc = replaceText(doc, "$numeroNegativo", obj.getNumeroNegativo()); doc = replaceText(doc, "$autor", obj.getAutor()); doc = replaceText(doc, "$epoca", obj.getEpoca()); doc = replaceText(doc, "$descripcion", obj.getDescripcion()); doc = replaceText(doc, "$documentacion", obj.getDocumentacion()); doc = replaceText(doc, "$observaciones", obj.getObservaciones()); doc = replaceText(doc, "$recibio", obj.getRecibio()); doc = replaceText(doc, "$inventario", obj.getInventario()); doc = replaceText(doc, "$catalogo", obj.getCatalogo()); doc = replaceText(doc, "$aprobo", obj.getAprobo()); saveWord(filePathFinal, doc); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:mongodbutils.Filehandler.java
public boolean processFile(String filePath, MongodbConnection mc, String strdbName, String strCollName) throws IOException { this.mc = mc; FileInputStream fileIn = null; try {// www . ja va 2 s . c o m fileIn = new FileInputStream(filePath); POIFSFileSystem fs = new POIFSFileSystem(fileIn); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); Object objReturn = null; //Read in first row as field names Row rowH = sheet.getRow(sheet.getFirstRowNum()); String fields[] = new String[sheet.getRow(0).getLastCellNum()]; for (Cell cell : rowH) { objReturn = null; objReturn = getCellValue(cell); fields[cell.getColumnIndex()] = objReturn.toString(); } //loop thru all cells with values int rowcount = 0; for (Row row : sheet) { if (row.getRowNum() == 0) { continue; //skip first row } JSONObject obj = new JSONObject(); for (Cell cell : row) { if (fields.length < cell.getColumnIndex()) { continue; //only export column if we have header set } objReturn = null; objReturn = getCellValue(cell); if (!objReturn.toString().equals("")) { if (objReturn instanceof Double) { obj.put(fields[cell.getColumnIndex()], objReturn); } else if (objReturn instanceof String) { if (objReturn.toString().contains("$date")) { JSONParser parser = new JSONParser(); try { obj.put(fields[cell.getColumnIndex()], parser.parse(objReturn.toString())); } catch (ParseException ex) { Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex); } } else { obj.put(fields[cell.getColumnIndex()], objReturn); } } } } rowcount += 1; mc.insertJSON(strdbName, strCollName, obj.toJSONString()); } return true; } catch (FileNotFoundException ex) { Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, e); } finally { if (fileIn != null) { fileIn.close(); } } return false; }
From source file:mx.dr.util.report.impl.PoiService.java
License:Open Source License
/** * @see mx.dr.util.report.IPoiService#doReport(InputStream, Object, OutputStream) *//*from ww w .java 2 s . com*/ public void doReport(InputStream is, Object dto, OutputStream out) throws Exception { POIFSFileSystem fs = null; HSSFWorkbook wb = null; fs = new POIFSFileSystem(is); wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); DRCoordinateReport anotCoordenada; DRCoordinateLabelReport anotEtiqueta; DRRelativeCoordinateReport anotRelativa; Object valor; Object valor2; HSSFRow row; HSSFCell cerda; int offset; CellDTO celdaDto; for (Method method : dto.getClass().getMethods()) { anotEtiqueta = method.getAnnotation(DRCoordinateLabelReport.class); if (anotEtiqueta != null) { dto.getClass().getMethod("set" + method.getName().substring(3), CellDTO.class).invoke(dto, new CellDTO(sheet.getRow(anotEtiqueta.y()).getCell(anotEtiqueta.x()).getCellStyle(), sheet.getRow(anotEtiqueta.y()).getCell(anotEtiqueta.x()).getRichStringCellValue())); } } for (Method method : dto.getClass().getMethods()) { anotCoordenada = method.getAnnotation(DRCoordinateReport.class); if (anotCoordenada != null) { valor = method.invoke(dto); if (valor != null) { cerda = sheet.getRow(anotCoordenada.y()).getCell(anotCoordenada.x()); ingresaValor(cerda, valor); if (valor instanceof List) { offset = anotCoordenada.y(); int index = 0; while (index < ((List) valor).size()) { Object detalle = ((List) valor).get(index); row = sheet.createRow(index + offset); for (Method methodMan : detalle.getClass().getMethods()) { anotCoordenada = methodMan.getAnnotation(DRCoordinateReport.class); if (anotCoordenada != null) { cerda = row.createCell(anotCoordenada.x()); valor2 = methodMan.invoke(detalle); if (valor2 != null) { ingresaValor(cerda, valor2); } } } index++; } index -= 1; for (Method m : dto.getClass().getMethods()) { anotEtiqueta = m.getAnnotation(DRCoordinateLabelReport.class); anotRelativa = m.getAnnotation(DRRelativeCoordinateReport.class); if (anotEtiqueta != null) { row = sheet.getRow(anotEtiqueta.y() + index); if (row == null) { row = sheet.createRow(anotEtiqueta.y() + index); } cerda = row.createCell(anotEtiqueta.x()); celdaDto = (CellDTO) m.invoke(dto); cerda.setCellStyle(celdaDto.getStyle()); cerda.setCellValue(celdaDto.getLabel()); } else if (anotRelativa != null) { row = sheet.getRow(anotRelativa.y() + index); if (row == null) { row = sheet.createRow(anotRelativa.y() + index); } cerda = row.createCell(anotRelativa.x()); valor2 = m.invoke(dto); if (valor2 != null) { ingresaValor(cerda, valor2); } } } } } } } //String res = "/mailConfig.properties"; //tempPath=PoiService.class.getResource(res).getPath().replaceFirst(res, "") // + "/../../" + Labels.getLabel("parametro.adjuntos.folder") + "/" + archivo; //FileUtils.writeToFile(archivo,new ByteArrayInputStream(doc.getDataContent())); //tempPath = this.getPath(TEMP_DIR)+"\\"+archivo; wb.write(out);//new FileOutputStream(tempPath ,false)); }
From source file:my_poi.MyXLS2CSVmra.java
License:Apache License
/** * Creates a new XLS -> CSV converter * //from w ww .j a v a 2 s . c om * @param filename * The file to process * @param minColumns * The minimum number of columns to output, or -1 for no minimum * @throws IOException * @throws FileNotFoundException */ public MyXLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException { this(new POIFSFileSystem(new FileInputStream(filename)), System.out, minColumns); }
From source file:net.freeutils.tnef.msg.Msg.java
License:Open Source License
public static void main(String[] args) throws Exception { String filename = args[0];//from w ww.j a va2 s .c o m String outputdir = args[1]; InputStream in = null; try { in = new FileInputStream(filename); POIFSFileSystem fs = new POIFSFileSystem(in); DirectoryEntry root = fs.getRoot(); //printDirectory(root, ""); Message message = processMessage(root); TNEF.extractContent(message, outputdir); } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (in != null) in.close(); } }
From source file:net.intelliant.util.UtilImport.java
License:Open Source License
public static List<String> readExcelFirstRow(String excelFilePath, boolean isFirstRowHeader, int sheetIndex) throws FileNotFoundException, IOException { List<String> columnIndices = new ArrayList<String>(); File file = new File(excelFilePath); if (file != null && file.canRead()) { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file)); HSSFWorkbook wb = new HSSFWorkbook(fs); // HSSFSheet sheet = wb.getSheet(wb.getActiveSheetIndex()); HSSFSheet sheet = wb.getSheetAt(sheetIndex); if (sheet != null) { HSSFRow firstRow = sheet.getRow(sheet.getFirstRowNum()); if (firstRow != null) { firstRow.getPhysicalNumberOfCells(); Iterator<?> cells = firstRow.cellIterator(); while (cells.hasNext()) { HSSFCell cell = (HSSFCell) cells.next(); if (isFirstRowHeader) { if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { columnIndices.add(cell.toString()); } else { columnIndices.add("N/A - " + cell.getCellNum()); }//from w w w . j a v a 2 s. c o m } else { columnIndices.add(String.valueOf(cell.getCellNum())); } } } } } return columnIndices; }
From source file:net.sf.jasperreports.engine.export.JRXlsExporter.java
License:Open Source License
protected void openWorkbook(OutputStream os) { XlsExporterConfiguration configuration = getCurrentConfiguration(); String lcWorkbookTemplate = workbookTemplate == null ? configuration.getWorkbookTemplate() : workbookTemplate;/*from w w w. j a va 2 s. c o m*/ if (lcWorkbookTemplate == null) { workbook = new HSSFWorkbook(); } else { InputStream templateIs = null; try { templateIs = RepositoryUtil.getInstance(jasperReportsContext) .getInputStreamFromLocation(lcWorkbookTemplate); if (templateIs == null) { throw new JRRuntimeException("Workbook template not found at : " + lcWorkbookTemplate); } else { workbook = new HSSFWorkbook(new POIFSFileSystem(templateIs)); boolean keepSheets = keepTemplateSheets == null ? configuration.isKeepWorkbookTemplateSheets() : keepTemplateSheets; if (keepSheets) { sheetIndex += workbook.getNumberOfSheets(); } else { for (int i = 0; i < workbook.getNumberOfSheets(); i++) { workbook.removeSheetAt(i); } } } } catch (JRException e) { throw new JRRuntimeException(e); } catch (IOException e) { throw new JRRuntimeException(e); } finally { if (templateIs != null) { try { templateIs.close(); } catch (IOException e) { } } } } emptyCellStyle = workbook.createCellStyle(); emptyCellStyle.setFillForegroundColor((new HSSFColor.WHITE()).getIndex()); emptyCellStyle.setFillPattern(backgroundMode); dataFormat = workbook.createDataFormat(); createHelper = workbook.getCreationHelper(); firstPageNotSet = true; palette = workbook.getCustomPalette(); customColorIndex = MIN_COLOR_INDEX; }