List of usage examples for org.apache.poi.poifs.filesystem POIFSFileSystem writeFilesystem
public void writeFilesystem(final OutputStream stream) throws IOException
From source file:com.orange.ocara.model.export.docx.AuditDocxExporter.java
License:Mozilla Public License
/** * Create OleObject using a sample.//from www . j av a2s . c o m * * @param from File to embed * @param to Destination file */ private void createOleObject(File from, File to) throws IOException, Ole10NativeException { File existingOleObject = new File(templateDirectory, "word/embeddings/oleObject.bin"); OutputStream os = null; try { // When POIFSFileSystem fs = new POIFSFileSystem(FileUtils.openInputStream(existingOleObject)); fs.getRoot().getEntry(Ole10Native.OLE10_NATIVE).delete(); Ole10Native ole = new Ole10Native(from.getName(), from.getName(), from.getName(), IOUtils.toByteArray(FileUtils.openInputStream(from))); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ole.writeOut(stream); fs.getRoot().createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(stream.toByteArray())); os = FileUtils.openOutputStream(to); fs.writeFilesystem(os); } finally { IOUtils.closeQuietly(os); } }
From source file:com.vodafone.poms.ii.helpers.ExportManager.java
private static String addFile(XSSFSheet sh, String filePath, double oleId) throws IOException, InvalidFormatException { File file = new File(filePath); FileInputStream fin = new FileInputStream(file); byte[] data;//from ww w . java 2s. co m data = new byte[fin.available()]; fin.read(data); Ole10Native ole10 = new Ole10Native(file.getAbsolutePath(), file.getAbsolutePath(), file.getAbsolutePath(), data); ByteArrayOutputStream bos = new ByteArrayOutputStream(500); ole10.writeOut(bos); POIFSFileSystem poifs = new POIFSFileSystem(); poifs.getRoot().createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray())); poifs.getRoot().setStorageClsid(ClassID.OLE10_PACKAGE); final PackagePartName pnOLE = PackagingURIHelper .createPartName("/xl/embeddings/oleObject" + oleId + Math.random() + ".bin"); final PackagePart partOLE = sh.getWorkbook().getPackage().createPart(pnOLE, "application/vnd.openxmlformats-officedocument.oleObject"); PackageRelationship prOLE = sh.getPackagePart().addRelationship(pnOLE, TargetMode.INTERNAL, POIXMLDocument.OLE_OBJECT_REL_TYPE); OutputStream os = partOLE.getOutputStream(); poifs.writeFilesystem(os); os.close(); poifs.close(); return prOLE.getId(); }
From source file:de.jlo.talendcomp.excel.SpreadsheetFile.java
License:Apache License
private static void encryptFile(String inFilePath, String outFilePath, String password) throws Exception { if (password == null || password.trim().isEmpty()) { throw new Exception("Password cannot be null or empty!"); }//from ww w . j av a 2s . c om if (inFilePath == null || inFilePath.trim().isEmpty()) { throw new Exception("Input file cannot be null or empty!"); } File inFile = new File(inFilePath); if (outFilePath == null || outFilePath.trim().isEmpty()) { throw new Exception("Output file cannot be null or empty!"); } File outFile = new File(outFilePath); if (inFile.exists() == false) { throw new Exception("Excel file to encrypt: " + inFile.getAbsolutePath() + " does not exists!"); } ensureDirExists(outFile); POIFSFileSystem fs = new POIFSFileSystem(); EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard); Encryptor enc = info.getEncryptor(); enc.confirmPassword(password); OPCPackage opc = OPCPackage.open(inFile, PackageAccess.READ_WRITE); OutputStream os = enc.getDataStream(fs); opc.save(os); opc.close(); FileOutputStream fos = null; Exception ex = null; try { fos = new FileOutputStream(outFile); fs.writeFilesystem(fos); } catch (Exception e) { ex = e; } finally { if (fos != null) { try { fos.close(); } catch (Exception e1) { // ignore } } } if (ex != null) { throw ex; } }
From source file:edu.ku.brc.specify.tasks.subpane.wb.XLSExport.java
License:Open Source License
public void writeData(final List<?> data) throws Exception { HSSFWorkbook workBook = new HSSFWorkbook(); HSSFSheet workSheet = workBook.createSheet(); DocumentSummaryInformation mappings = null; int rowNum = 0; if (config.getFirstRowHasHeaders() && !config.getAppendData()) { writeHeaders(workSheet);//from www . j av a2 s.c om rowNum++; String[] headers = config.getHeaders(); for (int i = 0; i < headers.length; i++) { workSheet.setColumnWidth(i, StringUtils.isNotEmpty(headers[i]) ? (256 * headers[i].length()) : 2560); } WorkbenchTemplate wbTemplate = null; if (data.get(0) instanceof WorkbenchTemplate) { wbTemplate = (WorkbenchTemplate) data.get(0); } else { wbTemplate = ((WorkbenchRow) data.get(0)).getWorkbench().getWorkbenchTemplate(); } mappings = writeMappings(wbTemplate); } //assuming data is never empty. boolean hasTemplate = data.get(0) instanceof WorkbenchTemplate; boolean hasRows = hasTemplate ? data.size() > 1 : data.size() > 0; if (hasRows) { int[] disciplinees; WorkbenchRow wbRow = (WorkbenchRow) data.get(hasTemplate ? 1 : 0); Workbench workBench = wbRow.getWorkbench(); WorkbenchTemplate template = workBench.getWorkbenchTemplate(); int numCols = template.getWorkbenchTemplateMappingItems().size(); int geoDataCol = -1; Vector<Integer> imgCols = new Vector<Integer>(); disciplinees = bldColTypes(template); for (Object rowObj : data) { if (rowObj instanceof WorkbenchTemplate) { continue; } WorkbenchRow row = (WorkbenchRow) rowObj; HSSFRow hssfRow = workSheet.createRow(rowNum++); int colNum; boolean rowHasGeoData = false; for (colNum = 0; colNum < numCols; colNum++) { HSSFCell cell = hssfRow.createCell(colNum); cell.setCellType(disciplinees[colNum]); setCellValue(cell, row.getData(colNum)); } if (row.getBioGeomancerResults() != null && !row.getBioGeomancerResults().equals("")) { geoDataCol = colNum; rowHasGeoData = true; HSSFCell cell = hssfRow.createCell(colNum++); cell.setCellType(HSSFCell.CELL_TYPE_STRING); setCellValue(cell, row.getBioGeomancerResults()); } // if (row.getCardImage() != null) if (row.getRowImage(0) != null) { if (!rowHasGeoData) { colNum++; } int imgIdx = 0; WorkbenchRowImage img = row.getRowImage(imgIdx++); while (img != null) { if (imgCols.indexOf(colNum) < 0) { imgCols.add(colNum); } HSSFCell cell = hssfRow.createCell(colNum++); cell.setCellType(HSSFCell.CELL_TYPE_STRING); String cellValue = img.getCardImageFullPath(); String attachToTbl = img.getAttachToTableName(); if (attachToTbl != null) { cellValue += "\t" + attachToTbl; } setCellValue(cell, cellValue); img = row.getRowImage(imgIdx++); } } } if (imgCols.size() > 0 || geoDataCol != -1) { writeExtraHeaders(workSheet, imgCols, geoDataCol); } } try { // Write the workbook File file = new File(getConfig().getFileName()); if (file.canWrite() || (!file.exists() && file.createNewFile())) { FileOutputStream fos = new FileOutputStream(file); workBook.write(fos); fos.close(); //Now write the mappings. //NOT (hopefully) the best way to write the mappings, but (sadly) the easiest way. //May need to do this another way if this slows performance for big wbs. if (mappings != null) { InputStream is = new FileInputStream(file); POIFSFileSystem poifs = new POIFSFileSystem(is); is.close(); mappings.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); fos = new FileOutputStream(file); poifs.writeFilesystem(fos); fos.close(); } } else { UIRegistry.displayErrorDlgLocalized("WB_EXPORT_PERM_ERR"); } } catch (Exception e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(XLSExport.class, e); throw (e); } }
From source file:net.sf.mpxj.utility.MppClean.java
License:Open Source License
/** * Process an MPP file to make it anonymous. * /*w w w.j a v a2 s . c o m*/ * @param input input file name * @param output output file name * @throws Exception */ private void process(String input, String output) throws MPXJException, IOException { // // Extract the project data // MPPReader reader = new MPPReader(); m_project = reader.read(input); String varDataFileName; String projectDirName; switch (m_project.getMppFileType()) { case 8: { projectDirName = " 1"; varDataFileName = "FixDeferFix 0"; break; } case 9: { projectDirName = " 19"; varDataFileName = "Var2Data"; break; } case 12: { projectDirName = " 112"; varDataFileName = "Var2Data"; break; } default: { throw new IllegalArgumentException("Unsupported file type " + m_project.getMppFileType()); } } // // Load the raw file // FileInputStream is = new FileInputStream(input); POIFSFileSystem fs = new POIFSFileSystem(is); is.close(); // // Locate the root of the project file system // DirectoryEntry root = fs.getRoot(); m_projectDir = (DirectoryEntry) root.getEntry(projectDirName); // // Process Tasks // Map<String, String> replacements = new HashMap<String, String>(); for (Task task : m_project.getAllTasks()) { mapText(task.getName(), replacements); } processReplacements(((DirectoryEntry) m_projectDir.getEntry("TBkndTask")), varDataFileName, replacements, true); // // Process Resources // replacements.clear(); for (Resource resource : m_project.getAllResources()) { mapText(resource.getName(), replacements); mapText(resource.getInitials(), replacements); } processReplacements((DirectoryEntry) m_projectDir.getEntry("TBkndRsc"), varDataFileName, replacements, true); // // Process project header details // replacements.clear(); ProjectHeader header = m_project.getProjectHeader(); mapText(header.getProjectTitle(), replacements); processReplacements(m_projectDir, "Props", replacements, true); replacements.clear(); mapText(header.getProjectTitle(), replacements); mapText(header.getSubject(), replacements); mapText(header.getAuthor(), replacements); mapText(header.getKeywords(), replacements); mapText(header.getComments(), replacements); processReplacements(root, "\005SummaryInformation", replacements, false); replacements.clear(); mapText(header.getManager(), replacements); mapText(header.getCompany(), replacements); mapText(header.getCategory(), replacements); processReplacements(root, "\005DocumentSummaryInformation", replacements, false); // // Write the replacement raw file // FileOutputStream os = new FileOutputStream(output); fs.writeFilesystem(os); os.flush(); os.close(); }
From source file:net.sf.mpxj.utility.MppCleanUtility.java
License:Open Source License
/** * Process an MPP file to make it anonymous. * /*from ww w .j a v a2 s . co m*/ * @param input input file name * @param output output file name * @throws Exception */ private void process(String input, String output) throws MPXJException, IOException { // // Extract the project data // MPPReader reader = new MPPReader(); m_project = reader.read(input); String varDataFileName; String projectDirName; int mppFileType = NumberHelper.getInt(m_project.getProjectProperties().getMppFileType()); switch (mppFileType) { case 8: { projectDirName = " 1"; varDataFileName = "FixDeferFix 0"; break; } case 9: { projectDirName = " 19"; varDataFileName = "Var2Data"; break; } case 12: { projectDirName = " 112"; varDataFileName = "Var2Data"; break; } default: { throw new IllegalArgumentException("Unsupported file type " + mppFileType); } } // // Load the raw file // FileInputStream is = new FileInputStream(input); POIFSFileSystem fs = new POIFSFileSystem(is); is.close(); // // Locate the root of the project file system // DirectoryEntry root = fs.getRoot(); m_projectDir = (DirectoryEntry) root.getEntry(projectDirName); // // Process Tasks // Map<String, String> replacements = new HashMap<String, String>(); for (Task task : m_project.getAllTasks()) { mapText(task.getName(), replacements); } processReplacements(((DirectoryEntry) m_projectDir.getEntry("TBkndTask")), varDataFileName, replacements, true); // // Process Resources // replacements.clear(); for (Resource resource : m_project.getAllResources()) { mapText(resource.getName(), replacements); mapText(resource.getInitials(), replacements); } processReplacements((DirectoryEntry) m_projectDir.getEntry("TBkndRsc"), varDataFileName, replacements, true); // // Process project properties // replacements.clear(); ProjectProperties properties = m_project.getProjectProperties(); mapText(properties.getProjectTitle(), replacements); processReplacements(m_projectDir, "Props", replacements, true); replacements.clear(); mapText(properties.getProjectTitle(), replacements); mapText(properties.getSubject(), replacements); mapText(properties.getAuthor(), replacements); mapText(properties.getKeywords(), replacements); mapText(properties.getComments(), replacements); processReplacements(root, "\005SummaryInformation", replacements, false); replacements.clear(); mapText(properties.getManager(), replacements); mapText(properties.getCompany(), replacements); mapText(properties.getCategory(), replacements); processReplacements(root, "\005DocumentSummaryInformation", replacements, false); // // Write the replacement raw file // FileOutputStream os = new FileOutputStream(output); fs.writeFilesystem(os); os.flush(); os.close(); }
From source file:org.elasticwarehouse.core.parsers.FileEmbeddedDocumentExtractor.java
License:Apache License
public void parseEmbedded(InputStream inputStream, ContentHandler contentHandler, Metadata metadata, boolean outputHtml) throws SAXException, IOException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name == null) { name = "file" + count++; }// w w w .j a v a2 s . co m DefaultDetector detector = new DefaultDetector(); MediaType contentType = detector.detect(inputStream, metadata); if (name.indexOf('.') == -1 && contentType != null) { try { name += config.getMimeRepository().forName(contentType.toString()).getExtension(); } catch (MimeTypeException e) { EWLogger.logerror(e); e.printStackTrace(); } } String relID = metadata.get(Metadata.EMBEDDED_RELATIONSHIP_ID); if (relID != null && !name.startsWith(relID)) { name = relID + "_" + name; } File outputFile = new File(extractDir, FilenameUtils.normalize(name)); File parent = outputFile.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IOException("unable to create directory \"" + parent + "\""); } } System.out.println("Extracting '" + name + "' (" + contentType + ") to " + outputFile); FileOutputStream os = null; try { os = new FileOutputStream(outputFile); if (inputStream instanceof TikaInputStream) { TikaInputStream tin = (TikaInputStream) inputStream; if (tin.getOpenContainer() != null && tin.getOpenContainer() instanceof DirectoryEntry) { POIFSFileSystem fs = new POIFSFileSystem(); copy((DirectoryEntry) tin.getOpenContainer(), fs.getRoot()); fs.writeFilesystem(os); } else { IOUtils.copy(inputStream, os); } } else { IOUtils.copy(inputStream, os); } } catch (Exception e) { // // being a CLI program messages should go to the stderr too // String msg = String.format(Locale.ROOT, "Ignoring unexpected exception trying to save embedded file %s (%s)", name, e.getMessage()); EWLogger.logerror(e); System.err.println(msg); //logger.warn(msg, e); } finally { if (os != null) { os.close(); } } }
From source file:poi.hpsf.examples.ModifyDocumentSummaryInformation.java
License:Apache License
/** * <p>Main method - see class description.</p> * * @param args The command-line parameters. * @throws java.io.IOException// w w w .ja v a 2 s . c om * @throws MarkUnsupportedException * @throws NoPropertySetStreamException * @throws UnexpectedPropertySetTypeException * @throws WritingNotSupportedException */ public static void main(final String[] args) throws IOException, NoPropertySetStreamException, MarkUnsupportedException, UnexpectedPropertySetTypeException, WritingNotSupportedException { /* Read the name of the POI filesystem to modify from the command line. * For brevity to boundary check is performed on the command-line * arguments. */ File poiFilesystem = new File(args[0]); /* Open the POI filesystem. */ InputStream is = new FileInputStream(poiFilesystem); POIFSFileSystem poifs = new POIFSFileSystem(is); is.close(); /* Read the summary information. */ DirectoryEntry dir = poifs.getRoot(); SummaryInformation si; try { DocumentEntry siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); DocumentInputStream dis = new DocumentInputStream(siEntry); PropertySet ps = new PropertySet(dis); dis.close(); si = new SummaryInformation(ps); } catch (FileNotFoundException ex) { /* There is no summary information yet. We have to create a new * one. */ si = PropertySetFactory.newSummaryInformation(); } /* Change the author to "Rainer Klute". Any former author value will * be lost. If there has been no author yet, it will be created. */ si.setAuthor("Rainer Klute"); System.out.println("Author changed to " + si.getAuthor() + "."); /* Handling the document summary information is analogous to handling * the summary information. An additional feature, however, are the * custom properties. */ /* Read the document summary information. */ DocumentSummaryInformation dsi; try { DocumentEntry dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); DocumentInputStream dis = new DocumentInputStream(dsiEntry); PropertySet ps = new PropertySet(dis); dis.close(); dsi = new DocumentSummaryInformation(ps); } catch (FileNotFoundException ex) { /* There is no document summary information yet. We have to create a * new one. */ dsi = PropertySetFactory.newDocumentSummaryInformation(); } /* Change the category to "POI example". Any former category value will * be lost. If there has been no category yet, it will be created. */ dsi.setCategory("POI example"); System.out.println("Category changed to " + dsi.getCategory() + "."); /* Read the custom properties. If there are no custom properties yet, * the application has to create a new CustomProperties object. It will * serve as a container for custom properties. */ CustomProperties customProperties = dsi.getCustomProperties(); if (customProperties == null) customProperties = new CustomProperties(); /* Insert some custom properties into the container. */ customProperties.put("Key 1", "Value 1"); customProperties.put("Schl\u00fcssel 2", "Wert 2"); customProperties.put("Sample Number", new Integer(12345)); customProperties.put("Sample Boolean", Boolean.TRUE); customProperties.put("Sample Date", new Date()); /* Read a custom property. */ Object value = customProperties.get("Sample Number"); /* Write the custom properties back to the document summary * information. */ dsi.setCustomProperties(customProperties); /* Write the summary information and the document summary information * to the POI filesystem. */ si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME); dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); /* Write the POI filesystem back to the original file. Please note that * in production code you should never write directly to the origin * file! In case of a writing error everything would be lost. */ OutputStream out = new FileOutputStream(poiFilesystem); poifs.writeFilesystem(out); out.close(); }
From source file:poi.hpsf.examples.WriteTitle.java
License:Apache License
/** * <p>Runs the example program.</p> * * @param args Command-line arguments. The first and only command-line * argument is the name of the POI file system to create. * @throws java.io.IOException if any I/O exception occurs. * @throws WritingNotSupportedException if HPSF does not (yet) support * writing a certain property type.// ww w.j ava 2s. c om */ public static void main(final String[] args) throws WritingNotSupportedException, IOException { /* Check whether we have exactly one command-line argument. */ if (args.length != 1) { System.err.println("Usage: " + WriteTitle.class.getName() + "destinationPOIFS"); System.exit(1); } final String fileName = args[0]; /* Create a mutable property set. Initially it contains a single section * with no properties. */ final MutablePropertySet mps = new MutablePropertySet(); /* Retrieve the section the property set already contains. */ final MutableSection ms = (MutableSection) mps.getSections().get(0); /* Turn the property set into a summary information property. This is * done by setting the format ID of its first section to * SectionIDMap.SUMMARY_INFORMATION_ID. */ ms.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID); /* Create an empty property. */ final MutableProperty p = new MutableProperty(); /* Fill the property with appropriate settings so that it specifies the * document's title. */ p.setID(PropertyIDMap.PID_TITLE); p.setType(Variant.VT_LPWSTR); p.setValue("Sample title"); /* Place the property into the section. */ ms.setProperty(p); /* Create the POI file system the property set is to be written to. */ final POIFSFileSystem poiFs = new POIFSFileSystem(); /* For writing the property set into a POI file system it has to be * handed over to the POIFS.createDocument() method as an input stream * which produces the bytes making out the property set stream. */ final InputStream is = mps.toInputStream(); /* Create the summary information property set in the POI file * system. It is given the default name most (if not all) summary * information property sets have. */ poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME); /* Write the whole POI file system to a disk file. */ poiFs.writeFilesystem(new FileOutputStream(fileName)); }
From source file:ro.nextreports.engine.exporter.XlsExporter.java
License:Apache License
public static void createSummaryInformation(String filePath, String title) { if (filePath == null) { return;//from w w w.j a v a 2 s . c o m } try { File poiFilesystem = new File(filePath); InputStream is = new FileInputStream(poiFilesystem); POIFSFileSystem poifs = new POIFSFileSystem(is); is.close(); DirectoryEntry dir = poifs.getRoot(); SummaryInformation si = PropertySetFactory.newSummaryInformation(); si.setTitle(title); si.setAuthor(ReleaseInfoAdapter.getCompany()); si.setApplicationName("NextReports " + ReleaseInfoAdapter.getVersionNumber()); si.setSubject("Created by NextReports Designer" + ReleaseInfoAdapter.getVersionNumber()); si.setCreateDateTime(new Date()); si.setKeywords(ReleaseInfoAdapter.getHome()); si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME); OutputStream out = new FileOutputStream(poiFilesystem); poifs.writeFilesystem(out); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }