From: Cédric Walter Date: Wed, 2 Apr 2014 11:23:16 +0000 (+0000) Subject: moved poi example code to module poi-examples X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=5a1255db3543afbd301cf191be5246bf169f54b3;p=poi.git moved poi example code to module poi-examples git-svn-id: https://svn.apache.org/repos/asf/poi/branches/maven@1583970 13f79535-47bb-0310-9956-ffa450edef68 --- diff --git a/poi-examples/pom.xml b/poi-examples/pom.xml index 17eb53d937..25b7c0491b 100644 --- a/poi-examples/pom.xml +++ b/poi-examples/pom.xml @@ -36,48 +36,6 @@ http://poi.apache.org/ Apache POI Examples - - - - - - maven-resources-plugin - 2.6 - - - copy-sources - - generate-sources - - copy-resources - - - ${basedir}/src/main/java - - - ../../src/examples/src - - - - - - - - - maven-clean-plugin - 2.5 - - - - src - false - - - - - - - ${project.groupId} diff --git a/poi-examples/src/main/java/poi/hpsf/examples/CopyCompare.java b/poi-examples/src/main/java/poi/hpsf/examples/CopyCompare.java new file mode 100644 index 0000000000..1fb9d48ef2 --- /dev/null +++ b/poi-examples/src/main/java/poi/hpsf/examples/CopyCompare.java @@ -0,0 +1,542 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hpsf.examples; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.poi.hpsf.HPSFRuntimeException; +import org.apache.poi.hpsf.MarkUnsupportedException; +import org.apache.poi.hpsf.MutablePropertySet; +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.PropertySet; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.Util; +import org.apache.poi.hpsf.WritingNotSupportedException; +import org.apache.poi.poifs.eventfilesystem.POIFSReader; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; +import org.apache.poi.poifs.filesystem.DirectoryEntry; +import org.apache.poi.poifs.filesystem.DocumentEntry; +import org.apache.poi.poifs.filesystem.DocumentInputStream; +import org.apache.poi.poifs.filesystem.Entry; +import org.apache.poi.poifs.filesystem.POIFSDocumentPath; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.util.TempFile; + +/** + *

This class copies a POI file system to a new file and compares the copy + * with the original.

+ * + *

Property set streams are copied logically, i.e. the application + * establishes a {@link org.apache.poi.hpsf.PropertySet} of an original property + * set, creates a {@link org.apache.poi.hpsf.MutablePropertySet} from the + * {@link org.apache.poi.hpsf.PropertySet} and writes the + * {@link org.apache.poi.hpsf.MutablePropertySet} to the destination POI file + * system. - Streams which are no property set streams are copied bit by + * bit.

+ * + *

The comparison of the POI file systems is done logically. That means that + * the two disk files containing the POI file systems do not need to be + * exactly identical. However, both POI file systems must contain the same + * files, and most of these files must be bitwise identical. Property set + * streams, however, are compared logically: they must have the same sections + * with the same attributs, and the sections must contain the same properties. + * Details like the ordering of the properties do not matter.

+ * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class CopyCompare +{ + /** + *

Runs the example program. The application expects one or two + * arguments:

+ * + *
    + * + *
  1. The first argument is the disk file name of the POI filesystem to + * copy.

  2. + * + *
  3. The second argument is optional. If it is given, it is the name of + * a disk file the copy of the POI filesystem will be written to. If it is + * not given, the copy will be written to a temporary file which will be + * deleted at the end of the program.

  4. + * + *
+ * + * @param args Command-line arguments. + * @exception MarkUnsupportedException if a POI document stream does not + * support the mark() operation. + * @exception NoPropertySetStreamException if the application tries to + * create a property set from a POI document stream that is not a property + * set stream. + * @exception IOException if any I/O exception occurs. + * @exception UnsupportedEncodingException if a character encoding is not + * supported. + */ + public static void main(final String[] args) + throws NoPropertySetStreamException, MarkUnsupportedException, + UnsupportedEncodingException, IOException + { + String originalFileName = null; + String copyFileName = null; + + /* Check the command-line arguments. */ + if (args.length == 1) + { + originalFileName = args[0]; + File f = TempFile.createTempFile("CopyOfPOIFileSystem-", ".ole2"); + f.deleteOnExit(); + copyFileName = f.getAbsolutePath(); + } + else if (args.length == 2) + { + originalFileName = args[0]; + copyFileName = args[1]; + } + else + { + System.err.println("Usage: " + CopyCompare.class.getName() + + "originPOIFS [copyPOIFS]"); + System.exit(1); + } + + /* Read the origin POIFS using the eventing API. The real work is done + * in the class CopyFile which is registered here as a POIFSReader. */ + final POIFSReader r = new POIFSReader(); + final CopyFile cf = new CopyFile(copyFileName); + r.registerListener(cf); + r.read(new FileInputStream(originalFileName)); + + /* Write the new POIFS to disk. */ + cf.close(); + + /* Read all documents from the original POI file system and compare them + * with the equivalent document from the copy. */ + final POIFSFileSystem opfs = + new POIFSFileSystem(new FileInputStream(originalFileName)); + final POIFSFileSystem cpfs = + new POIFSFileSystem(new FileInputStream(copyFileName)); + + final DirectoryEntry oRoot = opfs.getRoot(); + final DirectoryEntry cRoot = cpfs.getRoot(); + final StringBuffer messages = new StringBuffer(); + if (equal(oRoot, cRoot, messages)) + System.out.println("Equal"); + else + System.out.println("Not equal: " + messages.toString()); + } + + + + /** + *

Compares two {@link DirectoryEntry} instances of a POI file system. + * The directories must contain the same streams with the same names and + * contents.

+ * + * @param d1 The first directory. + * @param d2 The second directory. + * @param msg The method may append human-readable comparison messages to + * this string buffer. + * @return true if the directories are equal, else + * false. + * @exception MarkUnsupportedException if a POI document stream does not + * support the mark() operation. + * @exception NoPropertySetStreamException if the application tries to + * create a property set from a POI document stream that is not a property + * set stream. + * @throws UnsupportedEncodingException + * @exception IOException if any I/O exception occurs. + */ + private static boolean equal(final DirectoryEntry d1, + final DirectoryEntry d2, + final StringBuffer msg) + throws NoPropertySetStreamException, MarkUnsupportedException, + UnsupportedEncodingException, IOException + { + boolean equal = true; + /* Iterate over d1 and compare each entry with its counterpart in d2. */ + for (final Iterator i = d1.getEntries(); equal && i.hasNext();) + { + final Entry e1 = (Entry) i.next(); + final String n1 = e1.getName(); + Entry e2 = null; + try + { + e2 = d2.getEntry(n1); + } + catch (FileNotFoundException ex) + { + msg.append("Document \"" + e1 + "\" exists, document \"" + + e2 + "\" does not.\n"); + equal = false; + break; + } + + if (e1.isDirectoryEntry() && e2.isDirectoryEntry()) + equal = equal((DirectoryEntry) e1, (DirectoryEntry) e2, msg); + else if (e1.isDocumentEntry() && e2.isDocumentEntry()) + equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg); + else + { + msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " + + "document while the other one is a directory.\n"); + equal = false; + } + } + + /* Iterate over d2 just to make sure that there are no entries in d2 + * that are not in d1. */ + for (final Iterator i = d2.getEntries(); equal && i.hasNext();) + { + final Entry e2 = (Entry) i.next(); + final String n2 = e2.getName(); + Entry e1 = null; + try + { + e1 = d1.getEntry(n2); + } + catch (FileNotFoundException ex) + { + msg.append("Document \"" + e2 + "\" exitsts, document \"" + + e1 + "\" does not.\n"); + equal = false; + break; + } + } + return equal; + } + + + + /** + *

Compares two {@link DocumentEntry} instances of a POI file system. + * Documents that are not property set streams must be bitwise identical. + * Property set streams must be logically equal.

+ * + * @param d1 The first document. + * @param d2 The second document. + * @param msg The method may append human-readable comparison messages to + * this string buffer. + * @return true if the documents are equal, else + * false. + * @exception MarkUnsupportedException if a POI document stream does not + * support the mark() operation. + * @exception NoPropertySetStreamException if the application tries to + * create a property set from a POI document stream that is not a property + * set stream. + * @throws UnsupportedEncodingException + * @exception IOException if any I/O exception occurs. + */ + private static boolean equal(final DocumentEntry d1, final DocumentEntry d2, + final StringBuffer msg) + throws NoPropertySetStreamException, MarkUnsupportedException, + UnsupportedEncodingException, IOException + { + boolean equal = true; + final DocumentInputStream dis1 = new DocumentInputStream(d1); + final DocumentInputStream dis2 = new DocumentInputStream(d2); + if (PropertySet.isPropertySetStream(dis1) && + PropertySet.isPropertySetStream(dis2)) + { + final PropertySet ps1 = PropertySetFactory.create(dis1); + final PropertySet ps2 = PropertySetFactory.create(dis2); + equal = ps1.equals(ps2); + if (!equal) + { + msg.append("Property sets are not equal.\n"); + return equal; + } + } + else + { + int i1; + int i2; + do + { + i1 = dis1.read(); + i2 = dis2.read(); + if (i1 != i2) + { + equal = false; + msg.append("Documents are not equal.\n"); + break; + } + } + while (equal && i1 == -1); + } + return true; + } + + + + /** + *

This class does all the work. Its method {@link + * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each file in + * the original POI file system. Except for property set streams it copies + * everything unmodified to the destination POI filesystem. Property set + * streams are copied by creating a new {@link PropertySet} from the + * original property set by using the {@link + * MutablePropertySet#MutablePropertySet(PropertySet)} constructor.

+ */ + static class CopyFile implements POIFSReaderListener + { + String dstName; + OutputStream out; + POIFSFileSystem poiFs; + + + /** + *

The constructor of a {@link CopyFile} instance creates the target + * POIFS. It also stores the name of the file the POIFS will be written + * to once it is complete.

+ * + * @param dstName The name of the disk file the destination POIFS is to + * be written to. + */ + public CopyFile(final String dstName) + { + this.dstName = dstName; + poiFs = new POIFSFileSystem(); + } + + + /** + *

The method is called by POI's eventing API for each file in the + * origin POIFS.

+ */ + public void processPOIFSReaderEvent(final POIFSReaderEvent event) + { + /* The following declarations are shortcuts for accessing the + * "event" object. */ + final POIFSDocumentPath path = event.getPath(); + final String name = event.getName(); + final DocumentInputStream stream = event.getStream(); + + Throwable t = null; + + try + { + /* Find out whether the current document is a property set + * stream or not. */ + if (PropertySet.isPropertySetStream(stream)) + { + /* Yes, the current document is a property set stream. + * Let's create a PropertySet instance from it. */ + PropertySet ps = null; + try + { + ps = PropertySetFactory.create(stream); + } + catch (NoPropertySetStreamException ex) + { + /* This exception will not be thrown because we already + * checked above. */ + } + + /* Copy the property set to the destination POI file + * system. */ + copy(poiFs, path, name, ps); + } + else + /* No, the current document is not a property set stream. We + * copy it unmodified to the destination POIFS. */ + copy(poiFs, event.getPath(), event.getName(), stream); + } + catch (MarkUnsupportedException ex) + { + t = ex; + } + catch (IOException ex) + { + t = ex; + } + catch (WritingNotSupportedException ex) + { + t = ex; + } + + /* According to the definition of the processPOIFSReaderEvent method + * we cannot pass checked exceptions to the caller. The following + * lines check whether a checked exception occured and throws an + * unchecked exception. The message of that exception is that of + * the underlying checked exception. */ + if (t != null) + { + throw new HPSFRuntimeException + ("Could not read file \"" + path + "/" + name + + "\". Reason: " + Util.toString(t)); + } + } + + + + /** + *

Writes a {@link PropertySet} to a POI filesystem.

+ * + * @param poiFs The POI filesystem to write to. + * @param path The file's path in the POI filesystem. + * @param name The file's name in the POI filesystem. + * @param ps The property set to write. + * @throws WritingNotSupportedException + * @throws IOException + */ + public void copy(final POIFSFileSystem poiFs, + final POIFSDocumentPath path, + final String name, + final PropertySet ps) + throws WritingNotSupportedException, IOException + { + final DirectoryEntry de = getPath(poiFs, path); + final MutablePropertySet mps = new MutablePropertySet(ps); + de.createDocument(name, mps.toInputStream()); + } + + + + /** + *

Copies the bytes from a {@link DocumentInputStream} to a new + * stream in a POI filesystem.

+ * + * @param poiFs The POI filesystem to write to. + * @param path The source document's path. + * @param name The source document's name. + * @param stream The stream containing the source document. + * @throws IOException + */ + public void copy(final POIFSFileSystem poiFs, + final POIFSDocumentPath path, + final String name, + final DocumentInputStream stream) throws IOException + { + final DirectoryEntry de = getPath(poiFs, path); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + int c; + while ((c = stream.read()) != -1) + out.write(c); + stream.close(); + out.close(); + final InputStream in = + new ByteArrayInputStream(out.toByteArray()); + de.createDocument(name, in); + } + + + /** + *

Writes the POI file system to a disk file.

+ * + * @throws FileNotFoundException + * @throws IOException + */ + public void close() throws FileNotFoundException, IOException + { + out = new FileOutputStream(dstName); + poiFs.writeFilesystem(out); + out.close(); + } + + + + /** Contains the directory paths that have already been created in the + * output POI filesystem and maps them to their corresponding + * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ + private final Map paths = new HashMap(); + + + + /** + *

Ensures that the directory hierarchy for a document in a POI + * fileystem is in place. When a document is to be created somewhere in + * a POI filesystem its directory must be created first. This method + * creates all directories between the POI filesystem root and the + * directory the document should belong to which do not yet exist.

+ * + *

Unfortunately POI does not offer a simple method to interrogate + * the POIFS whether a certain child node (file or directory) exists in + * a directory. However, since we always start with an empty POIFS which + * contains the root directory only and since each directory in the + * POIFS is created by this method we can maintain the POIFS's directory + * hierarchy ourselves: The {@link DirectoryEntry} of each directory + * created is stored in a {@link Map}. The directories' path names map + * to the corresponding {@link DirectoryEntry} instances.

+ * + * @param poiFs The POI filesystem the directory hierarchy is created + * in, if needed. + * @param path The document's path. This method creates those directory + * components of this hierarchy which do not yet exist. + * @return The directory entry of the document path's parent. The caller + * should use this {@link DirectoryEntry} to create documents in it. + */ + public DirectoryEntry getPath(final POIFSFileSystem poiFs, + final POIFSDocumentPath path) + { + try + { + /* Check whether this directory has already been created. */ + final String s = path.toString(); + DirectoryEntry de = (DirectoryEntry) paths.get(s); + if (de != null) + /* Yes: return the corresponding DirectoryEntry. */ + return de; + + /* No: We have to create the directory - or return the root's + * DirectoryEntry. */ + int l = path.length(); + if (l == 0) + /* Get the root directory. It does not have to be created + * since it always exists in a POIFS. */ + de = poiFs.getRoot(); + else + { + /* Create a subordinate directory. The first step is to + * ensure that the parent directory exists: */ + de = getPath(poiFs, path.getParent()); + /* Now create the target directory: */ + de = de.createDirectory(path.getComponent + (path.length() - 1)); + } + paths.put(s, de); + return de; + } + catch (IOException ex) + { + /* This exception will be thrown if the directory already + * exists. However, since we have full control about directory + * creation we can ensure that this will never happen. */ + ex.printStackTrace(System.err); + throw new RuntimeException(ex.toString()); + /* FIXME (2): Replace the previous line by the following once we + * no longer need JDK 1.3 compatibility. */ + // throw new RuntimeException(ex); + } + } + } + +} diff --git a/poi-examples/src/main/java/poi/hpsf/examples/ModifyDocumentSummaryInformation.java b/poi-examples/src/main/java/poi/hpsf/examples/ModifyDocumentSummaryInformation.java new file mode 100644 index 0000000000..66c1cbdb0e --- /dev/null +++ b/poi-examples/src/main/java/poi/hpsf/examples/ModifyDocumentSummaryInformation.java @@ -0,0 +1,194 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hpsf.examples; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Date; + +import org.apache.poi.hpsf.CustomProperties; +import org.apache.poi.hpsf.DocumentSummaryInformation; +import org.apache.poi.hpsf.MarkUnsupportedException; +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.PropertySet; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.SummaryInformation; +import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; +import org.apache.poi.hpsf.WritingNotSupportedException; +import org.apache.poi.poifs.filesystem.DirectoryEntry; +import org.apache.poi.poifs.filesystem.DocumentEntry; +import org.apache.poi.poifs.filesystem.DocumentInputStream; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + +/** + *

This is a sample application showing how to easily modify properties in + * the summary information and in the document summary information. The + * application reads the name of a POI filesystem from the command line and + * performs the following actions:

+ * + *
    + * + *
  • Open the POI filesystem.

  • + * + *
  • Read the summary information.

  • + * + *
  • Read and print the "author" property.

  • + * + *
  • Change the author to "Rainer Klute".

  • + * + *
  • Read the document summary information.

  • + * + *
  • Read and print the "category" property.

  • + * + *
  • Change the category to "POI example".

  • + * + *
  • Read the custom properties (if available).

  • + * + *
  • Insert a new custom property.

  • + * + *
  • Write the custom properties back to the document summary + * information.

  • + * + *
  • Write the summary information to the POI filesystem.

  • + * + *
  • Write the document summary information to the POI filesystem.

  • + * + *
  • Write the POI filesystem back to the original file.

  • + * + * + * + * @author Rainer Klute klute@rainer-klute.de + */ +public class ModifyDocumentSummaryInformation { + + /** + *

    Main method - see class description.

    + * + * @param args The command-line parameters. + * @throws IOException + * @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(); + } +} diff --git a/poi-examples/src/main/java/poi/hpsf/examples/ReadCustomPropertySets.java b/poi-examples/src/main/java/poi/hpsf/examples/ReadCustomPropertySets.java new file mode 100644 index 0000000000..bf6bcd1f8f --- /dev/null +++ b/poi-examples/src/main/java/poi/hpsf/examples/ReadCustomPropertySets.java @@ -0,0 +1,137 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hpsf.examples; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.Property; +import org.apache.poi.hpsf.PropertySet; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.Section; +import org.apache.poi.poifs.eventfilesystem.POIFSReader; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; +import org.apache.poi.util.HexDump; + +/** + *

    Sample application showing how to read a document's custom property set. + * Call it with the document's file name as command-line parameter.

    + * + *

    Explanations can be found in the HPSF HOW-TO.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class ReadCustomPropertySets +{ + + /** + *

    Runs the example program.

    + * + * @param args Command-line arguments (unused). + * @throws IOException if any I/O exception occurs. + */ + public static void main(final String[] args) + throws IOException + { + final String filename = args[0]; + POIFSReader r = new POIFSReader(); + + /* Register a listener for *all* documents. */ + r.registerListener(new MyPOIFSReaderListener()); + r.read(new FileInputStream(filename)); + } + + + static class MyPOIFSReaderListener implements POIFSReaderListener + { + public void processPOIFSReaderEvent(final POIFSReaderEvent event) + { + PropertySet ps = null; + try + { + ps = PropertySetFactory.create(event.getStream()); + } + catch (NoPropertySetStreamException ex) + { + out("No property set stream: \"" + event.getPath() + + event.getName() + "\""); + return; + } + catch (Exception ex) + { + throw new RuntimeException + ("Property set stream \"" + + event.getPath() + event.getName() + "\": " + ex); + } + + /* Print the name of the property set stream: */ + out("Property set stream \"" + event.getPath() + + event.getName() + "\":"); + + /* Print the number of sections: */ + final long sectionCount = ps.getSectionCount(); + out(" No. of sections: " + sectionCount); + + /* Print the list of sections: */ + List sections = ps.getSections(); + int nr = 0; + for (Iterator i = sections.iterator(); i.hasNext();) + { + /* Print a single section: */ + Section sec = (Section) i.next(); + out(" Section " + nr++ + ":"); + String s = hex(sec.getFormatID().getBytes()); + s = s.substring(0, s.length() - 1); + out(" Format ID: " + s); + + /* Print the number of properties in this section. */ + int propertyCount = sec.getPropertyCount(); + out(" No. of properties: " + propertyCount); + + /* Print the properties: */ + Property[] properties = sec.getProperties(); + for (int i2 = 0; i2 < properties.length; i2++) + { + /* Print a single property: */ + Property p = properties[i2]; + long id = p.getID(); + long type = p.getType(); + Object value = p.getValue(); + out(" Property ID: " + id + ", type: " + type + + ", value: " + value); + } + } + } + } + + static void out(final String msg) + { + System.out.println(msg); + } + + static String hex(final byte[] bytes) + { + return HexDump.dump(bytes, 0L, 0); + } + +} diff --git a/poi-examples/src/main/java/poi/hpsf/examples/ReadTitle.java b/poi-examples/src/main/java/poi/hpsf/examples/ReadTitle.java new file mode 100644 index 0000000000..c036d222b6 --- /dev/null +++ b/poi-examples/src/main/java/poi/hpsf/examples/ReadTitle.java @@ -0,0 +1,82 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hpsf.examples; + +import java.io.FileInputStream; +import java.io.IOException; + +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.SummaryInformation; +import org.apache.poi.poifs.eventfilesystem.POIFSReader; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; + +/** + *

    Sample application showing how to read a OLE 2 document's + * title. Call it with the document's file name as command line + * parameter.

    + * + *

    Explanations can be found in the HPSF HOW-TO.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class ReadTitle +{ + /** + *

    Runs the example program.

    + * + * @param args Command-line arguments. The first command-line argument must + * be the name of a POI filesystem to read. + * @throws IOException if any I/O exception occurs. + */ + public static void main(final String[] args) throws IOException + { + final String filename = args[0]; + POIFSReader r = new POIFSReader(); + r.registerListener(new MyPOIFSReaderListener(), + "\005SummaryInformation"); + r.read(new FileInputStream(filename)); + } + + + static class MyPOIFSReaderListener implements POIFSReaderListener + { + public void processPOIFSReaderEvent(final POIFSReaderEvent event) + { + SummaryInformation si = null; + try + { + si = (SummaryInformation) + PropertySetFactory.create(event.getStream()); + } + catch (Exception ex) + { + throw new RuntimeException + ("Property set stream \"" + + event.getPath() + event.getName() + "\": " + ex); + } + final String title = si.getTitle(); + if (title != null) + System.out.println("Title: \"" + title + "\""); + else + System.out.println("Document has no title."); + } + } + +} diff --git a/poi-examples/src/main/java/poi/hpsf/examples/WriteAuthorAndTitle.java b/poi-examples/src/main/java/poi/hpsf/examples/WriteAuthorAndTitle.java new file mode 100644 index 0000000000..00749ab4d2 --- /dev/null +++ b/poi-examples/src/main/java/poi/hpsf/examples/WriteAuthorAndTitle.java @@ -0,0 +1,423 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hpsf.examples; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.Map; + +import org.apache.poi.hpsf.HPSFRuntimeException; +import org.apache.poi.hpsf.MarkUnsupportedException; +import org.apache.poi.hpsf.MutablePropertySet; +import org.apache.poi.hpsf.MutableSection; +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.PropertySet; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.SummaryInformation; +import org.apache.poi.hpsf.Util; +import org.apache.poi.hpsf.Variant; +import org.apache.poi.hpsf.WritingNotSupportedException; +import org.apache.poi.hpsf.wellknown.PropertyIDMap; +import org.apache.poi.poifs.eventfilesystem.POIFSReader; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; +import org.apache.poi.poifs.filesystem.DirectoryEntry; +import org.apache.poi.poifs.filesystem.DocumentInputStream; +import org.apache.poi.poifs.filesystem.POIFSDocumentPath; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + +/** + *

    This class is a sample application which shows how to write or modify the + * author and title property of an OLE 2 document. This could be done in two + * different ways:

    + * + *
      + * + *
    • The first approach is to open the OLE 2 file as a POI filesystem + * (see class {@link POIFSFileSystem}), read the summary information property + * set (see classes {@link SummaryInformation} and {@link PropertySet}), write + * the author and title properties into it and write the property set back into + * the POI filesystem.

    • + * + *
    • The second approach does not modify the original POI filesystem, but + * instead creates a new one. All documents from the original POIFS are copied + * to the destination POIFS, except for the summary information stream. The + * latter is modified by setting the author and title property before writing + * it to the destination POIFS. It there are several summary information streams + * in the original POIFS - e.g. in subordinate directories - they are modified + * just the same.

    • + * + *
    + * + *

    This sample application takes the second approach. It expects the name of + * the existing POI filesystem's name as its first command-line parameter and + * the name of the output POIFS as the second command-line argument. The + * program then works as described above: It copies nearly all documents + * unmodified from the input POI filesystem to the output POI filesystem. If it + * encounters a summary information stream it reads its properties. Then it sets + * the "author" and "title" properties to new values and writes the modified + * summary information stream into the output file.

    + * + *

    Further explanations can be found in the HPSF HOW-TO.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class WriteAuthorAndTitle +{ + /** + *

    Runs the example program.

    + * + * @param args Command-line arguments. The first command-line argument must + * be the name of a POI filesystem to read. + * @throws IOException if any I/O exception occurs. + */ + public static void main(final String[] args) throws IOException + { + /* Check whether we have exactly two command-line arguments. */ + if (args.length != 2) + { + System.err.println("Usage: " + WriteAuthorAndTitle.class.getName() + + " originPOIFS destinationPOIFS"); + System.exit(1); + } + + /* Read the names of the origin and destination POI filesystems. */ + final String srcName = args[0]; + final String dstName = args[1]; + + /* Read the origin POIFS using the eventing API. The real work is done + * in the class ModifySICopyTheRest which is registered here as a + * POIFSReader. */ + final POIFSReader r = new POIFSReader(); + final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName); + r.registerListener(msrl); + r.read(new FileInputStream(srcName)); + + /* Write the new POIFS to disk. */ + msrl.close(); + } + + + + /** + *

    This class does all the work. As its name implies it modifies a + * summary information property set and copies everything else unmodified + * to the destination POI filesystem. Since an instance of it is registered + * as a {@link POIFSReader} its method {@link + * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each document + * in the origin POIFS.

    + */ + static class ModifySICopyTheRest implements POIFSReaderListener + { + String dstName; + OutputStream out; + POIFSFileSystem poiFs; + + + /** + *

    The constructor of a {@link ModifySICopyTheRest} instance creates + * the target POIFS. It also stores the name of the file the POIFS will + * be written to once it is complete.

    + * + * @param dstName The name of the disk file the destination POIFS is to + * be written to. + */ + public ModifySICopyTheRest(final String dstName) + { + this.dstName = dstName; + poiFs = new POIFSFileSystem(); + } + + + /** + *

    The method is called by POI's eventing API for each file in the + * origin POIFS.

    + */ + public void processPOIFSReaderEvent(final POIFSReaderEvent event) + { + /* The following declarations are shortcuts for accessing the + * "event" object. */ + final POIFSDocumentPath path = event.getPath(); + final String name = event.getName(); + final DocumentInputStream stream = event.getStream(); + + Throwable t = null; + + try + { + /* Find out whether the current document is a property set + * stream or not. */ + if (PropertySet.isPropertySetStream(stream)) + { + /* Yes, the current document is a property set stream. + * Let's create a PropertySet instance from it. */ + PropertySet ps = null; + try + { + ps = PropertySetFactory.create(stream); + } + catch (NoPropertySetStreamException ex) + { + /* This exception will not be thrown because we already + * checked above. */ + } + + /* Now we know that we really have a property set. The next + * step is to find out whether it is a summary information + * or not. */ + if (ps.isSummaryInformation()) + /* Yes, it is a summary information. We will modify it + * and write the result to the destination POIFS. */ + editSI(poiFs, path, name, ps); + else + /* No, it is not a summary information. We don't care + * about its internals and copy it unmodified to the + * destination POIFS. */ + copy(poiFs, path, name, ps); + } + else + /* No, the current document is not a property set stream. We + * copy it unmodified to the destination POIFS. */ + copy(poiFs, event.getPath(), event.getName(), stream); + } + catch (MarkUnsupportedException ex) + { + t = ex; + } + catch (IOException ex) + { + t = ex; + } + catch (WritingNotSupportedException ex) + { + t = ex; + } + + /* According to the definition of the processPOIFSReaderEvent method + * we cannot pass checked exceptions to the caller. The following + * lines check whether a checked exception occured and throws an + * unchecked exception. The message of that exception is that of + * the underlying checked exception. */ + if (t != null) + { + throw new HPSFRuntimeException + ("Could not read file \"" + path + "/" + name + + "\". Reason: " + Util.toString(t)); + } + } + + + /** + *

    Receives a summary information property set modifies (or creates) + * its "author" and "title" properties and writes the result under the + * same path and name as the origin to a destination POI filesystem.

    + * + * @param poiFs The POI filesystem to write to. + * @param path The original (and destination) stream's path. + * @param name The original (and destination) stream's name. + * @param si The property set. It should be a summary information + * property set. + * @throws IOException + * @throws WritingNotSupportedException + */ + public void editSI(final POIFSFileSystem poiFs, + final POIFSDocumentPath path, + final String name, + final PropertySet si) + throws WritingNotSupportedException, IOException + + { + /* Get the directory entry for the target stream. */ + final DirectoryEntry de = getPath(poiFs, path); + + /* Create a mutable property set as a copy of the original read-only + * property set. */ + final MutablePropertySet mps = new MutablePropertySet(si); + + /* Retrieve the section containing the properties to modify. A + * summary information property set contains exactly one section. */ + final MutableSection s = + (MutableSection) mps.getSections().get(0); + + /* Set the properties. */ + s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR, + "Rainer Klute"); + s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR, + "Test"); + + /* Create an input stream containing the bytes the property set + * stream consists of. */ + final InputStream pss = mps.toInputStream(); + + /* Write the property set stream to the POIFS. */ + de.createDocument(name, pss); + } + + + /** + *

    Writes a {@link PropertySet} to a POI filesystem. This method is + * simpler than {@link #editSI} because the origin property set has just + * to be copied.

    + * + * @param poiFs The POI filesystem to write to. + * @param path The file's path in the POI filesystem. + * @param name The file's name in the POI filesystem. + * @param ps The property set to write. + * @throws WritingNotSupportedException + * @throws IOException + */ + public void copy(final POIFSFileSystem poiFs, + final POIFSDocumentPath path, + final String name, + final PropertySet ps) + throws WritingNotSupportedException, IOException + { + final DirectoryEntry de = getPath(poiFs, path); + final MutablePropertySet mps = new MutablePropertySet(ps); + de.createDocument(name, mps.toInputStream()); + } + + + + /** + *

    Copies the bytes from a {@link DocumentInputStream} to a new + * stream in a POI filesystem.

    + * + * @param poiFs The POI filesystem to write to. + * @param path The source document's path. + * @param name The source document's name. + * @param stream The stream containing the source document. + * @throws IOException + */ + public void copy(final POIFSFileSystem poiFs, + final POIFSDocumentPath path, + final String name, + final DocumentInputStream stream) throws IOException + { + final DirectoryEntry de = getPath(poiFs, path); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + int c; + while ((c = stream.read()) != -1) + out.write(c); + stream.close(); + out.close(); + final InputStream in = + new ByteArrayInputStream(out.toByteArray()); + de.createDocument(name, in); + } + + + /** + *

    Writes the POI file system to a disk file.

    + * + * @throws FileNotFoundException + * @throws IOException + */ + public void close() throws FileNotFoundException, IOException + { + out = new FileOutputStream(dstName); + poiFs.writeFilesystem(out); + out.close(); + } + + + + /** Contains the directory paths that have already been created in the + * output POI filesystem and maps them to their corresponding + * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ + private final Map paths = new HashMap(); + + + + /** + *

    Ensures that the directory hierarchy for a document in a POI + * fileystem is in place. When a document is to be created somewhere in + * a POI filesystem its directory must be created first. This method + * creates all directories between the POI filesystem root and the + * directory the document should belong to which do not yet exist.

    + * + *

    Unfortunately POI does not offer a simple method to interrogate + * the POIFS whether a certain child node (file or directory) exists in + * a directory. However, since we always start with an empty POIFS which + * contains the root directory only and since each directory in the + * POIFS is created by this method we can maintain the POIFS's directory + * hierarchy ourselves: The {@link DirectoryEntry} of each directory + * created is stored in a {@link Map}. The directories' path names map + * to the corresponding {@link DirectoryEntry} instances.

    + * + * @param poiFs The POI filesystem the directory hierarchy is created + * in, if needed. + * @param path The document's path. This method creates those directory + * components of this hierarchy which do not yet exist. + * @return The directory entry of the document path's parent. The caller + * should use this {@link DirectoryEntry} to create documents in it. + */ + public DirectoryEntry getPath(final POIFSFileSystem poiFs, + final POIFSDocumentPath path) + { + try + { + /* Check whether this directory has already been created. */ + final String s = path.toString(); + DirectoryEntry de = (DirectoryEntry) paths.get(s); + if (de != null) + /* Yes: return the corresponding DirectoryEntry. */ + return de; + + /* No: We have to create the directory - or return the root's + * DirectoryEntry. */ + int l = path.length(); + if (l == 0) + /* Get the root directory. It does not have to be created + * since it always exists in a POIFS. */ + de = poiFs.getRoot(); + else + { + /* Create a subordinate directory. The first step is to + * ensure that the parent directory exists: */ + de = getPath(poiFs, path.getParent()); + /* Now create the target directory: */ + de = de.createDirectory(path.getComponent + (path.length() - 1)); + } + paths.put(s, de); + return de; + } + catch (IOException ex) + { + /* This exception will be thrown if the directory already + * exists. However, since we have full control about directory + * creation we can ensure that this will never happen. */ + ex.printStackTrace(System.err); + throw new RuntimeException(ex.toString()); + /* FIXME (2): Replace the previous line by the following once we + * no longer need JDK 1.3 compatibility. */ + // throw new RuntimeException(ex); + } + } + } + +} diff --git a/poi-examples/src/main/java/poi/hpsf/examples/WriteTitle.java b/poi-examples/src/main/java/poi/hpsf/examples/WriteTitle.java new file mode 100644 index 0000000000..22e1f69cdd --- /dev/null +++ b/poi-examples/src/main/java/poi/hpsf/examples/WriteTitle.java @@ -0,0 +1,106 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hpsf.examples; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.poi.hpsf.MutableProperty; +import org.apache.poi.hpsf.MutablePropertySet; +import org.apache.poi.hpsf.MutableSection; +import org.apache.poi.hpsf.SummaryInformation; +import org.apache.poi.hpsf.Variant; +import org.apache.poi.hpsf.WritingNotSupportedException; +import org.apache.poi.hpsf.wellknown.PropertyIDMap; +import org.apache.poi.hpsf.wellknown.SectionIDMap; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + +/** + *

    This class is a simple sample application showing how to create a property + * set and write it to disk.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class WriteTitle +{ + /** + *

    Runs the example program.

    + * + * @param args Command-line arguments. The first and only command-line + * argument is the name of the POI file system to create. + * @throws IOException if any I/O exception occurs. + * @throws WritingNotSupportedException if HPSF does not (yet) support + * writing a certain property type. + */ + 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)); + } + +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/ApacheconEU08.java b/poi-examples/src/main/java/poi/hslf/examples/ApacheconEU08.java new file mode 100644 index 0000000000..25f1eab9c5 --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/ApacheconEU08.java @@ -0,0 +1,515 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.*; +import org.apache.poi.hslf.model.*; +import org.apache.poi.hslf.record.TextHeaderAtom; + +import java.io.IOException; +import java.io.FileOutputStream; +import java.awt.*; + +/** + * Presentation for Fast Feather Track on ApacheconEU 2008 + * + * @author Yegor Kozlov + */ +public final class ApacheconEU08 { + + public static void main(String[] args) throws IOException { + SlideShow ppt = new SlideShow(); + ppt.setPageSize(new Dimension(720, 540)); + + slide1(ppt); + slide2(ppt); + slide3(ppt); + slide4(ppt); + slide5(ppt); + slide6(ppt); + slide7(ppt); + slide8(ppt); + slide9(ppt); + slide10(ppt); + slide11(ppt); + slide12(ppt); + + FileOutputStream out = new FileOutputStream("apachecon_eu_08.ppt"); + ppt.write(out); + out.close(); + + } + + public static void slide1(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.CENTER_TITLE_TYPE); + tr1.setText("POI-HSLF"); + box1.setAnchor(new Rectangle(54, 78, 612, 115)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.setRunType(TextHeaderAtom.CENTRE_BODY_TYPE); + tr2.setText("Java API To Access Microsoft PowerPoint Format Files"); + box2.setAnchor(new Rectangle(108, 204, 504, 138)); + slide.addShape(box2); + + TextBox box3 = new TextBox(); + TextRun tr3 = box3.getTextRun(); + tr3.getRichTextRuns()[0].setFontSize(32); + box3.setHorizontalAlignment(TextBox.AlignCenter); + tr3.setText( + "Yegor Kozlov\r" + + "yegor - apache - org"); + box3.setAnchor(new Rectangle(206, 348, 310, 84)); + slide.addShape(box3); + } + + public static void slide2(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.TITLE_TYPE); + tr1.setText("What is HSLF?"); + box1.setAnchor(new Rectangle(36, 21, 648, 90)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.setRunType(TextHeaderAtom.BODY_TYPE); + tr2.setText("HorribleSLideshowFormat is the POI Project's pure Java implementation " + + "of the Powerpoint binary file format. \r" + + "POI sub-project since 2005\r" + + "Started by Nick Birch, Yegor Kozlov joined soon after"); + box2.setAnchor(new Rectangle(36, 126, 648, 356)); + slide.addShape(box2); + + + } + + public static void slide3(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.TITLE_TYPE); + tr1.setText("HSLF in a Nutshell"); + box1.setAnchor(new Rectangle(36, 15, 648, 65)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.setRunType(TextHeaderAtom.BODY_TYPE); + tr2.setText( + "HSLF provides a way to read, create and modify MS PowerPoint presentations\r" + + "Pure Java API - you don't need PowerPoint to read and write *.ppt files\r" + + "Comprehensive support of PowerPoint objects"); + tr2.getRichTextRuns()[0].setFontSize(28); + box2.setAnchor(new Rectangle(36, 80, 648, 200)); + slide.addShape(box2); + + TextBox box3 = new TextBox(); + TextRun tr3 = box3.getTextRun(); + tr3.setRunType(TextHeaderAtom.BODY_TYPE); + tr3.setText( + "Rich text\r" + + "Tables\r" + + "Shapes\r" + + "Pictures\r" + + "Master slides"); + tr3.getRichTextRuns()[0].setFontSize(24); + tr3.getRichTextRuns()[0].setIndentLevel(1); + box3.setAnchor(new Rectangle(36, 265, 648, 150)); + slide.addShape(box3); + + TextBox box4 = new TextBox(); + TextRun tr4 = box4.getTextRun(); + tr4.setRunType(TextHeaderAtom.BODY_TYPE); + tr4.setText("Access to low level data structures"); + box4.setAnchor(new Rectangle(36, 430, 648, 50)); + slide.addShape(box4); + } + + public static void slide4(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + String[][] txt1 = { + {"Note"}, + {"This presentation was created programmatically using POI HSLF"} + }; + Table table1 = new Table(2, 1); + for (int i = 0; i < txt1.length; i++) { + for (int j = 0; j < txt1[i].length; j++) { + TableCell cell = table1.getCell(i, j); + cell.setText(txt1[i][j]); + cell.getTextRun().getRichTextRuns()[0].setFontSize(10); + RichTextRun rt = cell.getTextRun().getRichTextRuns()[0]; + rt.setFontName("Arial"); + rt.setBold(true); + if(i == 0){ + rt.setFontSize(32); + rt.setFontColor(Color.white); + cell.getFill().setForegroundColor(new Color(0, 153, 204)); + } else { + rt.setFontSize(28); + cell.getFill().setForegroundColor(new Color(235, 239, 241)); + } + cell.setVerticalAlignment(TextBox.AnchorMiddle); + } + } + + Line border1 = table1.createBorder(); + border1.setLineColor(Color.black); + border1.setLineWidth(1.0); + table1.setAllBorders(border1); + + Line border2 = table1.createBorder(); + border2.setLineColor(Color.black); + border2.setLineWidth(2.0); + table1.setOutsideBorders(border2); + + table1.setColumnWidth(0, 510); + table1.setRowHeight(0, 60); + table1.setRowHeight(1, 100); + slide.addShape(table1); + + table1.moveTo(100, 100); + + TextBox box1 = new TextBox(); + box1.setHorizontalAlignment(TextBox.AlignCenter); + TextRun tr1 = box1.getTextRun(); + tr1.setText("The source code is available at\r" + + "http://people.apache.org/~yegor/apachecon_eu08/"); + RichTextRun rt = tr1.getRichTextRuns()[0]; + rt.setFontSize(24); + box1.setAnchor(new Rectangle(80, 356, 553, 65)); + slide.addShape(box1); + + } + + public static void slide5(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.TITLE_TYPE); + tr1.setText("HSLF in Action - 1\rData Extraction"); + box1.setAnchor(new Rectangle(36, 21, 648, 100)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.setRunType(TextHeaderAtom.BODY_TYPE); + tr2.setText( + "Text from slides and notes\r" + + "Images\r" + + "Shapes and their properties (type, position in the slide, color, font, etc.)"); + box2.setAnchor(new Rectangle(36, 150, 648, 300)); + slide.addShape(box2); + + + } + + public static void slide6(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.TITLE_TYPE); + tr1.setText("HSLF in Action - 2"); + box1.setAnchor(new Rectangle(36, 20, 648, 90)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.getRichTextRuns()[0].setFontSize(18); + tr2.setText("Creating a simple presentation from scratch"); + box2.setAnchor(new Rectangle(170, 100, 364, 30)); + slide.addShape(box2); + + TextBox box3 = new TextBox(); + TextRun tr3 = box3.getTextRun(); + RichTextRun rt3 = tr3.getRichTextRuns()[0]; + rt3.setFontName("Courier New"); + rt3.setFontSize(8); + tr3.setText( + " SlideShow ppt = new SlideShow();\r" + + " Slide slide = ppt.createSlide();\r" + + "\r" + + " TextBox box2 = new TextBox();\r" + + " box2.setHorizontalAlignment(TextBox.AlignCenter);\r" + + " box2.setVerticalAlignment(TextBox.AnchorMiddle);\r" + + " box2.getTextRun().setText(\"Java Code\");\r" + + " box2.getFill().setForegroundColor(new Color(187, 224, 227));\r" + + " box2.setLineColor(Color.black);\r" + + " box2.setLineWidth(0.75);\r" + + " box2.setAnchor(new Rectangle(66, 243, 170, 170));\r" + + " slide.addShape(box2);\r" + + "\r" + + " TextBox box3 = new TextBox();\r" + + " box3.setHorizontalAlignment(TextBox.AlignCenter);\r" + + " box3.setVerticalAlignment(TextBox.AnchorMiddle);\r" + + " box3.getTextRun().setText(\"*.ppt file\");\r" + + " box3.setLineWidth(0.75);\r" + + " box3.setLineColor(Color.black);\r" + + " box3.getFill().setForegroundColor(new Color(187, 224, 227));\r" + + " box3.setAnchor(new Rectangle(473, 243, 170, 170));\r" + + " slide.addShape(box3);\r" + + "\r" + + " AutoShape box4 = new AutoShape(ShapeTypes.Arrow);\r" + + " box4.getFill().setForegroundColor(new Color(187, 224, 227));\r" + + " box4.setLineWidth(0.75);\r" + + " box4.setLineColor(Color.black);\r" + + " box4.setAnchor(new Rectangle(253, 288, 198, 85));\r" + + " slide.addShape(box4);\r" + + "\r" + + " FileOutputStream out = new FileOutputStream(\"hslf-demo.ppt\");\r" + + " ppt.write(out);\r" + + " out.close();"); + box3.setAnchor(new Rectangle(30, 150, 618, 411)); + slide.addShape(box3); + } + + public static void slide7(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box2 = new TextBox(); + box2.setHorizontalAlignment(TextBox.AlignCenter); + box2.setVerticalAlignment(TextBox.AnchorMiddle); + box2.getTextRun().setText("Java Code"); + box2.getFill().setForegroundColor(new Color(187, 224, 227)); + box2.setLineColor(Color.black); + box2.setLineWidth(0.75); + box2.setAnchor(new Rectangle(66, 243, 170, 170)); + slide.addShape(box2); + + TextBox box3 = new TextBox(); + box3.setHorizontalAlignment(TextBox.AlignCenter); + box3.setVerticalAlignment(TextBox.AnchorMiddle); + box3.getTextRun().setText("*.ppt file"); + box3.setLineWidth(0.75); + box3.setLineColor(Color.black); + box3.getFill().setForegroundColor(new Color(187, 224, 227)); + box3.setAnchor(new Rectangle(473, 243, 170, 170)); + slide.addShape(box3); + + AutoShape box4 = new AutoShape(ShapeTypes.Arrow); + box4.getFill().setForegroundColor(new Color(187, 224, 227)); + box4.setLineWidth(0.75); + box4.setLineColor(Color.black); + box4.setAnchor(new Rectangle(253, 288, 198, 85)); + slide.addShape(box4); + } + + public static void slide8(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.TITLE_TYPE); + tr1.setText("Wait, there is more!"); + box1.setAnchor(new Rectangle(36, 21, 648, 90)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.setRunType(TextHeaderAtom.BODY_TYPE); + tr2.setText( + "Rich text\r" + + "Tables\r" + + "Pictures (JPEG, PNG, BMP, WMF, PICT)\r" + + "Comprehensive formatting features"); + box2.setAnchor(new Rectangle(36, 126, 648, 356)); + slide.addShape(box2); + } + + public static void slide9(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.TITLE_TYPE); + tr1.setText("HSLF in Action - 3"); + box1.setAnchor(new Rectangle(36, 20, 648, 50)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.getRichTextRuns()[0].setFontSize(18); + tr2.setText("PPGraphics2D: PowerPoint Graphics2D driver"); + box2.setAnchor(new Rectangle(178, 70, 387, 30)); + slide.addShape(box2); + + TextBox box3 = new TextBox(); + TextRun tr3 = box3.getTextRun(); + RichTextRun rt3 = tr3.getRichTextRuns()[0]; + rt3.setFontName("Courier New"); + rt3.setFontSize(8); + tr3.setText( + " //bar chart data. The first value is the bar color, the second is the width\r" + + " Object[] def = new Object[]{\r" + + " Color.yellow, new Integer(100),\r" + + " Color.green, new Integer(150),\r" + + " Color.gray, new Integer(75),\r" + + " Color.red, new Integer(200),\r" + + " };\r" + + "\r" + + " SlideShow ppt = new SlideShow();\r" + + " Slide slide = ppt.createSlide();\r" + + "\r" + + " ShapeGroup group = new ShapeGroup();\r" + + " //define position of the drawing in the slide\r" + + " Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300);\r" + + " group.setAnchor(bounds);\r" + + " slide.addShape(group);\r" + + " Graphics2D graphics = new PPGraphics2D(group);\r" + + "\r" + + " //draw a simple bar graph\r" + + " int x = bounds.x + 50, y = bounds.y + 50;\r" + + " graphics.setFont(new Font(\"Arial\", Font.BOLD, 10));\r" + + " for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {\r" + + " graphics.setColor(Color.black);\r" + + " int width = ((Integer)def[i+1]).intValue();\r" + + " graphics.drawString(\"Q\" + idx, x-20, y+20);\r" + + " graphics.drawString(width + \"%\", x + width + 10, y + 20);\r" + + " graphics.setColor((Color)def[i]);\r" + + " graphics.fill(new Rectangle(x, y, width, 30));\r" + + " y += 40;\r" + + " }\r" + + " graphics.setColor(Color.black);\r" + + " graphics.setFont(new Font(\"Arial\", Font.BOLD, 14));\r" + + " graphics.draw(bounds);\r" + + " graphics.drawString(\"Performance\", x + 70, y + 40);\r" + + "\r" + + " FileOutputStream out = new FileOutputStream(\"hslf-demo.ppt\");\r" + + " ppt.write(out);\r" + + " out.close();"); + box3.setAnchor(new Rectangle(96, 110, 499, 378)); + slide.addShape(box3); + } + + public static void slide10(SlideShow ppt) throws IOException { + //bar chart data. The first value is the bar color, the second is the width + Object[] def = new Object[]{ + Color.yellow, new Integer(100), + Color.green, new Integer(150), + Color.gray, new Integer(75), + Color.red, new Integer(200), + }; + + Slide slide = ppt.createSlide(); + + ShapeGroup group = new ShapeGroup(); + //define position of the drawing in the slide + Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); + group.setAnchor(bounds); + slide.addShape(group); + Graphics2D graphics = new PPGraphics2D(group); + + //draw a simple bar graph + int x = bounds.x + 50, y = bounds.y + 50; + graphics.setFont(new Font("Arial", Font.BOLD, 10)); + for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { + graphics.setColor(Color.black); + int width = ((Integer)def[i+1]).intValue(); + graphics.drawString("Q" + idx, x-20, y+20); + graphics.drawString(width + "%", x + width + 10, y + 20); + graphics.setColor((Color)def[i]); + graphics.fill(new Rectangle(x, y, width, 30)); + y += 40; + } + graphics.setColor(Color.black); + graphics.setFont(new Font("Arial", Font.BOLD, 14)); + graphics.draw(bounds); + graphics.drawString("Performance", x + 70, y + 40); + + } + + public static void slide11(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.TITLE_TYPE); + tr1.setText("HSLF Development Plans"); + box1.setAnchor(new Rectangle(36, 21, 648, 90)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.setRunType(TextHeaderAtom.BODY_TYPE); + tr2.getRichTextRuns()[0].setFontSize(32); + tr2.setText( + "Support for more PowerPoint functionality\r" + + "Rendering slides into java.awt.Graphics2D"); + box2.setAnchor(new Rectangle(36, 126, 648, 100)); + slide.addShape(box2); + + TextBox box3 = new TextBox(); + TextRun tr3 = box3.getTextRun(); + tr3.setRunType(TextHeaderAtom.BODY_TYPE); + tr3.getRichTextRuns()[0].setIndentLevel(1); + tr3.setText( + "A way to export slides into images or other formats"); + box3.setAnchor(new Rectangle(36, 220, 648, 70)); + slide.addShape(box3); + + TextBox box4 = new TextBox(); + TextRun tr4 = box4.getTextRun(); + tr4.setRunType(TextHeaderAtom.BODY_TYPE); + tr4.getRichTextRuns()[0].setFontSize(32); + tr4.setText( + "Integration with Apache FOP - Formatting Objects Processor"); + box4.setAnchor(new Rectangle(36, 290, 648, 90)); + slide.addShape(box4); + + TextBox box5 = new TextBox(); + TextRun tr5 = box5.getTextRun(); + tr5.setRunType(TextHeaderAtom.BODY_TYPE); + tr5.getRichTextRuns()[0].setIndentLevel(1); + tr5.setText( + "Transformation of XSL-FO into PPT\r" + + "PPT2PDF transcoder"); + box5.setAnchor(new Rectangle(36, 380, 648, 100)); + slide.addShape(box5); + } + + public static void slide12(SlideShow ppt) throws IOException { + Slide slide = ppt.createSlide(); + + TextBox box1 = new TextBox(); + TextRun tr1 = box1.getTextRun(); + tr1.setRunType(TextHeaderAtom.CENTER_TITLE_TYPE); + tr1.setText("Questions?"); + box1.setAnchor(new Rectangle(54, 167, 612, 115)); + slide.addShape(box1); + + TextBox box2 = new TextBox(); + TextRun tr2 = box2.getTextRun(); + tr2.setRunType(TextHeaderAtom.CENTRE_BODY_TYPE); + tr2.setText( + "http://poi.apache.org/hslf/\r" + + "http://people.apache.org/~yegor"); + box2.setAnchor(new Rectangle(108, 306, 504, 138)); + slide.addShape(box2); + } +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/BulletsDemo.java b/poi-examples/src/main/java/poi/hslf/examples/BulletsDemo.java new file mode 100644 index 0000000000..3a97b61aa0 --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/BulletsDemo.java @@ -0,0 +1,62 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.SlideShow; +import org.apache.poi.hslf.usermodel.RichTextRun; +import org.apache.poi.hslf.model.Slide; +import org.apache.poi.hslf.model.TextBox; + +import java.io.FileOutputStream; + +/** + * How to create a single-level bulleted list + * and change some of the bullet attributes + * + * @author Yegor Kozlov + */ +public final class BulletsDemo { + + public static void main(String[] args) throws Exception { + + SlideShow ppt = new SlideShow(); + + Slide slide = ppt.createSlide(); + + TextBox shape = new TextBox(); + RichTextRun rt = shape.getTextRun().getRichTextRuns()[0]; + shape.setText( + "January\r" + + "February\r" + + "March\r" + + "April"); + rt.setFontSize(42); + rt.setBullet(true); + rt.setBulletOffset(0); //bullet offset + rt.setTextOffset(50); //text offset (should be greater than bullet offset) + rt.setBulletChar('\u263A'); //bullet character + slide.addShape(shape); + + shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide + slide.addShape(shape); + + FileOutputStream out = new FileOutputStream("bullets.ppt"); + ppt.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/CreateHyperlink.java b/poi-examples/src/main/java/poi/hslf/examples/CreateHyperlink.java new file mode 100644 index 0000000000..0aa8db32de --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/CreateHyperlink.java @@ -0,0 +1,75 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.SlideShow; +import org.apache.poi.hslf.model.*; + +import java.io.FileOutputStream; +import java.awt.*; + +/** + * Demonstrates how to create hyperlinks in PowerPoint presentations + * + * @author Yegor Kozlov + */ +public final class CreateHyperlink { + + public static void main(String[] args) throws Exception { + SlideShow ppt = new SlideShow(); + + Slide slideA = ppt.createSlide(); + Slide slideB = ppt.createSlide(); + Slide slideC = ppt.createSlide(); + + // link to a URL + TextBox textBox1 = new TextBox(); + textBox1.setText("Apache POI"); + textBox1.setAnchor(new Rectangle(100, 100, 200, 50)); + + String text = textBox1.getText(); + Hyperlink link = new Hyperlink(); + link.setAddress("http://www.apache.org"); + link.setTitle(textBox1.getText()); + int linkId = ppt.addHyperlink(link); + + // apply link to the text + textBox1.setHyperlink(linkId, 0, text.length()); + + slideA.addShape(textBox1); + + // link to another slide + TextBox textBox2 = new TextBox(); + textBox2.setText("Go to slide #3"); + textBox2.setAnchor(new Rectangle(100, 300, 200, 50)); + + Hyperlink link2 = new Hyperlink(); + link2.setAddress(slideC); + ppt.addHyperlink(link2); + + // apply link to the whole shape + textBox2.setHyperlink(link2); + + slideA.addShape(textBox2); + + FileOutputStream out = new FileOutputStream("hyperlink.ppt"); + ppt.write(out); + out.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/DataExtraction.java b/poi-examples/src/main/java/poi/hslf/examples/DataExtraction.java new file mode 100644 index 0000000000..a278e894b6 --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/DataExtraction.java @@ -0,0 +1,148 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.*; +import org.apache.poi.hslf.model.*; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hwpf.HWPFDocument; +import org.apache.poi.hwpf.usermodel.Range; +import org.apache.poi.hwpf.usermodel.Paragraph; + +import java.io.*; + +/** + * Demonstrates how you can extract misc embedded data from a ppt file + * + * @author Yegor Kozlov + */ +public final class DataExtraction { + + public static void main(String args[]) throws Exception { + + if (args.length == 0) { + usage(); + return; + } + + FileInputStream is = new FileInputStream(args[0]); + SlideShow ppt = new SlideShow(is); + is.close(); + + //extract all sound files embedded in this presentation + SoundData[] sound = ppt.getSoundData(); + for (int i = 0; i < sound.length; i++) { + String type = sound[i].getSoundType(); //*.wav + String name = sound[i].getSoundName(); //typically file name + byte[] data = sound[i].getData(); //raw bytes + + //save the sound on disk + FileOutputStream out = new FileOutputStream(name + type); + out.write(data); + out.close(); + } + + //extract embedded OLE documents + Slide[] slide = ppt.getSlides(); + for (int i = 0; i < slide.length; i++) { + Shape[] shape = slide[i].getShapes(); + for (int j = 0; j < shape.length; j++) { + if (shape[j] instanceof OLEShape) { + OLEShape ole = (OLEShape) shape[j]; + ObjectData data = ole.getObjectData(); + String name = ole.getInstanceName(); + if ("Worksheet".equals(name)) { + + //read xls + HSSFWorkbook wb = new HSSFWorkbook(data.getData()); + + } else if ("Document".equals(name)) { + HWPFDocument doc = new HWPFDocument(data.getData()); + //read the word document + Range r = doc.getRange(); + for(int k = 0; k < r.numParagraphs(); k++) { + Paragraph p = r.getParagraph(k); + System.out.println(p.text()); + } + + //save on disk + FileOutputStream out = new FileOutputStream(name + "-("+(j)+").doc"); + doc.write(out); + out.close(); + } else { + FileOutputStream out = new FileOutputStream(ole.getProgID() + "-"+(j+1)+".dat"); + InputStream dis = data.getData(); + byte[] chunk = new byte[2048]; + int count; + while ((count = dis.read(chunk)) >= 0) { + out.write(chunk,0,count); + } + is.close(); + out.close(); + } + } + + } + } + + //Pictures + for (int i = 0; i < slide.length; i++) { + Shape[] shape = slide[i].getShapes(); + for (int j = 0; j < shape.length; j++) { + if (shape[j] instanceof Picture) { + Picture p = (Picture) shape[j]; + PictureData data = p.getPictureData(); + String name = p.getPictureName(); + int type = data.getType(); + String ext; + switch (type) { + case Picture.JPEG: + ext = ".jpg"; + break; + case Picture.PNG: + ext = ".png"; + break; + case Picture.WMF: + ext = ".wmf"; + break; + case Picture.EMF: + ext = ".emf"; + break; + case Picture.PICT: + ext = ".pict"; + break; + case Picture.DIB: + ext = ".dib"; + break; + default: + continue; + } + FileOutputStream out = new FileOutputStream("pict-" + j + ext); + out.write(data.getData()); + out.close(); + } + + } + } + + } + + private static void usage(){ + System.out.println("Usage: DataExtraction ppt"); + } +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/Graphics2DDemo.java b/poi-examples/src/main/java/poi/hslf/examples/Graphics2DDemo.java new file mode 100644 index 0000000000..8d7921146a --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/Graphics2DDemo.java @@ -0,0 +1,79 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.SlideShow; +import org.apache.poi.hslf.model.*; + +import java.awt.*; +import java.io.FileOutputStream; + +/** + * Demonstrates how to draw into a slide using the HSLF Graphics2D driver. + * + * @author Yegor Kozlov + */ +public final class Graphics2DDemo { + + /** + * A simple bar chart demo + */ + public static void main(String[] args) throws Exception { + SlideShow ppt = new SlideShow(); + + //bar chart data. The first value is the bar color, the second is the width + Object[] def = new Object[]{ + Color.yellow, new Integer(40), + Color.green, new Integer(60), + Color.gray, new Integer(30), + Color.red, new Integer(80), + }; + + Slide slide = ppt.createSlide(); + + ShapeGroup group = new ShapeGroup(); + //define position of the drawing in the slide + Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); + group.setAnchor(bounds); + group.setCoordinates(new java.awt.Rectangle(0, 0, 100, 100)); + slide.addShape(group); + Graphics2D graphics = new PPGraphics2D(group); + + //draw a simple bar graph + int x = 10, y = 10; + graphics.setFont(new Font("Arial", Font.BOLD, 10)); + for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { + graphics.setColor(Color.black); + int width = ((Integer)def[i+1]).intValue(); + graphics.drawString("Q" + idx, x-5, y+10); + graphics.drawString(width + "%", x + width+3, y + 10); + graphics.setColor((Color)def[i]); + graphics.fill(new Rectangle(x, y, width, 10)); + y += 15; + } + graphics.setColor(Color.black); + graphics.setFont(new Font("Arial", Font.BOLD, 14)); + graphics.draw(group.getCoordinates()); + graphics.drawString("Performance", x + 30, y + 10); + + FileOutputStream out = new FileOutputStream("hslf-graphics.ppt"); + ppt.write(out); + out.close(); + } + +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/HeadersFootersDemo.java b/poi-examples/src/main/java/poi/hslf/examples/HeadersFootersDemo.java new file mode 100644 index 0000000000..3ebcecc90f --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/HeadersFootersDemo.java @@ -0,0 +1,51 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.SlideShow; +import org.apache.poi.hslf.model.HeadersFooters; +import org.apache.poi.hslf.model.Slide; + +import java.io.FileOutputStream; + +/** + * Demonstrates how to set headers / footers + * + * @author Yegor Kozlov + */ +public class HeadersFootersDemo { + public static void main(String[] args) throws Exception { + SlideShow ppt = new SlideShow(); + + HeadersFooters slideHeaders = ppt.getSlideHeadersFooters(); + slideHeaders.setFootersText("Created by POI-HSLF"); + slideHeaders.setSlideNumberVisible(true); + slideHeaders.setDateTimeText("custom date time"); + + HeadersFooters notesHeaders = ppt.getNotesHeadersFooters(); + notesHeaders.setFootersText("My notes footers"); + notesHeaders.setHeaderText("My notes header"); + + Slide slide = ppt.createSlide(); + + FileOutputStream out = new FileOutputStream("headers_footers.ppt"); + ppt.write(out); + out.close(); + + } + +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/Hyperlinks.java b/poi-examples/src/main/java/poi/hslf/examples/Hyperlinks.java new file mode 100644 index 0000000000..968426c513 --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/Hyperlinks.java @@ -0,0 +1,81 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.SlideShow; +import org.apache.poi.hslf.model.Slide; +import org.apache.poi.hslf.model.TextRun; +import org.apache.poi.hslf.model.Hyperlink; +import org.apache.poi.hslf.model.Shape; + +import java.io.FileInputStream; + +/** + * Demonstrates how to read hyperlinks from a presentation + * + * @author Yegor Kozlov + */ +public final class Hyperlinks { + + public static void main(String[] args) throws Exception { + for (int i = 0; i < args.length; i++) { + FileInputStream is = new FileInputStream(args[i]); + SlideShow ppt = new SlideShow(is); + is.close(); + + Slide[] slide = ppt.getSlides(); + for (int j = 0; j < slide.length; j++) { + System.out.println("slide " + slide[j].getSlideNumber()); + + //read hyperlinks from the slide's text runs + System.out.println("reading hyperlinks from the text runs"); + TextRun[] txt = slide[j].getTextRuns(); + for (int k = 0; k < txt.length; k++) { + String text = txt[k].getText(); + Hyperlink[] links = txt[k].getHyperlinks(); + if(links != null) for (int l = 0; l < links.length; l++) { + Hyperlink link = links[l]; + String title = link.getTitle(); + String address = link.getAddress(); + System.out.println(" " + title); + System.out.println(" " + address); + String substring = text.substring(link.getStartIndex(), link.getEndIndex()-1);//in ppt end index is inclusive + System.out.println(" " + substring); + } + } + + //in PowerPoint you can assign a hyperlink to a shape without text, + //for example to a Line object. The code below demonstrates how to + //read such hyperlinks + System.out.println(" reading hyperlinks from the slide's shapes"); + Shape[] sh = slide[j].getShapes(); + for (int k = 0; k < sh.length; k++) { + Hyperlink link = sh[k].getHyperlink(); + if(link != null) { + String title = link.getTitle(); + String address = link.getAddress(); + System.out.println(" " + title); + System.out.println(" " + address); + } + } + } + + } + + } +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/PPT2PNG.java b/poi-examples/src/main/java/poi/hslf/examples/PPT2PNG.java new file mode 100644 index 0000000000..99037d3264 --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/PPT2PNG.java @@ -0,0 +1,103 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.*; +import org.apache.poi.hslf.model.*; + +import javax.imageio.ImageIO; +import java.io.FileOutputStream; +import java.io.FileInputStream; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.awt.geom.Rectangle2D; + +/** + * Demonstrates how you can use HSLF to convert each slide into a PNG image + * + * @author Yegor Kozlov + */ +public final class PPT2PNG { + + public static void main(String args[]) throws Exception { + + if (args.length == 0) { + usage(); + return; + } + + int slidenum = -1; + float scale = 1; + String file = null; + + for (int i = 0; i < args.length; i++) { + if (args[i].startsWith("-")) { + if ("-scale".equals(args[i])){ + scale = Float.parseFloat(args[++i]); + } else if ("-slide".equals(args[i])) { + slidenum = Integer.parseInt(args[++i]); + } + } else { + file = args[i]; + } + } + if(file == null){ + usage(); + return; + } + + FileInputStream is = new FileInputStream(file); + SlideShow ppt = new SlideShow(is); + is.close(); + + Dimension pgsize = ppt.getPageSize(); + int width = (int)(pgsize.width*scale); + int height = (int)(pgsize.height*scale); + + Slide[] slide = ppt.getSlides(); + for (int i = 0; i < slide.length; i++) { + if (slidenum != -1 && slidenum != (i+1)) continue; + + String title = slide[i].getTitle(); + System.out.println("Rendering slide "+slide[i].getSlideNumber() + (title == null ? "" : ": " + title)); + + BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = img.createGraphics(); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); + graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + + graphics.setPaint(Color.white); + graphics.fill(new Rectangle2D.Float(0, 0, width, height)); + + graphics.scale((double)width/pgsize.width, (double)height/pgsize.height); + + slide[i].draw(graphics); + + String fname = file.replaceAll("\\.ppt", "-" + (i+1) + ".png"); + FileOutputStream out = new FileOutputStream(fname); + ImageIO.write(img, "png", out); + out.close(); + } + } + + private static void usage(){ + System.out.println("Usage: PPT2PNG [-scale -slide ] ppt"); + } +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/SoundFinder.java b/poi-examples/src/main/java/poi/hslf/examples/SoundFinder.java new file mode 100644 index 0000000000..b31019db94 --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/SoundFinder.java @@ -0,0 +1,80 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.hslf.examples; +import org.apache.poi.ddf.*; +import org.apache.poi.hslf.model.*; +import org.apache.poi.hslf.record.InteractiveInfo; +import org.apache.poi.hslf.record.InteractiveInfoAtom; +import org.apache.poi.hslf.record.Record; +import org.apache.poi.hslf.usermodel.*; +import java.io.FileInputStream; +import java.util.Iterator; +import java.util.List; + +/** + * For each slide iterate over shapes and found associated sound data. + * + * @author Yegor Kozlov + */ +public class SoundFinder { + public static void main(String[] args) throws Exception { + SlideShow ppt = new SlideShow(new FileInputStream(args[0])); + SoundData[] sounds = ppt.getSoundData(); + + Slide[] slide = ppt.getSlides(); + for (int i = 0; i < slide.length; i++) { + Shape[] shape = slide[i].getShapes(); + for (int j = 0; j < shape.length; j++) { + int soundRef = getSoundReference(shape[j]); + if(soundRef != -1) { + System.out.println("Slide["+i+"], shape["+j+"], soundRef: "+soundRef); + System.out.println(" " + sounds[soundRef].getSoundName()); + System.out.println(" " + sounds[soundRef].getSoundType()); + } + } + } + } + + /** + * Check if a given shape is associated with a sound. + * @return 0-based reference to a sound in the sound collection + * or -1 if the shape is not associated with a sound + */ + protected static int getSoundReference(Shape shape){ + int soundRef = -1; + //dive into the shape container and search for InteractiveInfoAtom + EscherContainerRecord spContainer = shape.getSpContainer(); + List spchild = spContainer.getChildRecords(); + for (Iterator it = spchild.iterator(); it.hasNext();) { + EscherRecord obj = (EscherRecord) it.next(); + if (obj.getRecordId() == EscherClientDataRecord.RECORD_ID) { + byte[] data = obj.serialize(); + Record[] records = Record.findChildRecords(data, 8, +data.length - 8); + for (int j = 0; j < records.length; j++) { + if (records[j] instanceof InteractiveInfo) { + InteractiveInfoAtom info = ((InteractiveInfo)records[j]).getInteractiveInfoAtom(); + if (info.getAction() == InteractiveInfoAtom.ACTION_MEDIA) { + soundRef = info.getSoundRef(); + } + } + } + } + } + return soundRef; + } +} diff --git a/poi-examples/src/main/java/poi/hslf/examples/TableDemo.java b/poi-examples/src/main/java/poi/hslf/examples/TableDemo.java new file mode 100644 index 0000000000..44935c05ac --- /dev/null +++ b/poi-examples/src/main/java/poi/hslf/examples/TableDemo.java @@ -0,0 +1,127 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hslf.examples; + +import org.apache.poi.hslf.usermodel.SlideShow; +import org.apache.poi.hslf.usermodel.RichTextRun; +import org.apache.poi.hslf.model.*; + +import java.awt.*; +import java.io.FileOutputStream; + +/** + * Demonstrates how to create tables + * + * @author Yegor Kozlov + */ +public final class TableDemo { + + public static void main(String[] args) throws Exception { + + //test data for the first taable + String[][] txt1 = { + {"INPUT FILE", "NUMBER OF RECORDS"}, + {"Item File", "11,559"}, + {"Vendor File", "502"}, + {"Purchase History File - # of PO\u2019s\r(12/01/04 - 05/31/06)", "12,852"}, + {"Purchase History File - # of PO Lines\r(12/01/04 - 05/31/06)", "53,523" }, + {"Total PO History Spend", "$10,172,038"} + }; + + SlideShow ppt = new SlideShow(); + + Slide slide = ppt.createSlide(); + + //six rows, two columns + Table table1 = new Table(6, 2); + for (int i = 0; i < txt1.length; i++) { + for (int j = 0; j < txt1[i].length; j++) { + TableCell cell = table1.getCell(i, j); + cell.setText(txt1[i][j]); + RichTextRun rt = cell.getTextRun().getRichTextRuns()[0]; + rt.setFontName("Arial"); + rt.setFontSize(10); + if(i == 0){ + cell.getFill().setForegroundColor(new Color(227, 227, 227)); + } else { + rt.setBold(true); + } + cell.setVerticalAlignment(TextBox.AnchorMiddle); + cell.setHorizontalAlignment(TextBox.AlignCenter); + } + } + + Line border1 = table1.createBorder(); + border1.setLineColor(Color.black); + border1.setLineWidth(1.0); + table1.setAllBorders(border1); + + table1.setColumnWidth(0, 300); + table1.setColumnWidth(1, 150); + + slide.addShape(table1); + int pgWidth = ppt.getPageSize().width; + table1.moveTo((pgWidth - table1.getAnchor().width)/2, 100); + + //test data for the second taable + String[][] txt2 = { + {"Data Source"}, + {"CAS Internal Metrics - Item Master Summary\r" + + "CAS Internal Metrics - Vendor Summary\r" + + "CAS Internal Metrics - PO History Summary"} + }; + + //two rows, one column + Table table2 = new Table(2, 1); + for (int i = 0; i < txt2.length; i++) { + for (int j = 0; j < txt2[i].length; j++) { + TableCell cell = table2.getCell(i, j); + cell.setText(txt2[i][j]); + RichTextRun rt = cell.getTextRun().getRichTextRuns()[0]; + rt.setFontSize(10); + rt.setFontName("Arial"); + if(i == 0){ + cell.getFill().setForegroundColor(new Color(0, 51, 102)); + rt.setFontColor(Color.white); + rt.setBold(true); + rt.setFontSize(14); + cell.setHorizontalAlignment(TextBox.AlignCenter); + } else { + rt.setBullet(true); + rt.setFontSize(12); + cell.setHorizontalAlignment(TextBox.AlignLeft); + } + cell.setVerticalAlignment(TextBox.AnchorMiddle); + } + } + table2.setColumnWidth(0, 300); + table2.setRowHeight(0, 30); + table2.setRowHeight(1, 70); + + Line border2 = table2.createBorder(); + table2.setOutsideBorders(border2); + + slide.addShape(table2); + table2.moveTo(200, 400); + + FileOutputStream out = new FileOutputStream("hslf-table.ppt"); + ppt.write(out); + out.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/hsmf/examples/Msg2txt.java b/poi-examples/src/main/java/poi/hsmf/examples/Msg2txt.java new file mode 100644 index 0000000000..bf018a3e41 --- /dev/null +++ b/poi-examples/src/main/java/poi/hsmf/examples/Msg2txt.java @@ -0,0 +1,171 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hsmf.examples; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintWriter; + +import org.apache.poi.hsmf.MAPIMessage; +import org.apache.poi.hsmf.datatypes.AttachmentChunks; +import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; + +/** + * Reads one or several Outlook MSG files and for each of them creates + * a text file from available chunks and a directory that contains + * attachments. + * + * @author Bruno Girin + */ +public class Msg2txt { + + /** + * The stem used to create file names for the text file and the directory + * that contains the attachments. + */ + private String fileNameStem; + + /** + * The Outlook MSG file being processed. + */ + private MAPIMessage msg; + + public Msg2txt(String fileName) throws IOException { + fileNameStem = fileName; + if(fileNameStem.endsWith(".msg") || fileNameStem.endsWith(".MSG")) { + fileNameStem = fileNameStem.substring(0, fileNameStem.length() - 4); + } + msg = new MAPIMessage(fileName); + } + + /** + * Processes the message. + * + * @throws IOException if an exception occurs while writing the message out + */ + public void processMessage() throws IOException { + String txtFileName = fileNameStem + ".txt"; + String attDirName = fileNameStem + "-att"; + PrintWriter txtOut = null; + try { + txtOut = new PrintWriter(txtFileName); + try { + String displayFrom = msg.getDisplayFrom(); + txtOut.println("From: "+displayFrom); + } catch (ChunkNotFoundException e) { + // ignore + } + try { + String displayTo = msg.getDisplayTo(); + txtOut.println("To: "+displayTo); + } catch (ChunkNotFoundException e) { + // ignore + } + try { + String displayCC = msg.getDisplayCC(); + txtOut.println("CC: "+displayCC); + } catch (ChunkNotFoundException e) { + // ignore + } + try { + String displayBCC = msg.getDisplayBCC(); + txtOut.println("BCC: "+displayBCC); + } catch (ChunkNotFoundException e) { + // ignore + } + try { + String subject = msg.getSubject(); + txtOut.println("Subject: "+subject); + } catch (ChunkNotFoundException e) { + // ignore + } + try { + String body = msg.getTextBody(); + txtOut.println(body); + } catch (ChunkNotFoundException e) { + System.err.println("No message body"); + } + + AttachmentChunks[] attachments = msg.getAttachmentFiles(); + if(attachments.length > 0) { + File d = new File(attDirName); + if(d.mkdir()) { + for(AttachmentChunks attachment : attachments) { + processAttachment(attachment, d); + } + } else { + System.err.println("Can't create directory "+attDirName); + } + } + } finally { + if(txtOut != null) { + txtOut.close(); + } + } + } + + /** + * Processes a single attachment: reads it from the Outlook MSG file and + * writes it to disk as an individual file. + * + * @param attachment the chunk group describing the attachment + * @param dir the directory in which to write the attachment file + * @throws IOException when any of the file operations fails + */ + public void processAttachment(AttachmentChunks attachment, + File dir) throws IOException { + String fileName = attachment.attachFileName.toString(); + if(attachment.attachLongFileName != null) { + fileName = attachment.attachLongFileName.toString(); + } + + File f = new File(dir, fileName); + OutputStream fileOut = null; + try { + fileOut = new FileOutputStream(f); + fileOut.write(attachment.attachData.getValue()); + } finally { + if(fileOut != null) { + fileOut.close(); + } + } + } + + /** + * Processes the list of arguments as a list of names of Outlook MSG files. + * + * @param args the list of MSG files to process + */ + public static void main(String[] args) { + if(args.length <= 0) { + System.err.println("No files names provided"); + } else { + for(int i = 0; i < args.length; i++) { + try { + Msg2txt processor = new Msg2txt(args[i]); + processor.processMessage(); + } catch (IOException e) { + System.err.println("Could not process "+args[i]+": "+e); + } + } + } + } + +} diff --git a/poi-examples/src/main/java/poi/hssf/eventusermodel/examples/XLS2CSVmra.java b/poi-examples/src/main/java/poi/hssf/eventusermodel/examples/XLS2CSVmra.java new file mode 100644 index 0000000000..4c1119137e --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/eventusermodel/examples/XLS2CSVmra.java @@ -0,0 +1,327 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.eventusermodel.examples; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; + +import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener; +import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; +import org.apache.poi.hssf.eventusermodel.HSSFListener; +import org.apache.poi.hssf.eventusermodel.HSSFRequest; +import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener; +import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener; +import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; +import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; +import org.apache.poi.hssf.model.HSSFFormulaParser; +import org.apache.poi.hssf.record.BOFRecord; +import org.apache.poi.hssf.record.BlankRecord; +import org.apache.poi.hssf.record.BoolErrRecord; +import org.apache.poi.hssf.record.BoundSheetRecord; +import org.apache.poi.hssf.record.FormulaRecord; +import org.apache.poi.hssf.record.LabelRecord; +import org.apache.poi.hssf.record.LabelSSTRecord; +import org.apache.poi.hssf.record.NoteRecord; +import org.apache.poi.hssf.record.NumberRecord; +import org.apache.poi.hssf.record.RKRecord; +import org.apache.poi.hssf.record.Record; +import org.apache.poi.hssf.record.SSTRecord; +import org.apache.poi.hssf.record.StringRecord; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + +/** + * A XLS -> CSV processor, that uses the MissingRecordAware + * EventModel code to ensure it outputs all columns and rows. + * @author Nick Burch + */ +public class XLS2CSVmra implements HSSFListener { + private int minColumns; + private POIFSFileSystem fs; + private PrintStream output; + + private int lastRowNumber; + private int lastColumnNumber; + + /** Should we output the formula, or the value it has? */ + private boolean outputFormulaValues = true; + + /** For parsing Formulas */ + private SheetRecordCollectingListener workbookBuildingListener; + private HSSFWorkbook stubWorkbook; + + // Records we pick up as we process + private SSTRecord sstRecord; + private FormatTrackingHSSFListener formatListener; + + /** So we known which sheet we're on */ + private int sheetIndex = -1; + private BoundSheetRecord[] orderedBSRs; + private ArrayList boundSheetRecords = new ArrayList(); + + // For handling formulas with string results + private int nextRow; + private int nextColumn; + private boolean outputNextStringRecord; + + /** + * Creates a new XLS -> CSV converter + * @param fs The POIFSFileSystem to process + * @param output The PrintStream to output the CSV to + * @param minColumns The minimum number of columns to output, or -1 for no minimum + */ + public XLS2CSVmra(POIFSFileSystem fs, PrintStream output, int minColumns) { + this.fs = fs; + this.output = output; + this.minColumns = minColumns; + } + + /** + * Creates a new XLS -> CSV converter + * @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 XLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException { + this( + new POIFSFileSystem(new FileInputStream(filename)), + System.out, minColumns + ); + } + + /** + * Initiates the processing of the XLS file to CSV + */ + public void process() throws IOException { + MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this); + formatListener = new FormatTrackingHSSFListener(listener); + + HSSFEventFactory factory = new HSSFEventFactory(); + HSSFRequest request = new HSSFRequest(); + + if(outputFormulaValues) { + request.addListenerForAllRecords(formatListener); + } else { + workbookBuildingListener = new SheetRecordCollectingListener(formatListener); + request.addListenerForAllRecords(workbookBuildingListener); + } + + factory.processWorkbookEvents(request, fs); + } + + /** + * Main HSSFListener method, processes events, and outputs the + * CSV as the file is processed. + */ + public void processRecord(Record record) { + int thisRow = -1; + int thisColumn = -1; + String thisStr = null; + + switch (record.getSid()) + { + case BoundSheetRecord.sid: + boundSheetRecords.add(record); + break; + case BOFRecord.sid: + BOFRecord br = (BOFRecord)record; + if(br.getType() == BOFRecord.TYPE_WORKSHEET) { + // Create sub workbook if required + if(workbookBuildingListener != null && stubWorkbook == null) { + stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook(); + } + + // Output the worksheet name + // Works by ordering the BSRs by the location of + // their BOFRecords, and then knowing that we + // process BOFRecords in byte offset order + sheetIndex++; + if(orderedBSRs == null) { + orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords); + } + output.println(); + output.println( + orderedBSRs[sheetIndex].getSheetname() + + " [" + (sheetIndex+1) + "]:" + ); + } + break; + + case SSTRecord.sid: + sstRecord = (SSTRecord) record; + break; + + case BlankRecord.sid: + BlankRecord brec = (BlankRecord) record; + + thisRow = brec.getRow(); + thisColumn = brec.getColumn(); + thisStr = ""; + break; + case BoolErrRecord.sid: + BoolErrRecord berec = (BoolErrRecord) record; + + thisRow = berec.getRow(); + thisColumn = berec.getColumn(); + thisStr = ""; + break; + + case FormulaRecord.sid: + FormulaRecord frec = (FormulaRecord) record; + + thisRow = frec.getRow(); + thisColumn = frec.getColumn(); + + if(outputFormulaValues) { + if(Double.isNaN( frec.getValue() )) { + // Formula result is a string + // This is stored in the next record + outputNextStringRecord = true; + nextRow = frec.getRow(); + nextColumn = frec.getColumn(); + } else { + thisStr = formatListener.formatNumberDateCell(frec); + } + } else { + thisStr = '"' + + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"'; + } + break; + case StringRecord.sid: + if(outputNextStringRecord) { + // String for formula + StringRecord srec = (StringRecord)record; + thisStr = srec.getString(); + thisRow = nextRow; + thisColumn = nextColumn; + outputNextStringRecord = false; + } + break; + + case LabelRecord.sid: + LabelRecord lrec = (LabelRecord) record; + + thisRow = lrec.getRow(); + thisColumn = lrec.getColumn(); + thisStr = '"' + lrec.getValue() + '"'; + break; + case LabelSSTRecord.sid: + LabelSSTRecord lsrec = (LabelSSTRecord) record; + + thisRow = lsrec.getRow(); + thisColumn = lsrec.getColumn(); + if(sstRecord == null) { + thisStr = '"' + "(No SST Record, can't identify string)" + '"'; + } else { + thisStr = '"' + sstRecord.getString(lsrec.getSSTIndex()).toString() + '"'; + } + break; + case NoteRecord.sid: + NoteRecord nrec = (NoteRecord) record; + + thisRow = nrec.getRow(); + thisColumn = nrec.getColumn(); + // TODO: Find object to match nrec.getShapeId() + thisStr = '"' + "(TODO)" + '"'; + break; + case NumberRecord.sid: + NumberRecord numrec = (NumberRecord) record; + + thisRow = numrec.getRow(); + thisColumn = numrec.getColumn(); + + // Format + thisStr = formatListener.formatNumberDateCell(numrec); + break; + case RKRecord.sid: + RKRecord rkrec = (RKRecord) record; + + thisRow = rkrec.getRow(); + thisColumn = rkrec.getColumn(); + thisStr = '"' + "(TODO)" + '"'; + break; + default: + break; + } + + // Handle new row + if(thisRow != -1 && thisRow != lastRowNumber) { + lastColumnNumber = -1; + } + + // Handle missing column + if(record instanceof MissingCellDummyRecord) { + MissingCellDummyRecord mc = (MissingCellDummyRecord)record; + thisRow = mc.getRow(); + thisColumn = mc.getColumn(); + thisStr = ""; + } + + // If we got something to print out, do so + if(thisStr != null) { + if(thisColumn > 0) { + output.print(','); + } + output.print(thisStr); + } + + // Update column and row count + if(thisRow > -1) + lastRowNumber = thisRow; + if(thisColumn > -1) + lastColumnNumber = thisColumn; + + // Handle end of row + if(record instanceof LastCellOfRowDummyRecord) { + // Print out any missing commas if needed + if(minColumns > 0) { + // Columns are 0 based + if(lastColumnNumber == -1) { lastColumnNumber = 0; } + for(int i=lastColumnNumber; i<(minColumns); i++) { + output.print(','); + } + } + + // We're onto a new row + lastColumnNumber = -1; + + // End the row + output.println(); + } + } + + public static void main(String[] args) throws Exception { + if(args.length < 1) { + System.err.println("Use:"); + System.err.println(" XLS2CSVmra [min columns]"); + System.exit(1); + } + + int minColumns = -1; + if(args.length >= 2) { + minColumns = Integer.parseInt(args[1]); + } + + XLS2CSVmra xls2csv = new XLS2CSVmra(args[0], minColumns); + xls2csv.process(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/AddDimensionedImage.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/AddDimensionedImage.java new file mode 100644 index 0000000000..6482f186c0 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/AddDimensionedImage.java @@ -0,0 +1,946 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.hssf.usermodel.examples; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFClientAnchor; +import org.apache.poi.hssf.usermodel.HSSFPatriarch; +import org.apache.poi.hssf.util.CellReference; + + +/** + * Demonstrates how to add an image to a worksheet and set that image's size + * to a specific number of milimetres irrespective of the width of the columns + * or height of the rows. Overridden methods are provided so that the location + * of the image - the cells row and column co-ordinates that define the top + * left hand corners of the image - can be identified either in the familiar + * Excel manner - A1 for instance - or using POI's methodolody of a column and + * row index where 0, 0 would indicate cell A1. + * + * The best way to make use of these techniques is to delay adding the image to + * the sheet until all other work has been completed. That way, the sizes of + * all rows and columns will have been adjusted - assuming that step was + * necessary. Even though the anchors type is set to prevent the image moving + * or re-sizing, this setting does not have any effect until the sheet is being + * viewed using the Excel application. + * + * The key to the process is the HSSFClientAnchor class. It accepts eight + * parameters that define, in order; + * + * * How far - in terms of co-ordinate position - the image should be inset + * from the left hand border of a cell. + * * How far - in terms of co-ordinate positions - the image should be inset + * from the from the top of the cell. + * * How far - in terms of co-ordinate positions - the right hand edge of + * the image should protrude into a cell (measured from the cell's left hand + * edge to the image's right hand edge). + * * How far - in terms of co-ordinate positions - the bottm edge of the + * image should protrude into a row (measured from the cell's top edge to + * the image's bottom edge). + * * The index of the column that contains the cell whose top left hand + * corner should be aligned with the top left hand corner of the image. + * * The index of the row that contains the cell whose top left hand corner + * should be aligned with the image's top left hand corner. + * * The index of the column that contains the cell whose top left hand + * corner should be aligned with the image's bottom right hand corner + * * The index number of the row that contains the cell whose top left + * hand corner should be aligned with the images bottom right hand corner. + * + * It can be used to add an image into cell A1, for example, in the following + * manner; + * + * HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, + * (short)0, 0, (short)1, 1); + * + * The final four parameters determine that the top left hand corner should be + * aligned with the top left hand corner of cell A1 and it's bottom right + * hand corner with the top left hand corner of cell B2. Think of the image as + * being stretched so that it's top left hand corner is aligned with the top + * left hand corner of cell A1 and it's bottom right hand corner is aligned with + * the top left hand corner of cell B1. Interestingly, this would also produce + * the same results; + * + * anchor = new HSSFClientAnchor(0, 0, 1023, 255, + * (short)0, 0, (short)0, 0); + * + * Note that the final four parameters all contain the same value and seem to + * indicate that the images top left hand corner is aligned with the top left + * hand corner of cell A1 and that it's bottom right hand corner is also + * aligned with the top left hand corner of cell A1. Yet, running this code + * would see the image fully occupying cell A1. That is the result of the + * values passed to parameters three and four; these I have referred to as + * determing the images co-ordinates within the cell. They indicate that the + * image should occupy - in order - the full width of the column and the full + * height of the row. + * + * The co-ordinate values shown are the maxima; and they are independent of + * row height/column width and of the font used. Passing 255 will always result + * in the image occupying the full height of the row and passing 1023 will + * always result in the image occupying the full width of the column. They help + * in situations where an image is larger than a column/row and must overlap + * into the next column/row. Using them does mean, however, that it is often + * necessary to perform conversions between Excel's characters units, points, + * pixels and millimetres in order to establish how many rows/columns an image + * should occupy and just what the varous insets ought to be. + * + * Note that the first two parameters of the HSSFClientAchor classes constructor + * are not made use of in the code that follows. It would be fairly trivial + * however to extend these example further and provide methods that would centre + * an image within a cell or allow the user to specify that a plain border a + * fixed number of millimetres wide should wrap around the image. Those first + * two parameters would make this sort of functionality perfectly possible. + * + * Owing to the various conversions used, the actual size of the image may vary + * from that required; testing has so far found this to be in the region of + * plus or minus two millimetres. Most likely by modifying the way the + * calculations are performed - possibly using double(s) throughout and + * rounding the values at the correct point - it is likely that these errors + * could be reduced or removed. + * + * A note concerning Excels' image resizing behaviour. The HSSFClientAnchor + * class contains a method called setAnchorType(int) which can be used to + * determine how Excel will resize an image in reponse to the user increasing + * or decreasing the dimensions of the cell containing the image. There are + * three values that can be passed to this method; 0 = To move and size the + * image with the cell, 2 = To move but don't size the image with the cell, + * 3 = To prevent the image from moving or being resized along with the cell. If + * an image is inserted using this class and placed into a single cell then if + * the setAnchorType(int) method is called and a value of either 0 or 2 passed + * to it, the resultant resizing behaviour may be a surprise. The image will not + * grow in size of the column is made wider or the row higher but it will shrink + * if the columns width or rows height are reduced. + * + * @author Mark Beardsley [msb at apache.org] + * @version 1.00 5th August 2009. + */ +public class AddDimensionedImage { + + // Four constants that determine how - and indeed whether - the rows + // and columns an image may overlie should be expanded to accomodate that + // image. + // Passing EXPAND_ROW will result in the height of a row being increased + // to accomodate the image if it is not already larger. The image will + // be layed across one or more columns. + // Passing EXPAND_COLUMN will result in the width of the column being + // increased to accomodate the image if it is not already larger. The image + // will be layed across one or many rows. + // Passing EXPAND_ROW_AND_COLUMN will result in the height of the row + // bing increased along with the width of the column to accomdate the + // image if either is not already larger. + // Passing OVERLAY_ROW_AND_COLUMN will result in the image being layed + // over one or more rows and columns. No row or column will be resized, + // instead, code will determine how many rows and columns the image should + // overlie. + public static final int EXPAND_ROW = 1; + public static final int EXPAND_COLUMN = 2; + public static final int EXPAND_ROW_AND_COLUMN = 3; + public static final int OVERLAY_ROW_AND_COLUMN = 7; + + /** + * Add an image to a worksheet. + * + * @param cellNumber A String that contains the location of the cell whose + * top left hand corner should be aligned with the top + * left hand corner of the image; for example "A1", "A2" + * etc. This is to support the familiar Excel syntax. + * Whilst images are are not actually inserted into cells + * this provides a convenient method of indicating where + * the image should be positioned on the sheet. + * @param sheet A reference to the sheet that contains the cell referenced + * above. + * @param imageFile A String that encapsulates the name of and path to + * the image that is to be 'inserted into' the sheet. + * @param reqImageWidthMM A primitive double that contains the required + * width of the image in millimetres. + * @param reqImageHeightMM A primitive double that contains the required + * height of the image in millimetres. + * @param resizeBehaviour A primitive int whose value will determine how + * the code should react if the image is larger than + * the cell referenced by the cellNumber parameter. + * Four constants are provided to determine what + * should happen; + * AddDimensionedImage.EXPAND_ROW + * AddDimensionedImage.EXPAND_COLUMN + * AddDimensionedImage.EXPAND_ROW_AND_COLUMN + * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN + * @throws java.io.FileNotFoundException If the file containing the image + * cannot be located. + * @throws java.io.IOException If a problem occurs whilst reading the file + * of image data. + * @throws java.lang.IllegalArgumentException If an invalid value is passed + * to the resizeBehaviour + * parameter. + */ + public void addImageToSheet(String cellNumber, HSSFSheet sheet, + String imageFile, double reqImageWidthMM, double reqImageHeightMM, + int resizeBehaviour) throws IOException, IllegalArgumentException { + // Convert the String into column and row indices then chain the + // call to the overridden addImageToSheet() method. + CellReference cellRef = new CellReference(cellNumber); + this.addImageToSheet(cellRef.getCol(), cellRef.getRow(), sheet, + imageFile, reqImageWidthMM, reqImageHeightMM,resizeBehaviour); + } + + /** + * Add an image to a worksheet. + * + * @param colNumber A primitive int that contains the index number of a + * column on the worksheet; POI column indices are zero + * based. Together with the rowNumber parameter's value, + * this parameter identifies a cell on the worksheet. The + * image's top left hand corner will be aligned with the + * top left hand corner of this cell. + * @param rowNumber A primtive int that contains the index number of a row + * on the worksheet; POI row indices are zero based. + * Together with the rowNumber parameter's value, this + * parameter identifies a cell on the worksheet. The + * image's top left hand corner will be aligned with the + * top left hand corner of this cell. + * @param sheet A reference to the sheet that contains the cell identified + * by the two parameters above. + * @param imageFile A String that encapsulates the name of and path to + * the image that is to be 'inserted into' the sheet. + * @param reqImageWidthMM A primitive double that contains the required + * width of the image in millimetres. + * @param reqImageHeightMM A primitive double that contains the required + * height of the image in millimetres. + * @param resizeBehaviour A primitive int whose value will determine how + * the code should react if the image is larger than + * the cell referenced by the colNumber and + * rowNumber parameters. Four constants are provided + * to determine what should happen; + * AddDimensionedImage.EXPAND_ROW + * AddDimensionedImage.EXPAND_COLUMN + * AddDimensionedImage.EXPAND_ROW_AND_COLUMN + * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN + * @throws java.io.FileNotFoundException If the file containing the image + * cannot be located. + * @throws java.io.IOException If a problem occurs whilst reading the file + * of image data. + * @throws java.lang.IllegalArgumentException If an invalid value is passed + * to the resizeBehaviour + * parameter. + */ + private void addImageToSheet(int colNumber, int rowNumber, HSSFSheet sheet, + String imageFile, double reqImageWidthMM, double reqImageHeightMM, + int resizeBehaviour) throws FileNotFoundException, IOException, + IllegalArgumentException { + HSSFRow row = null; + HSSFClientAnchor anchor = null; + HSSFPatriarch patriarch = null; + ClientAnchorDetail rowClientAnchorDetail = null; + ClientAnchorDetail colClientAnchorDetail = null; + + // Validate the resizeBehaviour parameter. + if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) && + (resizeBehaviour != AddDimensionedImage.EXPAND_ROW) && + (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN) && + (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) { + throw new IllegalArgumentException("Invalid value passed to the " + + "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()"); + } + + // Call methods to calculate how the image and sheet should be + // manipulated to accomodate the image; columns and then rows. + colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, + reqImageWidthMM, resizeBehaviour); + rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, + reqImageHeightMM, resizeBehaviour); + + // Having determined if and how to resize the rows, columns and/or the + // image, create the HSSFClientAnchor object to position the image on + // the worksheet. Note how the two ClientAnchorDetail records are + // interrogated to recover the row/column co-ordinates and any insets. + // The first two parameters are not used currently but could be if the + // need arose to extend the functionality of this code by adding the + // ability to specify that a clear 'border' be placed around the image. + anchor = new HSSFClientAnchor(0, + 0, + colClientAnchorDetail.getInset(), + rowClientAnchorDetail.getInset(), + (short)colClientAnchorDetail.getFromIndex(), + rowClientAnchorDetail.getFromIndex(), + (short)colClientAnchorDetail.getToIndex(), + rowClientAnchorDetail.getToIndex()); + + // For now, set the anchor type to do not move or resize the + // image as the size of the row/column is adjusted. This could easilly + // become another parameter passed to the method. + //anchor.setAnchorType(HSSFClientAnchor.DONT_MOVE_AND_RESIZE); + anchor.setAnchorType(HSSFClientAnchor.MOVE_AND_RESIZE); + + // Now, add the picture to the workbook. Note that the type is assumed + // to be a JPEG/JPG, this could easily (and should) be parameterised + // however. + //int index = sheet.getWorkbook().addPicture(this.imageToBytes(imageFile), + // HSSFWorkbook.PICTURE_TYPE_JPEG); + int index = sheet.getWorkbook().addPicture(this.imageToBytes(imageFile), HSSFWorkbook.PICTURE_TYPE_PNG); + + // Get the drawing patriarch and create the picture. + patriarch = sheet.createDrawingPatriarch(); + patriarch.createPicture(anchor, index); + } + + /** + * Determines whether the sheets columns should be re-sized to accomodate + * the image, adjusts the columns width if necessary and creates then + * returns a ClientAnchorDetail object that facilitates construction of + * an HSSFClientAnchor that will fix the image on the sheet and establish + * it's size. + * + * @param sheet A reference to the sheet that will 'contain' the image. + * @param colNumber A primtive int that contains the index number of a + * column on the sheet. + * @param reqImageWidthMM A primtive double that contains the required + * width of the image in millimetres + * @param resizeBehaviour A primitve int whose value will indicate how the + * width of the column should be adjusted if the + * required width of the image is greater than the + * width of the column. + * @return An instance of the ClientAnchorDetail class that will contain + * the index number of the column containing the cell whose top + * left hand corner also defines the top left hand corner of the + * image, the index number column containing the cell whose top + * left hand corner also defines the bottom right hand corner of + * the image and an inset that determines how far the right hand + * edge of the image can protrude into the next column - expressed + * as a specific number of co-ordinate positions. + */ + private ClientAnchorDetail fitImageToColumns(HSSFSheet sheet, int colNumber, + double reqImageWidthMM, int resizeBehaviour) { + + double colWidthMM = 0.0D; + double colCoordinatesPerMM = 0.0D; + int pictureWidthCoordinates = 0; + ClientAnchorDetail colClientAnchorDetail = null; + + // Get the colum's width in millimetres + colWidthMM = ConvertImageUnits.widthUnits2Millimetres( + (short)sheet.getColumnWidth(colNumber)); + + // Check that the column's width will accomodate the image at the + // required dimension. If the width of the column is LESS than the + // required width of the image, decide how the application should + // respond - resize the column or overlay the image across one or more + // columns. + if(colWidthMM < reqImageWidthMM) { + + // Should the column's width simply be expanded? + if((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN) || + (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { + // Set the width of the column by converting the required image + // width from millimetres into Excel's column width units. + sheet.setColumnWidth(colNumber, + ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM)); + // To make the image occupy the full width of the column, convert + // the required width of the image into co-ordinates. This value + // will become the inset for the ClientAnchorDetail class that + // is then instantiated. + colWidthMM = reqImageWidthMM; + colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / + colWidthMM; + pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); + colClientAnchorDetail = new ClientAnchorDetail(colNumber, + colNumber, pictureWidthCoordinates); + } + // If the user has chosen to overlay both rows and columns or just + // to expand ONLY the size of the rows, then calculate how to lay + // the image out across one or more columns. + else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || + (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) { + colClientAnchorDetail = this.calculateColumnLocation(sheet, + colNumber, reqImageWidthMM); + } + } + // If the column is wider than the image. + else { + // Mow many co-ordinate positions are there per millimetre? + colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / + colWidthMM; + // Given the width of the image, what should be it's co-ordinate? + pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); + colClientAnchorDetail = new ClientAnchorDetail(colNumber, + colNumber, pictureWidthCoordinates); + } + return(colClientAnchorDetail); + } + + /** + * Determines whether the sheet's row should be re-sized to accomodate + * the image, adjusts the rows height if necessary and creates then + * returns a ClientAnchorDetail object that facilitates construction of + * an HSSFClientAnchor that will fix the image on the sheet and establish + * it's size. + * + * @param sheet A reference to the sheet that will 'contain' the image. + * @param rowNumber A primtive int that contains the index number of a + * row on the sheet. + * @param reqImageHeightMM A primtive double that contains the required + * height of the image in millimetres + * @param resizeBehaviour A primitve int whose value will indicate how the + * height of the row should be adjusted if the + * required height of the image is greater than the + * height of the row. + * @return An instance of the ClientAnchorDetail class that will contain + * the index number of the row containing the cell whose top + * left hand corner also defines the top left hand corner of the + * image, the index number of the row containing the cell whose + * top left hand corner also defines the bottom right hand + * corner of the image and an inset that determines how far the + * bottom edge of the image can protrude into the next (lower) + * row - expressed as a specific number of co-ordinate positions. + */ + private ClientAnchorDetail fitImageToRows(HSSFSheet sheet, int rowNumber, + double reqImageHeightMM, int resizeBehaviour) { + HSSFRow row = null; + double rowHeightMM = 0.0D; + double rowCoordinatesPerMM = 0.0D; + int pictureHeightCoordinates = 0; + ClientAnchorDetail rowClientAnchorDetail = null; + + // Get the row and it's height + row = sheet.getRow(rowNumber); + if(row == null) { + // Create row if it does not exist. + row = sheet.createRow(rowNumber); + } + + // Get the row's height in millimetres + rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE; + + // Check that the row's height will accomodate the image at the required + // dimensions. If the height of the row is LESS than the required height + // of the image, decide how the application should respond - resize the + // row or overlay the image across a series of rows. + if(rowHeightMM < reqImageHeightMM) { + if((resizeBehaviour == AddDimensionedImage.EXPAND_ROW) || + (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { + row.setHeightInPoints((float)(reqImageHeightMM * + ConvertImageUnits.POINTS_PER_MILLIMETRE)); + rowHeightMM = reqImageHeightMM; + rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / + rowHeightMM; + pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); + rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, + rowNumber, pictureHeightCoordinates); + } + // If the user has chosen to overlay both rows and columns or just + // to expand ONLY the size of the columns, then calculate how to lay + // the image out ver one or more rows. + else if((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || + (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) { + rowClientAnchorDetail = this.calculateRowLocation(sheet, + rowNumber, reqImageHeightMM); + } + } + // Else, if the image is smaller than the space available + else { + rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / + rowHeightMM; + pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); + rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, + rowNumber, pictureHeightCoordinates); + } + return(rowClientAnchorDetail); + } + + /** + * If the image is to overlie more than one column, calculations need to be + * performed to determine how many columns and whether the image will + * overlie just a part of one column in order to be presented at the + * required size. + * + * @param sheet The sheet that will 'contain' the image. + * @param startingColumn A primitive int whose value is the index of the + * column that contains the cell whose top left hand + * corner should be aligned with the top left hand + * corner of the image. + * @param reqImageWidthMM A primitive double whose value will indicate the + * required width of the image in millimetres. + * @return An instance of the ClientAnchorDetail class that will contain + * the index number of the column containing the cell whose top + * left hand corner also defines the top left hand corner of the + * image, the index number column containing the cell whose top + * left hand corner also defines the bottom right hand corner of + * the image and an inset that determines how far the right hand + * edge of the image can protrude into the next column - expressed + * as a specific number of co-ordinate positions. + */ + private ClientAnchorDetail calculateColumnLocation(HSSFSheet sheet, + int startingColumn, + double reqImageWidthMM) { + ClientAnchorDetail anchorDetail = null; + double totalWidthMM = 0.0D; + double colWidthMM = 0.0D; + double overlapMM = 0.0D; + double coordinatePositionsPerMM = 0.0D; + int toColumn = startingColumn; + int inset = 0; + + // Calculate how many columns the image will have to + // span in order to be presented at the required size. + while(totalWidthMM < reqImageWidthMM) { + colWidthMM = ConvertImageUnits.widthUnits2Millimetres( + (short)(sheet.getColumnWidth(toColumn))); + // Note use of the cell border width constant. Testing with an image + // declared to fit exactly into one column demonstrated that it's + // width was greater than the width of the column the POI returned. + // Further, this difference was a constant value that I am assuming + // related to the cell's borders. Either way, that difference needs + // to be allowed for in this calculation. + totalWidthMM += (colWidthMM + ConvertImageUnits.CELL_BORDER_WIDTH_MILLIMETRES); + toColumn++; + } + // De-crement by one the last column value. + toColumn--; + // Highly unlikely that this will be true but, if the width of a series + // of columns is exactly equal to the required width of the image, then + // simply build a ClientAnchorDetail object with an inset equal to the + // total number of co-ordinate positions available in a column, a + // from column co-ordinate (top left hand corner) equal to the value + // of the startingColumn parameter and a to column co-ordinate equal + // to the toColumn variable. + // + // Convert both values to ints to perform the test. + if((int)totalWidthMM == (int)reqImageWidthMM) { + // A problem could occur if the image is sized to fit into one or + // more columns. If that occurs, the value in the toColumn variable + // will be in error. To overcome this, there are two options, to + // ibcrement the toColumn variable's value by one or to pass the + // total number of co-ordinate positions to the third paramater + // of the ClientAnchorDetail constructor. For no sepcific reason, + // the latter option is used below. + anchorDetail = new ClientAnchorDetail(startingColumn, + toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS); + } + // In this case, the image will overlap part of another column and it is + // necessary to calculate just how much - this will become the inset + // for the ClientAnchorDetail object. + else { + // Firstly, claculate how much of the image should overlap into + // the next column. + overlapMM = reqImageWidthMM - (totalWidthMM - colWidthMM); + + // When the required size is very close indded to the column size, + // the calcaulation above can produce a negative value. To prevent + // problems occuring in later caculations, this is simply removed + // be setting the overlapMM value to zero. + if(overlapMM < 0) { + overlapMM = 0.0D; + } + + // Next, from the columns width, calculate how many co-ordinate + // positons there are per millimetre + coordinatePositionsPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / + colWidthMM; + // From this figure, determine how many co-ordinat positions to + // inset the left hand or bottom edge of the image. + inset = (int)(coordinatePositionsPerMM * overlapMM); + + // Now create the ClientAnchorDetail object, setting the from and to + // columns and the inset. + anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, inset); + } + return(anchorDetail); + } + + /** + * If the image is to overlie more than one rows, calculations need to be + * performed to determine how many rows and whether the image will + * overlie just a part of one row in order to be presented at the + * required size. + * + * @param sheet The sheet that will 'contain' the image. + * @param startingRow A primitive int whose value is the index of the row + * that contains the cell whose top left hand corner + * should be aligned with the top left hand corner of + * the image. + * @param reqImageHeightMM A primitive double whose value will indicate the + * required height of the image in millimetres. + * @return An instance of the ClientAnchorDetail class that will contain + * the index number of the row containing the cell whose top + * left hand corner also defines the top left hand corner of the + * image, the index number of the row containing the cell whose top + * left hand corner also defines the bottom right hand corner of + * the image and an inset that determines how far the bottom edge + * can protrude into the next (lower) row - expressed as a specific + * number of co-ordinate positions. + */ + private ClientAnchorDetail calculateRowLocation(HSSFSheet sheet, + int startingRow, double reqImageHeightMM) { + ClientAnchorDetail clientAnchorDetail = null; + HSSFRow row = null; + double rowHeightMM = 0.0D; + double totalRowHeightMM = 0.0D; + double overlapMM = 0.0D; + double rowCoordinatesPerMM = 0.0D; + int toRow = startingRow; + int inset = 0; + + // Step through the rows in the sheet and accumulate a total of their + // heights. + while(totalRowHeightMM < reqImageHeightMM) { + row = sheet.getRow(toRow); + // Note, if the row does not already exist on the sheet then create + // it here. + if(row == null) { + row = sheet.createRow(toRow); + } + // Get the row's height in millimetres and add to the running total. + rowHeightMM = row.getHeightInPoints() / + ConvertImageUnits.POINTS_PER_MILLIMETRE; + totalRowHeightMM += rowHeightMM; + toRow++; + } + // Owing to the way the loop above works, the rowNumber will have been + // incremented one row too far. Undo that here. + toRow--; + // Check to see whether the image should occupy an exact number of + // rows. If so, build the ClientAnchorDetail record to point + // to those rows and with an inset of the total number of co-ordinate + // position in the row. + // + // To overcome problems that can occur with comparing double values for + // equality, cast both to int(s) to truncate the value; VERY crude and + // I do not really like it!! + if((int)totalRowHeightMM == (int)reqImageHeightMM) { + clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, + ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS); + } + else { + // Calculate how far the image will project into the next row. Note + // that the height of the last row assessed is subtracted from the + // total height of all rows assessed so far. + overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM); + + // To prevent an exception being thrown when the required width of + // the image is very close indeed to the column size. + if(overlapMM < 0) { + overlapMM = 0.0D; + } + + rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / + rowHeightMM; + inset = (int)(overlapMM * rowCoordinatesPerMM); + clientAnchorDetail = new ClientAnchorDetail(startingRow, + toRow, inset); + } + return(clientAnchorDetail); + } + + /** + * Loads - reads in and converts into an array of byte(s) - an image from + * a named file. + * + * Note: this method should be modified so that the type of the image may + * also be passed to it. Currently, it assumes that all images are + * JPG/JPEG(s). + * + * @param imageFilename A String that encapsulates the path to and name + * of the file that contains the image which is to be + * 'loaded'. + * @return An array of type byte that contains the raw data of the named + * image. + * @throws java.io.FileNotFoundException Thrown if it was not possible to + * open the specified file. + * @throws java.io.IOException Thrown if reading the file failed or was + * interrupted. + */ + private byte[] imageToBytes(String imageFilename) throws IOException { + File imageFile = null; + FileInputStream fis = null; + ByteArrayOutputStream bos = null; + int read = 0; + try { + imageFile = new File(imageFilename); + fis = new FileInputStream(imageFile); + bos = new ByteArrayOutputStream(); + while((read = fis.read()) != -1) { + bos.write(read); + } + return(bos.toByteArray()); + } + finally { + if(fis != null) { + try { + fis.close(); + fis = null; + } + catch(IOException ioEx) { + // Nothing to do here + } + } + } + } + + /** + * The main entry point to the program. It contains code that demonstrates + * one way to use the program. + * + * Note, the code is not restricted to use on new workbooks only. If an + * image is to be inserted into an existing workbook. just open that + * workbook, gat a reference to a sheet and pass that; + * + * AddDimensionedImage addImage = new AddDimensionedImage(); + * + * File file = new File("....... Existing Workbook ......."); + * FileInputStream fis = new FileInputStream(file); + * HSSFWorkbook workbook = new HSSFWorkbook(fis); + * HSSFSheet sheet = workbook.getSheetAt(0); + * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20, + * AddDimensionedImage.EXPAND.ROW); + * + * @param args the command line arguments + */ + public static void main(String[] args) { + String imageFile = null; + String outputFile = null; + FileInputStream fis = null; + FileOutputStream fos = null; + HSSFWorkbook workbook = null; + HSSFSheet sheet = null; + try { + if(args.length < 2){ + System.err.println("Usage: AddDimensionedImage imageFile outputFile"); + return; + } + imageFile = args[0]; + outputFile = args[1]; + + workbook = new HSSFWorkbook(); + sheet = workbook.createSheet("Picture Test"); + new AddDimensionedImage().addImageToSheet("A1", sheet, + imageFile, 125, 125, + AddDimensionedImage.EXPAND_ROW_AND_COLUMN); + fos = new FileOutputStream(outputFile); + workbook.write(fos); + } + catch(FileNotFoundException fnfEx) { + System.out.println("Caught an: " + fnfEx.getClass().getName()); + System.out.println("Message: " + fnfEx.getMessage()); + System.out.println("Stacktrace follows..........."); + fnfEx.printStackTrace(System.out); + } + catch(IOException ioEx) { + System.out.println("Caught an: " + ioEx.getClass().getName()); + System.out.println("Message: " + ioEx.getMessage()); + System.out.println("Stacktrace follows..........."); + ioEx.printStackTrace(System.out); + } + finally { + if(fos != null) { + try { + fos.close(); + fos = null; + } + catch(IOException ioEx) { + // I G N O R E + } + } + } + } + + /** + * The HSSFClientAnchor class accepts eight parameters. In order, these are; + * + * * How far the left hand edge of the image is inset from the left hand + * edge of the cell + * * How far the top edge of the image is inset from the top of the cell + * * How far the right hand edge of the image is inset from the left + * hand edge of the cell + * * How far the bottom edge of the image is inset from the top of the + * cell. + * * Together, parameters five and six determine the column and row + * co-ordinates of the cell whose top left hand corner will be aligned + * with the image's top left hand corner. + * * Together, parameter seven and eight determine the column and row + * co-ordinates of the cell whose top left hand corner will be aligned + * with the images bottom right hand corner. + * + * An instance of the ClientAnchorDetail class provides three of the eight + * parameters, one of the co-ordinates for the images top left hand corner, + * one of the co-ordinates for the images bottom right hand corner and + * either how far the image should be inset from the top or the left hand + * edge of the cell. + * + * @author Mark Beardsley [mas at apache.org] + * @version 1.00 5th August 2009. + */ + public class ClientAnchorDetail { + + public int fromIndex = 0; + public int toIndex = 0; + public int inset = 0; + + /** + * Create a new instance of the ClientAnchorDetail class using the + * following parameters. + * + * @param fromIndex A primitive int that contains one of the + * co-ordinates (row or column index) for the top left + * hand corner of the image. + * @param toIndex A primitive int that contains one of the + * co-ordinates (row or column index) for the bottom + * right hand corner of the image. + * @param inset A primitive int that contains a value which indicates + * how far the image should be inset from the top or the + * left hand edge of a cell. + */ + public ClientAnchorDetail(int fromIndex, int toIndex, int inset) { + this.fromIndex = fromIndex; + this.toIndex = toIndex; + this.inset = inset; + } + + /** + * Get one of the number of the column or row that contains the cell + * whose top left hand corner will be aligned with the top left hand + * corner of the image. + * + * @return The value - row or column index - for one of the co-ordinates + * of the top left hand corner of the image. + */ + public int getFromIndex() { + return(this.fromIndex); + } + + /** + * Get one of the number of the column or row that contains the cell + * whose top left hand corner will be aligned with the bottom righ hand + * corner of the image. + * + * @return The value - row or column index - for one of the co-ordinates + * of the bottom right hand corner of the image. + */ + public int getToIndex() { + return(this.toIndex); + } + + /** + * Get the image's offset from the edge of a cell. + * + * @return How far either the right hand or bottom edge of the image is + * inset from the left hand or top edge of a cell. + */ + public int getInset() { + return(this.inset); + } + } + + /** + * Utility methods used to convert Excel's character based column and row + * size measurements into pixels and/or millimetres. The class also contains + * various constants that are required in other calculations. + * + * @author xio[darjino@hotmail.com] + * @version 1.01 30th July 2009. + * Added by Mark Beardsley [msb at apache.org]. + * Additional constants. + * widthUnits2Millimetres() and millimetres2Units() methods. + */ + public static class ConvertImageUnits { + + // Each cell conatins a fixed number of co-ordinate points; this number + // does not vary with row height or column width or with font. These two + // constants are defined below. + public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB + public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB + // The resoultion of an image can be expressed as a specific number + // of pixels per inch. Displays and printers differ but 96 pixels per + // inch is an acceptable standard to beging with. + public static final int PIXELS_PER_INCH = 96; // MB + // Cnstants that defines how many pixels and points there are in a + // millimetre. These values are required for the conversion algorithm. + public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB + public static final double POINTS_PER_MILLIMETRE = 2.83; // MB + // The column width returned by HSSF and the width of a picture when + // positioned to exactly cover one cell are different by almost exactly + // 2mm - give or take rounding errors. This constant allows that + // additional amount to be accounted for when calculating how many + // celles the image ought to overlie. + public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB + public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; + public static final int UNIT_OFFSET_LENGTH = 7; + public static final int[] UNIT_OFFSET_MAP = new int[] + { 0, 36, 73, 109, 146, 182, 219 }; + + /** + * pixel units to excel width units(units of 1/256th of a character width) + * @param pxs + * @return + */ + public static short pixel2WidthUnits(int pxs) { + short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * + (pxs / UNIT_OFFSET_LENGTH)); + widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)]; + return widthUnits; + } + + /** + * excel width units(units of 1/256th of a character width) to pixel + * units. + * + * @param widthUnits + * @return + */ + public static int widthUnits2Pixel(short widthUnits) { + int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) + * UNIT_OFFSET_LENGTH; + int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; + pixels += Math.round((float) offsetWidthUnits / + ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); + return pixels; + } + + /** + * Convert Excel's width units into millimetres. + * + * @param widthUnits The width of the column or the height of the + * row in Excel's units. + * @return A primitive double that contains the columns width or rows + * height in millimetres. + */ + public static double widthUnits2Millimetres(short widthUnits) { + return(ConvertImageUnits.widthUnits2Pixel(widthUnits) / + ConvertImageUnits.PIXELS_PER_MILLIMETRES); + } + + /** + * Convert into millimetres Excel's width units.. + * + * @param millimetres A primitive double that contains the columns + * width or rows height in millimetres. + * @return A primitive int that contains the columns width or rows + * height in Excel's units. + */ + public static int millimetres2WidthUnits(double millimetres) { + return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres * + ConvertImageUnits.PIXELS_PER_MILLIMETRES))); + } + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/Alignment.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/Alignment.java new file mode 100644 index 0000000000..b54640ee73 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/Alignment.java @@ -0,0 +1,66 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Shows how various alignment options work. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class Alignment { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + HSSFRow row = sheet.createRow(2); + createCell(wb, row, 0, HSSFCellStyle.ALIGN_CENTER); + createCell(wb, row, 1, HSSFCellStyle.ALIGN_CENTER_SELECTION); + createCell(wb, row, 2, HSSFCellStyle.ALIGN_FILL); + createCell(wb, row, 3, HSSFCellStyle.ALIGN_GENERAL); + createCell(wb, row, 4, HSSFCellStyle.ALIGN_JUSTIFY); + createCell(wb, row, 5, HSSFCellStyle.ALIGN_LEFT); + createCell(wb, row, 6, HSSFCellStyle.ALIGN_RIGHT); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } + + /** + * Creates a cell and aligns it a certain way. + * + * @param wb the workbook + * @param row the row to create the cell in + * @param column the column number to create the cell in + * @param align the alignment for the cell. + */ + private static void createCell(HSSFWorkbook wb, HSSFRow row, int column, int align) { + HSSFCell cell = row.createCell(column); + cell.setCellValue("Align It"); + HSSFCellStyle cellStyle = wb.createCellStyle(); + cellStyle.setAlignment((short)align); + cell.setCellStyle(cellStyle); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/BigExample.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/BigExample.java new file mode 100644 index 0000000000..3981a145da --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/BigExample.java @@ -0,0 +1,169 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.util.HSSFColor; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Demonstrates many features of the user API at once. Used in the HOW-TO guide. + * + * @author Glen Stampoultzis (glens at apache.org) + * @author Andrew Oliver (acoliver at apache.org) + */ +public class BigExample { + public static void main(String[] args) throws IOException { + int rownum; + + // create a new file + FileOutputStream out = new FileOutputStream("workbook.xls"); + // create a new workbook + HSSFWorkbook wb = new HSSFWorkbook(); + // create a new sheet + HSSFSheet s = wb.createSheet(); + // declare a row object reference + HSSFRow r = null; + // declare a cell object reference + HSSFCell c = null; + // create 3 cell styles + HSSFCellStyle cs = wb.createCellStyle(); + HSSFCellStyle cs2 = wb.createCellStyle(); + HSSFCellStyle cs3 = wb.createCellStyle(); + // create 2 fonts objects + HSSFFont f = wb.createFont(); + HSSFFont f2 = wb.createFont(); + + //set font 1 to 12 point type + f.setFontHeightInPoints((short) 12); + //make it red + f.setColor(HSSFColor.RED.index); + // make it bold + //arial is the default font + f.setBoldweight(f.BOLDWEIGHT_BOLD); + + //set font 2 to 10 point type + f2.setFontHeightInPoints((short) 10); + //make it the color at palette index 0xf (white) + f2.setColor(HSSFColor.WHITE.index); + //make it bold + f2.setBoldweight(f2.BOLDWEIGHT_BOLD); + + //set cell stlye + cs.setFont(f); + //set the cell format see HSSFDataFromat for a full list + cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + + //set a thin border + cs2.setBorderBottom(cs2.BORDER_THIN); + //fill w fg fill color + cs2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + // set foreground fill to red + cs2.setFillForegroundColor(HSSFColor.RED.index); + + // set the font + cs2.setFont(f2); + + // set the sheet name to HSSF Test + wb.setSheetName(0, "HSSF Test"); + // create a sheet with 300 rows (0-299) + for (rownum = 0; rownum < 300; rownum++) + { + // create a row + r = s.createRow(rownum); + // on every other row + if ((rownum % 2) == 0) + { + // make the row height bigger (in twips - 1/20 of a point) + r.setHeight((short) 0x249); + } + + //r.setRowNum(( short ) rownum); + // create 50 cells (0-49) (the += 2 becomes apparent later + for (int cellnum = 0; cellnum < 50; cellnum += 2) + { + // create a numeric cell + c = r.createCell(cellnum); + // do some goofy math to demonstrate decimals + c.setCellValue(rownum * 10000 + cellnum + + (((double) rownum / 1000) + + ((double) cellnum / 10000))); + + // on every other row + if ((rownum % 2) == 0) + { + // set this cell to the first cell style we defined + c.setCellStyle(cs); + } + + // create a string cell (see why += 2 in the + c = r.createCell(cellnum + 1); + + // set the cell's string value to "TEST" + c.setCellValue("TEST"); + // make this column a bit wider + s.setColumnWidth(cellnum + 1, (int)((50 * 8) / ((double) 1 / 20))); + + // on every other row + if ((rownum % 2) == 0) + { + // set this to the white on red cell style + // we defined above + c.setCellStyle(cs2); + } + + } + } + + //draw a thick black border on the row at the bottom using BLANKS + // advance 2 rows + rownum++; + rownum++; + + r = s.createRow(rownum); + + // define the third style to be the default + // except with a thick black border at the bottom + cs3.setBorderBottom(cs3.BORDER_THICK); + + //create 50 cells + for (int cellnum =0; cellnum < 50; cellnum++) { + //create a blank type cell (no value) + c = r.createCell(cellnum); + // set it to the thick black border style + c.setCellStyle(cs3); + } + + //end draw thick black border + + + // demonstrate adding/naming and deleting a sheet + // create a sheet, set its title then delete it + s = wb.createSheet(); + wb.setSheetName(1, "DeletedSheet"); + wb.removeSheetAt(1); + //end deleted sheet + + // write the workbook to the output stream + // close our file (don't blow out our file handles + wb.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/Borders.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/Borders.java new file mode 100644 index 0000000000..d29635004a --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/Borders.java @@ -0,0 +1,60 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.util.HSSFColor; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Demonstrates how to create borders around cells. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class Borders { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + + // Create a row and put some cells in it. Rows are 0 based. + HSSFRow row = sheet.createRow(1); + + // Create a cell and put a value in it. + HSSFCell cell = row.createCell(1); + cell.setCellValue(4); + + // Style the cell with borders all around. + HSSFCellStyle style = wb.createCellStyle(); + style.setBorderBottom(HSSFCellStyle.BORDER_THIN); + style.setBottomBorderColor(HSSFColor.BLACK.index); + style.setBorderLeft(HSSFCellStyle.BORDER_THIN); + style.setLeftBorderColor(HSSFColor.GREEN.index); + style.setBorderRight(HSSFCellStyle.BORDER_THIN); + style.setRightBorderColor(HSSFColor.BLUE.index); + style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED); + style.setTopBorderColor(HSSFColor.ORANGE.index); + cell.setCellStyle(style); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/CellComments.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/CellComments.java new file mode 100644 index 0000000000..c3a213d582 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/CellComments.java @@ -0,0 +1,98 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.util.HSSFColor; + +import java.io.*; + +/** + * Demonstrates how to work with excel cell comments. + * + *

    + * Excel comment is a kind of a text shape, + * so inserting a comment is very similar to placing a text box in a worksheet + *

    + * + * @author Yegor Kozlov + */ +public class CellComments { + + public static void main(String[] args) throws IOException { + + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF"); + + // Create the drawing patriarch. This is the top level container for all shapes including cell comments. + HSSFPatriarch patr = sheet.createDrawingPatriarch(); + + //create a cell in row 3 + HSSFCell cell1 = sheet.createRow(3).createCell(1); + cell1.setCellValue(new HSSFRichTextString("Hello, World")); + + //anchor defines size and position of the comment in worksheet + HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5)); + + // set text in the comment + comment1.setString(new HSSFRichTextString("We can set comments in POI")); + + //set comment author. + //you can see it in the status bar when moving mouse over the commented cell + comment1.setAuthor("Apache Software Foundation"); + + // The first way to assign comment to a cell is via HSSFCell.setCellComment method + cell1.setCellComment(comment1); + + //create another cell in row 6 + HSSFCell cell2 = sheet.createRow(6).createCell(1); + cell2.setCellValue(36.6); + + + HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 8, (short) 6, 11)); + //modify background color of the comment + comment2.setFillColor(204, 236, 255); + + HSSFRichTextString string = new HSSFRichTextString("Normal body temperature"); + + //apply custom font to the text in the comment + HSSFFont font = wb.createFont(); + font.setFontName("Arial"); + font.setFontHeightInPoints((short)10); + font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + font.setColor(HSSFColor.RED.index); + string.applyFont(font); + + comment2.setString(string); + comment2.setVisible(true); //by default comments are hidden. This one is always visible. + + comment2.setAuthor("Bill Gates"); + + /** + * The second way to assign comment to a cell is to implicitly specify its row and column. + * Note, it is possible to set row and column of a non-existing cell. + * It works, the comment is visible. + */ + comment2.setRow(6); + comment2.setColumn(1); + + FileOutputStream out = new FileOutputStream("poi_comment.xls"); + wb.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/CellTypes.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/CellTypes.java new file mode 100644 index 0000000000..07b9b0165a --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/CellTypes.java @@ -0,0 +1,45 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Date; + +public class CellTypes { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + HSSFRow row = sheet.createRow(2); + row.createCell(0).setCellValue(1.1); + row.createCell(1).setCellValue(new Date()); + row.createCell(2).setCellValue("a string"); + row.createCell(3).setCellValue(true); + row.createCell(4).setCellType(HSSFCell.CELL_TYPE_ERROR); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/CreateCells.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/CreateCells.java new file mode 100644 index 0000000000..ff8a0b73ca --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/CreateCells.java @@ -0,0 +1,54 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFCell; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Illustrates how to create cell values. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class CreateCells { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + + // Create a row and put some cells in it. Rows are 0 based. + HSSFRow row = sheet.createRow(0); + // Create a cell and put a value in it. + HSSFCell cell = row.createCell(0); + cell.setCellValue(1); + + // Or do it on one line. + row.createCell(1).setCellValue(1.2); + row.createCell(2).setCellValue("This is a string"); + row.createCell(3).setCellValue(true); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/CreateDateCells.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/CreateDateCells.java new file mode 100644 index 0000000000..746fd536b8 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/CreateDateCells.java @@ -0,0 +1,58 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Date; + +/** + * An example on how to cells with dates. The important thing to note + * about dates is that they are really normal numeric cells that are + * formatted specially. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class CreateDateCells { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + + // Create a row and put some cells in it. Rows are 0 based. + HSSFRow row = sheet.createRow(0); + + // Create a cell and put a date value in it. The first cell is not styled as a date. + HSSFCell cell = row.createCell(0); + cell.setCellValue(new Date()); + + // we style the second cell as a date (and time). It is important to create a new cell style from the workbook + // otherwise you can end up modifying the built in style and effecting not only this cell but other cells. + HSSFCellStyle cellStyle = wb.createCellStyle(); + cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); + cell = row.createCell(1); + cell.setCellValue(new Date()); + cell.setCellStyle(cellStyle); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/EmeddedObjects.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/EmeddedObjects.java new file mode 100644 index 0000000000..bb6f19d0a5 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/EmeddedObjects.java @@ -0,0 +1,68 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.poifs.filesystem.DirectoryNode; +import org.apache.poi.poifs.filesystem.Entry; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.hwpf.HWPFDocument; +import org.apache.poi.hslf.HSLFSlideShow; +import org.apache.poi.hslf.usermodel.SlideShow; + +import java.io.FileInputStream; +import java.util.Iterator; + +/** + * Demonstrates how you can extract embedded data from a .xls file + */ +public class EmeddedObjects { + public static void main(String[] args) throws Exception { + POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0])); + HSSFWorkbook workbook = new HSSFWorkbook(fs); + for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) { + //the OLE2 Class Name of the object + String oleName = obj.getOLE2ClassName(); + if (oleName.equals("Worksheet")) { + DirectoryNode dn = (DirectoryNode) obj.getDirectory(); + HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, fs, false); + //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets()); + } else if (oleName.equals("Document")) { + DirectoryNode dn = (DirectoryNode) obj.getDirectory(); + HWPFDocument embeddedWordDocument = new HWPFDocument(dn); + //System.out.println(entry.getName() + ": " + embeddedWordDocument.getRange().text()); + } else if (oleName.equals("Presentation")) { + DirectoryNode dn = (DirectoryNode) obj.getDirectory(); + SlideShow embeddedPowerPointDocument = new SlideShow(new HSLFSlideShow(dn)); + //System.out.println(entry.getName() + ": " + embeddedPowerPointDocument.getSlides().length); + } else { + if(obj.hasDirectoryEntry()){ + // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is + DirectoryNode dn = (DirectoryNode) obj.getDirectory(); + for (Iterator entries = dn.getEntries(); entries.hasNext();) { + Entry entry = (Entry) entries.next(); + //System.out.println(oleName + "." + entry.getName()); + } + } else { + // There is no DirectoryEntry + // Recover the object's data from the HSSFObjectData instance. + byte[] objectData = obj.getObjectData(); + } + } + } + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/EventExample.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/EventExample.java new file mode 100644 index 0000000000..c5644c9597 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/EventExample.java @@ -0,0 +1,118 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; +import org.apache.poi.hssf.eventusermodel.HSSFListener; +import org.apache.poi.hssf.eventusermodel.HSSFRequest; +import org.apache.poi.hssf.record.*; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * This example shows how to use the event API for reading a file. + */ +public class EventExample + implements HSSFListener +{ + private SSTRecord sstrec; + + /** + * This method listens for incoming records and handles them as required. + * @param record The record that was found while reading. + */ + public void processRecord(Record record) + { + switch (record.getSid()) + { + // the BOFRecord can represent either the beginning of a sheet or the workbook + case BOFRecord.sid: + BOFRecord bof = (BOFRecord) record; + if (bof.getType() == bof.TYPE_WORKBOOK) + { + System.out.println("Encountered workbook"); + // assigned to the class level member + } else if (bof.getType() == bof.TYPE_WORKSHEET) + { + System.out.println("Encountered sheet reference"); + } + break; + case BoundSheetRecord.sid: + BoundSheetRecord bsr = (BoundSheetRecord) record; + System.out.println("New sheet named: " + bsr.getSheetname()); + break; + case RowRecord.sid: + RowRecord rowrec = (RowRecord) record; + System.out.println("Row found, first column at " + + rowrec.getFirstCol() + " last column at " + rowrec.getLastCol()); + break; + case NumberRecord.sid: + NumberRecord numrec = (NumberRecord) record; + System.out.println("Cell found with value " + numrec.getValue() + + " at row " + numrec.getRow() + " and column " + numrec.getColumn()); + break; + // SSTRecords store a array of unique strings used in Excel. + case SSTRecord.sid: + sstrec = (SSTRecord) record; + for (int k = 0; k < sstrec.getNumUniqueStrings(); k++) + { + System.out.println("String table value " + k + " = " + sstrec.getString(k)); + } + break; + case LabelSSTRecord.sid: + LabelSSTRecord lrec = (LabelSSTRecord) record; + System.out.println("String cell found with value " + + sstrec.getString(lrec.getSSTIndex())); + break; + } + } + + /** + * Read an excel file and spit out what we find. + * + * @param args Expect one argument that is the file to read. + * @throws IOException When there is an error processing the file. + */ + public static void main(String[] args) throws IOException + { + // create a new file input stream with the input file specified + // at the command line + FileInputStream fin = new FileInputStream(args[0]); + // create a new org.apache.poi.poifs.filesystem.Filesystem + POIFSFileSystem poifs = new POIFSFileSystem(fin); + // get the Workbook (excel part) stream in a InputStream + InputStream din = poifs.createDocumentInputStream("Workbook"); + // construct out HSSFRequest object + HSSFRequest req = new HSSFRequest(); + // lazy listen for ALL records with the listener shown above + req.addListenerForAllRecords(new EventExample()); + // create our event factory + HSSFEventFactory factory = new HSSFEventFactory(); + // process our events based on the document input stream + factory.processEvents(req, din); + // once all the events are processed close our file input stream + fin.close(); + // and our document input stream (don't want to leak these!) + din.close(); + System.out.println("done."); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/FrillsAndFills.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/FrillsAndFills.java new file mode 100644 index 0000000000..02b7cb3e39 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/FrillsAndFills.java @@ -0,0 +1,60 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.util.HSSFColor; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Shows how to use various fills. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class FrillsAndFills { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + + // Create a row and put some cells in it. Rows are 0 based. + HSSFRow row = sheet.createRow(1); + + // Aqua background + HSSFCellStyle style = wb.createCellStyle(); + style.setFillBackgroundColor(HSSFColor.AQUA.index); + style.setFillPattern(HSSFCellStyle.BIG_SPOTS); + HSSFCell cell = row.createCell(1); + cell.setCellValue("X"); + cell.setCellStyle(style); + + // Orange "foreground", foreground being the fill foreground not the font color. + style = wb.createCellStyle(); + style.setFillForegroundColor(HSSFColor.ORANGE.index); + style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + cell = row.createCell(2); + cell.setCellValue("X"); + cell.setCellStyle(style); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/HSSFReadWrite.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/HSSFReadWrite.java new file mode 100644 index 0000000000..3cc124b67b --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/HSSFReadWrite.java @@ -0,0 +1,244 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFDataFormat; +import org.apache.poi.hssf.usermodel.HSSFFont; +import org.apache.poi.hssf.usermodel.HSSFRichTextString; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.util.CellRangeAddress; + +/** + * File for HSSF testing/examples + * + * THIS IS NOT THE MAIN HSSF FILE!! This is a utility for testing functionality. + * It does contain sample API usage that may be educational to regular API + * users. + * + * @see #main + * @author Andrew Oliver (acoliver at apache dot org) + */ +public final class HSSFReadWrite { + + /** + * creates an {@link HSSFWorkbook} the specified OS filename. + */ + private static HSSFWorkbook readFile(String filename) throws IOException { + return new HSSFWorkbook(new FileInputStream(filename)); + } + + /** + * given a filename this outputs a sample sheet with just a set of + * rows/cells. + */ + private static void testCreateSampleSheet(String outputFilename) throws IOException { + int rownum; + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet s = wb.createSheet(); + HSSFCellStyle cs = wb.createCellStyle(); + HSSFCellStyle cs2 = wb.createCellStyle(); + HSSFCellStyle cs3 = wb.createCellStyle(); + HSSFFont f = wb.createFont(); + HSSFFont f2 = wb.createFont(); + + f.setFontHeightInPoints((short) 12); + f.setColor((short) 0xA); + f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + f2.setFontHeightInPoints((short) 10); + f2.setColor((short) 0xf); + f2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + cs.setFont(f); + cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + cs2.setBorderBottom(HSSFCellStyle.BORDER_THIN); + cs2.setFillPattern((short) 1); // fill w fg + cs2.setFillForegroundColor((short) 0xA); + cs2.setFont(f2); + wb.setSheetName(0, "HSSF Test"); + for (rownum = 0; rownum < 300; rownum++) { + HSSFRow r = s.createRow(rownum); + if ((rownum % 2) == 0) { + r.setHeight((short) 0x249); + } + + for (int cellnum = 0; cellnum < 50; cellnum += 2) { + HSSFCell c = r.createCell(cellnum); + c.setCellValue(rownum * 10000 + cellnum + + (((double) rownum / 1000) + ((double) cellnum / 10000))); + if ((rownum % 2) == 0) { + c.setCellStyle(cs); + } + c = r.createCell(cellnum + 1); + c.setCellValue(new HSSFRichTextString("TEST")); + // 50 characters divided by 1/20th of a point + s.setColumnWidth(cellnum + 1, (int) (50 * 8 / 0.05)); + if ((rownum % 2) == 0) { + c.setCellStyle(cs2); + } + } + } + + // draw a thick black border on the row at the bottom using BLANKS + rownum++; + rownum++; + HSSFRow r = s.createRow(rownum); + cs3.setBorderBottom(HSSFCellStyle.BORDER_THICK); + for (int cellnum = 0; cellnum < 50; cellnum++) { + HSSFCell c = r.createCell(cellnum); + c.setCellStyle(cs3); + } + s.addMergedRegion(new CellRangeAddress(0, 3, 0, 3)); + s.addMergedRegion(new CellRangeAddress(100, 110, 100, 110)); + + // end draw thick black border + // create a sheet, set its title then delete it + s = wb.createSheet(); + wb.setSheetName(1, "DeletedSheet"); + wb.removeSheetAt(1); + + // end deleted sheet + FileOutputStream out = new FileOutputStream(outputFilename); + wb.write(out); + out.close(); + } + + /** + * Method main + * + * Given 1 argument takes that as the filename, inputs it and dumps the + * cell values/types out to sys.out.
    + * + * given 2 arguments where the second argument is the word "write" and the + * first is the filename - writes out a sample (test) spreadsheet + * see {@link HSSFReadWrite#testCreateSampleSheet(String)}.
    + * + * given 2 arguments where the first is an input filename and the second + * an output filename (not write), attempts to fully read in the + * spreadsheet and fully write it out.
    + * + * given 3 arguments where the first is an input filename and the second an + * output filename (not write) and the third is "modify1", attempts to read in the + * spreadsheet, deletes rows 0-24, 74-99. Changes cell at row 39, col 3 to + * "MODIFIED CELL" then writes it out. Hence this is "modify test 1". If you + * take the output from the write test, you'll have a valid scenario. + */ + public static void main(String[] args) { + if (args.length < 1) { + System.err.println("At least one argument expected"); + return; + } + + String fileName = args[0]; + try { + if (args.length < 2) { + + HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); + + System.out.println("Data dump:\n"); + + for (int k = 0; k < wb.getNumberOfSheets(); k++) { + HSSFSheet sheet = wb.getSheetAt(k); + int rows = sheet.getPhysicalNumberOfRows(); + System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows + + " row(s)."); + for (int r = 0; r < rows; r++) { + HSSFRow row = sheet.getRow(r); + if (row == null) { + continue; + } + + int cells = row.getPhysicalNumberOfCells(); + System.out.println("\nROW " + row.getRowNum() + " has " + cells + + " cell(s)."); + for (int c = 0; c < cells; c++) { + HSSFCell cell = row.getCell(c); + String value = null; + + switch (cell.getCellType()) { + + case HSSFCell.CELL_TYPE_FORMULA: + value = "FORMULA value=" + cell.getCellFormula(); + break; + + case HSSFCell.CELL_TYPE_NUMERIC: + value = "NUMERIC value=" + cell.getNumericCellValue(); + break; + + case HSSFCell.CELL_TYPE_STRING: + value = "STRING value=" + cell.getStringCellValue(); + break; + + default: + } + System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + + value); + } + } + } + } else if (args.length == 2) { + if (args[1].toLowerCase().equals("write")) { + System.out.println("Write mode"); + long time = System.currentTimeMillis(); + HSSFReadWrite.testCreateSampleSheet(fileName); + + System.out.println("" + (System.currentTimeMillis() - time) + + " ms generation time"); + } else { + System.out.println("readwrite test"); + HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); + FileOutputStream stream = new FileOutputStream(args[1]); + + wb.write(stream); + stream.close(); + } + } else if (args.length == 3 && args[2].toLowerCase().equals("modify1")) { + // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!" + + HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); + FileOutputStream stream = new FileOutputStream(args[1]); + HSSFSheet sheet = wb.getSheetAt(0); + + for (int k = 0; k < 25; k++) { + HSSFRow row = sheet.getRow(k); + + sheet.removeRow(row); + } + for (int k = 74; k < 100; k++) { + HSSFRow row = sheet.getRow(k); + + sheet.removeRow(row); + } + HSSFRow row = sheet.getRow(39); + HSSFCell cell = row.getCell(3); + cell.setCellValue("MODIFIED CELL!!!!!"); + + wb.write(stream); + stream.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/HyperlinkFormula.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/HyperlinkFormula.java new file mode 100644 index 0000000000..8ed9213bfa --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/HyperlinkFormula.java @@ -0,0 +1,44 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Test if hyperlink formula, with url that got more than 127 characters, works + * + * @author Bernard Chesnoy + */ +public class HyperlinkFormula { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + HSSFRow row = sheet.createRow(0); + + HSSFCell cell = row.createCell(0); + cell.setCellType(HSSFCell.CELL_TYPE_FORMULA); + cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")"); + + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/Hyperlinks.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/Hyperlinks.java new file mode 100644 index 0000000000..0872749d02 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/Hyperlinks.java @@ -0,0 +1,89 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.util.HSSFColor; + +import java.io.IOException; +import java.io.FileOutputStream; + +/** + * Demonstrates how to create hyperlinks. + * + * @author Yegor Kozlov (yegor at apach.org) + */ +public class Hyperlinks { + + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + + //cell style for hyperlinks + //by default hyperlinks are blue and underlined + HSSFCellStyle hlink_style = wb.createCellStyle(); + HSSFFont hlink_font = wb.createFont(); + hlink_font.setUnderline(HSSFFont.U_SINGLE); + hlink_font.setColor(HSSFColor.BLUE.index); + hlink_style.setFont(hlink_font); + + HSSFCell cell; + HSSFSheet sheet = wb.createSheet("Hyperlinks"); + + //URL + cell = sheet.createRow(0).createCell(0); + cell.setCellValue("URL Link"); + HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL); + link.setAddress("http://poi.apache.org/"); + cell.setHyperlink(link); + cell.setCellStyle(hlink_style); + + //link to a file in the current directory + cell = sheet.createRow(1).createCell(0); + cell.setCellValue("File Link"); + link = new HSSFHyperlink(HSSFHyperlink.LINK_FILE); + link.setAddress("link1.xls"); + cell.setHyperlink(link); + cell.setCellStyle(hlink_style); + + //e-mail link + cell = sheet.createRow(2).createCell(0); + cell.setCellValue("Email Link"); + link = new HSSFHyperlink(HSSFHyperlink.LINK_EMAIL); + //note, if subject contains white spaces, make sure they are url-encoded + link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); + cell.setHyperlink(link); + cell.setCellStyle(hlink_style); + + //link to a place in this workbook + + //create a target sheet and cell + HSSFSheet sheet2 = wb.createSheet("Target Sheet"); + sheet2.createRow(0).createCell(0).setCellValue("Target Cell"); + + cell = sheet.createRow(3).createCell(0); + cell.setCellValue("Worksheet Link"); + link = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT); + link.setAddress("'Target Sheet'!A1"); + cell.setHyperlink(link); + cell.setCellStyle(hlink_style); + + FileOutputStream out = new FileOutputStream("hssf-links.xls"); + wb.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/InCellLists.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/InCellLists.java new file mode 100644 index 0000000000..3ecd30e450 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/InCellLists.java @@ -0,0 +1,569 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.hssf.usermodel.examples; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFDataFormat; +import org.apache.poi.hssf.usermodel.HSSFRichTextString; + +/** + * This class contains code that demonstrates how to insert plain, numbered + * and bulleted lists into an Excel spreadsheet cell. + * + * Look at the code contained in the demonstrateMethodCalls() method. It calls + * other methods that create plain, numbered and bulleted single and + * multi-level lists. The demonstrateMethodCalls() method appears at the top + * of the class definition. + * + * Though different methods are provided to construct single and multi-level + * plain, numbered and bulleted lists, close examination will reveal that they + * are not strictly necessary. If the inputs to the listInCell() and + * multilLevelListInCell() methods are constructed to include the bullet + * character or the item numbers then these methods alone may be sufficient. + * + * @author Mark Beardsley [msb at apache.org] + */ +public class InCellLists { + + // This character looks like a solid, black, loser case letter 'o' + // positioned up from the base line of the text. + private static final char BULLET_CHARACTER = '\u2022'; + + // The tab character - \t - cannot be used to create a tab space + // within a cell as it is rendered as a square. Therefore, four + // spaces are used to simulate that character. + private static final String TAB = " "; + + /** + * Call each of the list creation methods. + * + * @param outputFilename A String that encapsulates the name of and path to + * the Excel spreadsheet file this code will create. + */ + public void demonstrateMethodCalls(String outputFilename) { + HSSFWorkbook workbook = null; + HSSFSheet sheet = null; + HSSFRow row = null; + HSSFCell cell = null; + File outputFile = null; + FileOutputStream fos = null; + ArrayList multiLevelListItems = null; + ArrayList listItems = null; + String listItem = null; + try { + workbook = new HSSFWorkbook(); + sheet = workbook.createSheet("In Cell Lists"); + row = sheet.createRow(0); + + // Create a cell at A1 and insert a single, bulleted, item into + // that cell. + cell = row.createCell(0); + this.bulletedItemInCell(workbook, "List Item", cell); + + // Create a cell at A2 and insert a plain list - that is one + // whose items are neither bulleted or numbered - into that cell. + row = sheet.createRow(1); + cell = row.createCell(0); + listItems = new ArrayList(); + listItems.add("List Item One."); + listItems.add("List Item Two."); + listItems.add("List Item Three."); + listItems.add("List Item Four."); + this.listInCell(workbook, listItems, cell); + // The row height and cell width are set here to ensure that the + // list may be seen. + row.setHeight((short)1100); + sheet.setColumnWidth(0, 9500); + + // Create a cell at A3 and insert a numbered list into that cell. + // Note that a couple of items have been added to the listItems + // ArrayList + row = sheet.createRow(2); + cell = row.createCell(0); + listItems.add("List Item Five."); + listItems.add("List Item Six."); + this.numberedListInCell(workbook, listItems, cell, 1, 2); + row.setHeight((short)1550); + + // Create a cell at A4 and insert a numbered list into that cell. + // Note that a couple of items have been added to the listItems + // ArrayList + row = sheet.createRow(3); + cell = row.createCell(0); + listItems.add("List Item Seven."); + listItems.add("List Item Eight."); + listItems.add("List Item Nine."); + listItems.add("List Item Ten."); + this.bulletedListInCell(workbook, listItems, cell); + row.setHeight((short)2550); + + // Insert a plain, multi-level list into cell A5. Note that + // the major difference here is that the list items are passed as + // an ArrayList of MultiLevelListItems. Note that an ArrayList + // of instances of an inner class was used here in preference to + // a Hashtable or HashMap as the ArrayList will preserve the + // ordering of the items added to it; the first item added will + // be the first item recovered and the last item added, the last + // item recovered. + row = sheet.createRow(4); + cell = row.createCell(0); + multiLevelListItems = new ArrayList(); + listItems = new ArrayList(); + listItems.add("ML List Item One - Sub Item One."); + listItems.add("ML List Item One - Sub Item Two."); + listItems.add("ML List Item One - Sub Item Three."); + listItems.add("ML List Item One - Sub Item Four."); + multiLevelListItems.add(new MultiLevelListItem("List Item One.", listItems)); + // Passing either null or an empty ArrayList will signal that + // there are no lower level items associated with the top level + // item + multiLevelListItems.add(new MultiLevelListItem("List Item Two.", null)); + multiLevelListItems.add(new MultiLevelListItem("List Item Three.", null)); + listItems = new ArrayList(); + listItems.add("ML List Item Four - Sub Item One."); + listItems.add("ML List Item Four - Sub Item Two."); + listItems.add("ML List Item Four - Sub Item Three."); + multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems)); + this.multiLevelListInCell(workbook, multiLevelListItems, cell); + row.setHeight((short)2800); + + // Insert a numbered multi-level list into cell A6. Note that the + // same ArrayList as constructed for the above plain multi-level + // list example will be re-used + row = sheet.createRow(5); + cell = row.createCell(0); + this.multiLevelNumberedListInCell(workbook, multiLevelListItems, + cell, 1, 1, 1, 2); + row.setHeight((short)2800); + + // Insert a numbered multi-level list into cell A7. Note that the + // same ArrayList as constructed for the plain multi-level list + // example will be re-used + row = sheet.createRow(6); + cell = row.createCell(0); + this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell); + row.setHeight((short)2800); + + // Save the completed workbook + outputFile = new File(outputFilename); + fos = new FileOutputStream(outputFile); + workbook.write(fos); + } + catch(FileNotFoundException fnfEx) { + System.out.println("Caught a: " + fnfEx.getClass().getName()); + System.out.println("Message: " + fnfEx.getMessage()); + System.out.println("Stacktrace follows..........."); + fnfEx.printStackTrace(System.out); + } + catch(IOException ioEx) { + System.out.println("Caught a: " + ioEx.getClass().getName()); + System.out.println("Message: " + ioEx.getMessage()); + System.out.println("Stacktrace follows..........."); + ioEx.printStackTrace(System.out); + } + finally { + if(fos != null) { + try { + fos.close(); + } + catch(IOException ioEx) { + + } + } + } + } + + /** + * Inserts a single bulleted item into a cell. + * + * @param workbook A reference to the HSSFWorkbook that 'contains' the + * cell. + * @param listItem An instance of the String class encapsulating the + * items text. + * @param cell An instance of the HSSFCell class that encapsulates a + * reference to the spreadsheet cell into which the list item + * will be written. + */ + public void bulletedItemInCell(HSSFWorkbook workbook, String listItem, HSSFCell cell) { + // A format String must be built to ensure that the contents of the + // cell appear as a bulleted item. + HSSFDataFormat format = workbook.createDataFormat(); + String formatString = InCellLists.BULLET_CHARACTER + " @"; + int formatIndex = format.getFormat(formatString); + + // Construct an HSSFCellStyle and set it's data formt to use the + // object created above. + HSSFCellStyle bulletStyle = workbook.createCellStyle(); + bulletStyle.setDataFormat((short)formatIndex); + + // Set the cells contents and style. + cell.setCellValue(new HSSFRichTextString(listItem)); + cell.setCellStyle(bulletStyle); + } + + /** + * Inserts a list of plain items - that is items that are neither + * numbered or bulleted - into a single cell. + * + * @param workbook A reference to the HSSFWorkbook that 'contains' the + * cell. + * @param listItems An ArrayList whose elements encapsulate the text for + * the list's items. + * @param cell An instance of the HSSFCell class that encapsulates a + * reference to the spreadsheet cell into which the list + * will be written. + */ + public void listInCell(HSSFWorkbook workbook, ArrayList listItems, HSSFCell cell) { + StringBuffer buffer = new StringBuffer(); + HSSFCellStyle wrapStyle = workbook.createCellStyle(); + wrapStyle.setWrapText(true); + for(String listItem : listItems) { + buffer.append(listItem); + buffer.append("\n"); + } + // The StringBuffer's contents are the source for the contents + // of the cell. + cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); + cell.setCellStyle(wrapStyle); + } + + /** + * Inserts a numbered list into a single cell. + * + * @param workbook A reference to the HSSFWorkbook that 'contains' the + * cell. + * @param listItems An ArrayList whose elements encapsulate the text for + * the lists items. + * @param cell An instance of the HSSFCell class that encapsulates a + * reference to the spreadsheet cell into which the list + * will be written. + * @param startingValue A primitive int containing the number for the first + * item in the list. + * @param increment A primitive int containing the value that should be used + * to calculate subsequent item numbers. + */ + public void numberedListInCell(HSSFWorkbook workbook, + ArrayList listItems, + HSSFCell cell, + int startingValue, + int increment) { + StringBuffer buffer = new StringBuffer(); + int itemNumber = startingValue; + // Note that again, an HSSFCellStye object is required and that + // it's wrap text property should be set to 'true' + HSSFCellStyle wrapStyle = workbook.createCellStyle(); + wrapStyle.setWrapText(true); + // Note that the basic method is identical to the listInCell() method + // with one difference; a number prefixed to the items text. + for(String listItem : listItems) { + buffer.append(String.valueOf(itemNumber) + ". "); + buffer.append(listItem); + buffer.append("\n"); + itemNumber += increment; + } + // The StringBuffer's contents are the source for the contents + // of the cell. + cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); + cell.setCellStyle(wrapStyle); + } + + /** + * Insert a bulleted list into a cell. + * + * @param workbook A reference to the HSSFWorkbook that 'contains' the + * cell. + * @param listItems An ArrayList whose elements encapsulate the text for + * the lists items. + * @param cell An instance of the HSSFCell class that encapsulates a + * reference to the spreadsheet cell into which the list + * will be written. + */ + public void bulletedListInCell(HSSFWorkbook workbook, + ArrayList listItems, + HSSFCell cell) { + StringBuffer buffer = new StringBuffer(); + // Note that again, an HSSFCellStye object is required and that + // it's wrap text property should be set to 'true' + HSSFCellStyle wrapStyle = workbook.createCellStyle(); + wrapStyle.setWrapText(true); + // Note that the basic method is identical to the listInCell() method + // with one difference; the bullet character prefixed to the items text. + for(String listItem : listItems) { + buffer.append(InCellLists.BULLET_CHARACTER + " "); + buffer.append(listItem); + buffer.append("\n"); + } + // The StringBuffer's contents are the source for the contents + // of the cell. + cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); + cell.setCellStyle(wrapStyle); + } + + /** + * Insert a multi-level list into a cell. + * + * @param workbook A reference to the HSSFWorkbook that 'contains' the + * cell. + * @param multiLevelListItems An ArrayList whose elements contain instances + * of the MultiLevelListItem class. Each element + * encapsulates the text for the high level item + * along with an ArrayList. Each element of this + * ArrayList encapsulates the text for a lower + * level item. + * @param cell An instance of the HSSFCell class that encapsulates a + * reference to the spreadsheet cell into which the list + * will be written. + */ + public void multiLevelListInCell(HSSFWorkbook workbook, + ArrayList multiLevelListItems, + HSSFCell cell) { + StringBuffer buffer = new StringBuffer(); + ArrayList lowerLevelItems = null; + // Note that again, an HSSFCellStye object is required and that + // it's wrap text property should be set to 'true' + HSSFCellStyle wrapStyle = workbook.createCellStyle(); + wrapStyle.setWrapText(true); + // Step through the ArrayList of MultilLevelListItem instances. + for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { + // For each element in the ArrayList, get the text for the high + // level list item...... + buffer.append(multiLevelListItem.getItemText()); + buffer.append("\n"); + // and then an ArrayList whose elements encapsulate the text + // for the lower level list items. + lowerLevelItems = multiLevelListItem.getLowerLevelItems(); + if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { + for(String item : lowerLevelItems) { + buffer.append(InCellLists.TAB); + buffer.append(item); + buffer.append("\n"); + } + } + } + // The StringBuffer's contents are the source for the contents + // of the cell. + cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); + cell.setCellStyle(wrapStyle); + } + + /** + * Insert a multi-level list into a cell. + * + * @param workbook A reference to the HSSFWorkbook that 'contains' the + * cell. + * @param multiLevelListItems An ArrayList whose elements contain instances + * of the MultiLevelListItem class. Each element + * encapsulates the text for the high level item + * along with an ArrayList. Each element of this + * ArrayList encapsulates the text for a lower + * level item. + * @param cell An instance of the HSSFCell class that encapsulates a + * reference to the spreadsheet cell into which the list + * will be written. + * @param highLevelStartingValue A primitive int containing the number + * for the first high level item in the list. + * @param highLevelIncrement A primitive int containing the value that + * should be used to calculate the number of + * subsequent high level item. + * @param lowLevelStartingValue A primitive int will containing the number + * for the first low level item associated + * with a high level item. + * @param lowLevelIncrement A primitive int containing the value that + * should be used to calculate the number of + * subsequent low level item. + */ + public void multiLevelNumberedListInCell(HSSFWorkbook workbook, + ArrayList multiLevelListItems, + HSSFCell cell, + int highLevelStartingValue, + int highLevelIncrement, + int lowLevelStartingValue, + int lowLevelIncrement) { + StringBuffer buffer = new StringBuffer(); + int highLevelItemNumber = highLevelStartingValue; + int lowLevelItemNumber = 0; + ArrayList lowerLevelItems = null; + // Note that again, an HSSFCellStye object is required and that + // it's wrap text property should be set to 'true' + HSSFCellStyle wrapStyle = workbook.createCellStyle(); + wrapStyle.setWrapText(true); + // Step through the ArrayList of MultilLevelListItem instances. + for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { + // For each element in the ArrayList, get the text for the high + // level list item...... + buffer.append(String.valueOf(highLevelItemNumber)); + buffer.append(". "); + buffer.append(multiLevelListItem.getItemText()); + buffer.append("\n"); + // and then an ArrayList whose elements encapsulate the text + // for the lower level list items. + lowerLevelItems = multiLevelListItem.getLowerLevelItems(); + if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { + lowLevelItemNumber = lowLevelStartingValue; + for(String item : lowerLevelItems) { + buffer.append(InCellLists.TAB); + buffer.append(String.valueOf(highLevelItemNumber)); + buffer.append("."); + buffer.append(String.valueOf(lowLevelItemNumber)); + buffer.append(" "); + buffer.append(item); + buffer.append("\n"); + lowLevelItemNumber += lowLevelIncrement; + } + } + highLevelItemNumber += highLevelIncrement; + } + // The StringBuffer's contents are the source for the contents + // of the cell. + cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); + cell.setCellStyle(wrapStyle); + } + + /** + * Insert a bulleted multi-level list into a cell. + * + * @param workbook A reference to the HSSFWorkbook that 'contains' the + * cell. + * @param multiLevelListItems An ArrayList whose elements contain instances + * of the MultiLevelListItem class. Each element + * encapsulates the text for the high level item + * along with an ArrayList. Each element of this + * ArrayList encapsulates the text for a lower + * level item. + * @param cell An instance of the HSSFCell class that encapsulates a + * reference to the spreadsheet cell into which the list + * will be written. + */ + public void multiLevelBulletedListInCell(HSSFWorkbook workbook, + ArrayList multiLevelListItems, + HSSFCell cell) { + StringBuffer buffer = new StringBuffer(); + ArrayList lowerLevelItems = null; + // Note that again, an HSSFCellStye object is required and that + // it's wrap text property should be set to 'true' + HSSFCellStyle wrapStyle = workbook.createCellStyle(); + wrapStyle.setWrapText(true); + // Step through the ArrayList of MultilLevelListItem instances. + for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { + // For each element in the ArrayList, get the text for the high + // level list item...... + buffer.append(InCellLists.BULLET_CHARACTER); + buffer.append(" "); + buffer.append(multiLevelListItem.getItemText()); + buffer.append("\n"); + // and then an ArrayList whose elements encapsulate the text + // for the lower level list items. + lowerLevelItems = multiLevelListItem.getLowerLevelItems(); + if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { + for(String item : lowerLevelItems) { + buffer.append(InCellLists.TAB); + buffer.append(InCellLists.BULLET_CHARACTER); + buffer.append(" "); + buffer.append(item); + buffer.append("\n"); + } + } + } + // The StringBuffer's contents are the source for the contents + // of the cell. + cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); + cell.setCellStyle(wrapStyle); + } + + /** + * The main entry point to the program. Demonstrates how to call the method + * that will create an Excel workbook containing many different sorts of + * lists. + * + * @param args the command line arguments. + */ + public static void main(String[] args) { + new InCellLists().demonstrateMethodCalls("C:/temp/Latest In Cell List.xls"); + } + + /** + * An instance of this inner class models an item or element in a + * multi-level list. Each multi-level list item consists of the text for the + * high level items and an ArrayList containing the text for each of the + * associated lower level items. When written into a cell, each multi-level + * list item will have this general appearance. + * + * Item One + * Sub Item One. + * Sub Item Two. + * Item Two + * Sub Item One. + * Sub Item Two. + * etc. + * + * It would be quite possible to modify this class to model much more + * complex list structures descending through two, three or even more + * levels. + */ + public final class MultiLevelListItem { + + private String itemText = null; + private ArrayList lowerLevelItems = null; + + /** + * Create a new instance of the MultiLevelListItem class using the + * following parameters. + * + * @param itemText A String that encapsulates the text for the high + * level list item. + * @param lowerLevelItems An ArrayList whose elements encapsulate the + * text for the associated lower level list + * items. + */ + public MultiLevelListItem(String itemText, ArrayList lowerLevelItems) { + this.itemText = itemText; + this.lowerLevelItems = lowerLevelItems; + } + + /** + * Get the text for the high level list item. + * + * @return A String that encapsulates the text for the high level list + * item. + */ + public String getItemText() { + return(this.itemText); + } + + /** + * Get the text for the associated lower level list items. + * + * @return An ArrayList whose elements each encapsulate the text for a + * single associated lower level list item. + */ + public ArrayList getLowerLevelItems() { + return(this.lowerLevelItems); + } + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/MergedCells.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/MergedCells.java new file mode 100644 index 0000000000..31e5215b8e --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/MergedCells.java @@ -0,0 +1,47 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; + +import java.io.IOException; +import java.io.FileOutputStream; + +/** + * An example of how to merge regions of cells. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class MergedCells { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + + HSSFRow row = sheet.createRow(1); + HSSFCell cell = row.createCell(1); + cell.setCellValue("This is a test of merging"); + + sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2)); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewLinesInCells.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewLinesInCells.java new file mode 100644 index 0000000000..7653a0b527 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewLinesInCells.java @@ -0,0 +1,59 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Demonstrates how to use newlines in cells. + * + * @author Glen Stampoultzis (glens at apache.org) + * @author Fauzia Lala + */ +public class NewLinesInCells { + public static void main( String[] args ) throws IOException { + + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet s = wb.createSheet(); + HSSFRow r = null; + HSSFCell c = null; + HSSFCellStyle cs = wb.createCellStyle(); + HSSFFont f2 = wb.createFont(); + + cs = wb.createCellStyle(); + + cs.setFont(f2); + // Word Wrap MUST be turned on + cs.setWrapText(true); + + r = s.createRow(2); + r.setHeight((short) 0x349); + c = r.createCell(2); + c.setCellType(HSSFCell.CELL_TYPE_STRING); + c.setCellValue("Use \n with word wrap on to create a new line"); + c.setCellStyle(cs); + s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20))); + + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewSheet.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewSheet.java new file mode 100644 index 0000000000..40754feec4 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewSheet.java @@ -0,0 +1,43 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.ss.util.WorkbookUtil; + +import java.io.IOException; +import java.io.FileOutputStream; + +/** + * Creates a new workbook with a sheet that's been explicitly defined. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class NewSheet { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + HSSFSheet sheet2 = wb.createSheet(); // create with default name + final String name = "second sheet"; + wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name)); // setting sheet name later + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewWorkbook.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewWorkbook.java new file mode 100644 index 0000000000..c1614e6c1a --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/NewWorkbook.java @@ -0,0 +1,42 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * This example creates a new blank workbook. This workbook will contain a single blank sheet. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class NewWorkbook +{ + public static void main(String[] args) + throws IOException + { + HSSFWorkbook wb = new HSSFWorkbook(); + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/OfficeDrawing.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/OfficeDrawing.java new file mode 100644 index 0000000000..1b580d35f0 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/OfficeDrawing.java @@ -0,0 +1,321 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; + +import java.io.*; + +/** + * Demonstrates how to use the office drawing capabilities of POI. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class OfficeDrawing { + public static void main(String[] args) throws IOException { + // Create the workbook and sheets. + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + HSSFSheet sheet2 = wb.createSheet("second sheet"); + HSSFSheet sheet3 = wb.createSheet("third sheet"); + HSSFSheet sheet4 = wb.createSheet("fourth sheet"); + HSSFSheet sheet5 = wb.createSheet("fifth sheet"); + + // Draw stuff in them + drawSheet1( sheet1 ); + drawSheet2( sheet2 ); + drawSheet3( sheet3 ); + drawSheet4( sheet4, wb ); + drawSheet5( sheet5, wb ); + + // Write the file out. + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } + + private static void drawSheet1( HSSFSheet sheet1 ) + { + // Create a row and size one of the cells reasonably large. + HSSFRow row = sheet1.createRow(2); + row.setHeight((short) 2800); + row.createCell(1); + sheet1.setColumnWidth(2, 9000); + + // Create the drawing patriarch. This is the top level container for + // all shapes. + HSSFPatriarch patriarch = sheet1.createDrawingPatriarch(); + + // Draw some lines and an oval. + drawLinesToCenter( patriarch ); + drawManyLines( patriarch ); + drawOval( patriarch ); + drawPolygon( patriarch ); + + // Draw a rectangle. + HSSFSimpleShape rect = patriarch.createSimpleShape( new HSSFClientAnchor(100, 100, 900, 200, (short)0, 0, (short)0, 0) ); + rect.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); + } + + private static void drawSheet2( HSSFSheet sheet2 ) + { + // Create a row and size one of the cells reasonably large. + HSSFRow row = sheet2.createRow(2); + row.createCell(1); + row.setHeightInPoints(240); + sheet2.setColumnWidth(2, 9000); + + // Create the drawing patriarch. This is the top level container for + // all shapes. This will clear out any existing shapes for that sheet. + HSSFPatriarch patriarch = sheet2.createDrawingPatriarch(); + + // Draw a grid in one of the cells. + drawGrid( patriarch ); + } + + private static void drawSheet3( HSSFSheet sheet3 ) + { + // Create a row and size one of the cells reasonably large + HSSFRow row = sheet3.createRow(2); + row.setHeightInPoints(140); + row.createCell(1); + sheet3.setColumnWidth(2, 9000); + + // Create the drawing patriarch. This is the top level container for + // all shapes. This will clear out any existing shapes for that sheet. + HSSFPatriarch patriarch = sheet3.createDrawingPatriarch(); + + // Create a shape group. + HSSFShapeGroup group = patriarch.createGroup( + new HSSFClientAnchor(0,0,900,200,(short)2,2,(short)2,2)); + + // Create a couple of lines in the group. + HSSFSimpleShape shape1 = group.createShape(new HSSFChildAnchor(3,3,500,500)); + shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + ( (HSSFChildAnchor) shape1.getAnchor() ).setAnchor((short)3,3,500,500); + HSSFSimpleShape shape2 = group.createShape(new HSSFChildAnchor((short)1,200,400,600)); + shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + + } + + private static void drawSheet4( HSSFSheet sheet4, HSSFWorkbook wb ) + { + // Create the drawing patriarch. This is the top level container for + // all shapes. This will clear out any existing shapes for that sheet. + HSSFPatriarch patriarch = sheet4.createDrawingPatriarch(); + + // Create a couple of textboxes + HSSFTextbox textbox1 = patriarch.createTextbox( + new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)2,2)); + textbox1.setString(new HSSFRichTextString("This is a test") ); + HSSFTextbox textbox2 = patriarch.createTextbox( + new HSSFClientAnchor(0,0,900,100,(short)3,3,(short)3,4)); + textbox2.setString(new HSSFRichTextString("Woo") ); + textbox2.setFillColor(200,0,0); + textbox2.setLineStyle(HSSFSimpleShape.LINESTYLE_DOTGEL); + + // Create third one with some fancy font styling. + HSSFTextbox textbox3 = patriarch.createTextbox( + new HSSFClientAnchor(0,0,900,100,(short)4,4,(short)5,4+1)); + HSSFFont font = wb.createFont(); + font.setItalic(true); + font.setUnderline(HSSFFont.U_DOUBLE); + HSSFRichTextString string = new HSSFRichTextString("Woo!!!"); + string.applyFont(2,5,font); + textbox3.setString(string ); + textbox3.setFillColor(0x08000030); + textbox3.setLineStyle(HSSFSimpleShape.LINESTYLE_NONE); // no line around the textbox. + textbox3.setNoFill(true); // make it transparent + } + + private static void drawSheet5( HSSFSheet sheet5, HSSFWorkbook wb ) throws IOException + { + + // Create the drawing patriarch. This is the top level container for + // all shapes. This will clear out any existing shapes for that sheet. + HSSFPatriarch patriarch = sheet5.createDrawingPatriarch(); + + HSSFClientAnchor anchor; + anchor = new HSSFClientAnchor(0,0,0,255,(short)2,2,(short)4,7); + anchor.setAnchorType( 2 ); + patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4.png", wb )); + + anchor = new HSSFClientAnchor(0,0,0,255,(short)4,2,(short)5,7); + anchor.setAnchorType( 2 ); + patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4edited.png", wb )); + + anchor = new HSSFClientAnchor(0,0,1023,255,(short)6,2,(short)8,7); + anchor.setAnchorType( 2 ); + HSSFPicture picture = patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4s.png", wb )); + //Reset the image to the original size. + picture.resize(); + picture.setLineStyle( picture.LINESTYLE_DASHDOTGEL ); + + } + + private static int loadPicture( String path, HSSFWorkbook wb ) throws IOException + { + int pictureIndex; + FileInputStream fis = null; + ByteArrayOutputStream bos = null; + try + { + fis = new FileInputStream( path); + bos = new ByteArrayOutputStream( ); + int c; + while ( (c = fis.read()) != -1) + bos.write( c ); + pictureIndex = wb.addPicture( bos.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG ); + } + finally + { + if (fis != null) + fis.close(); + if (bos != null) + bos.close(); + } + return pictureIndex; + } + + private static void drawOval( HSSFPatriarch patriarch ) + { + // Create an oval and style to taste. + HSSFClientAnchor a = new HSSFClientAnchor(); + a.setAnchor((short)2, 2, 20, 20, (short) 2, 2, 190, 80); + HSSFSimpleShape s = patriarch.createSimpleShape(a); + s.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL); + s.setLineStyleColor(10,10,10); + s.setFillColor(90,10,200); + s.setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3); + s.setLineStyle(HSSFShape.LINESTYLE_DOTSYS); + } + + private static void drawPolygon( HSSFPatriarch patriarch ) + { + // HSSFClientAnchor a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 2, 2, (short) 3, 3 ); + // HSSFPolygon p = patriarch.createPolygon(a); + // p.setPolygonDrawArea(100,100); + // p.setPoints( new int[]{30, 90, 50}, new int[]{88, 5, 44} ); + + + HSSFClientAnchor a = new HSSFClientAnchor(); + a.setAnchor( (short) 2, 2, 0, 0, (short) 3, 3, 1023, 255 ); + HSSFShapeGroup g = patriarch.createGroup( a ); + g.setCoordinates(0,0,200,200); + HSSFPolygon p1 = g.createPolygon( new HSSFChildAnchor( 0, 0, 200, 200 ) ); + p1.setPolygonDrawArea( 100, 100 ); + p1.setPoints( new int[]{0, 90, 50}, new int[]{5, 5, 44} ); + p1.setFillColor( 0, 255, 0 ); + HSSFPolygon p2 = g.createPolygon( new HSSFChildAnchor( 20, 20, 200, 200 ) ); + p2.setPolygonDrawArea( 200, 200 ); + p2.setPoints( new int[]{120, 20, 150}, new int[]{105, 30, 195} ); + p2.setFillColor( 255, 0, 0 ); + } + + private static void drawManyLines( HSSFPatriarch patriarch ) + { + // Draw bunch of lines + int x1 = 100; + int y1 = 100; + int x2 = 800; + int y2 = 200; + int color = 0; + for (int i = 0; i < 10; i++) + { + HSSFClientAnchor a2 = new HSSFClientAnchor(); + a2.setAnchor((short) 2, 2, x1, y1, (short) 2, 2, x2, y2); + HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); + shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + shape2.setLineStyleColor(color); + y1 -= 10; + y2 -= 10; + color += 30; + } + } + + private static void drawGrid( HSSFPatriarch patriarch ) + { + // This draws a grid of lines. Since the coordinates space fixed at + // 1024 by 256 we use a ratio to get a reasonably square grids. + + double xRatio = 3.22; + double yRatio = 0.6711; + + int x1 = 000; + int y1 = 000; + int x2 = 000; + int y2 = 200; + for (int i = 0; i < 20; i++) + { + HSSFClientAnchor a2 = new HSSFClientAnchor(); + a2.setAnchor((short) 2, 2, (int) ( x1 * xRatio ), (int) ( y1 * yRatio ), + (short) 2, 2, (int) ( x2 * xRatio ), (int) ( y2 * yRatio )); + HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); + shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + + x1 += 10; + x2 += 10; + } + + x1 = 000; + y1 = 000; + x2 = 200; + y2 = 000; + for (int i = 0; i < 20; i++) + { + HSSFClientAnchor a2 = new HSSFClientAnchor(); + a2.setAnchor((short) 2, 2, (int) ( x1 * xRatio ), (int) ( y1 * yRatio ), + (short) 2, 2, (int) ( x2 * xRatio ), (int) ( y2 * yRatio )); + HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); + shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + + y1 += 10; + y2 += 10; + } + } + + private static void drawLinesToCenter( HSSFPatriarch patriarch ) + { + // Draw some lines from and to the corners + { + HSSFClientAnchor a1 = new HSSFClientAnchor(); + a1.setAnchor( (short)2, 2, 0, 0, (short) 2, 2, 512, 128); + HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); + shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + } + { + HSSFClientAnchor a1 = new HSSFClientAnchor(); + a1.setAnchor( (short)2, 2, 512, 128, (short) 2, 2, 1024, 0); + HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); + shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + } + { + HSSFClientAnchor a1 = new HSSFClientAnchor(); + a1.setAnchor( (short)1, 1, 0, 0, (short) 1, 1, 512, 100); + HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); + shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + } + { + HSSFClientAnchor a1 = new HSSFClientAnchor(); + a1.setAnchor( (short)1, 1, 512, 100, (short) 1, 1, 1024, 0); + HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); + shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); + } + + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java new file mode 100644 index 0000000000..4de1207f42 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java @@ -0,0 +1,103 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; + +import java.awt.*; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Demonstrates the use of the EscherGraphics2d library. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class OfficeDrawingWithGraphics { + public static void main( String[] args ) throws IOException { + // Create a workbook with one sheet and size the first three somewhat + // larger so we can fit the chemical structure diagram in. + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet( "my drawing" ); + sheet.setColumnWidth(1, 256 * 27); + HSSFRow row1 = sheet.createRow(0); + row1.setHeightInPoints(10 * 15); + HSSFRow row2 = sheet.createRow(1); + row2.setHeightInPoints(5 * 15); + HSSFRow row3 = sheet.createRow(2); + row3.setHeightInPoints(10 * 15); + + // Add some cells so we can test that the anchoring works when we + // sort them. + row1.createCell(0).setCellValue("C"); + row2.createCell(0).setCellValue("A"); + row3.createCell(0).setCellValue("B"); + + // Create the top level drawing patriarch. + HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); + + HSSFClientAnchor a; + HSSFShapeGroup group; + EscherGraphics g; + EscherGraphics2d g2d; + // Anchor entirely within one cell. + a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 ); + group = patriarch.createGroup( a ); + group.setCoordinates( 0, 0, 320, 276 ); + float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1()); + g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel ); + g2d = new EscherGraphics2d( g ); + drawStar( g2d ); + + a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 1, (short) 1, 1 ); + group = patriarch.createGroup( a ); + group.setCoordinates( 0, 0, 640, 276 ); + verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1()); +// verticalPixelsPerPoint = (float)Math.abs(group.getY2() - group.getY1()) / a.getAnchorHeightInPoints(sheet); + g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel ); + g2d = new EscherGraphics2d( g ); + drawStar( g2d ); + + FileOutputStream out = new FileOutputStream("workbook.xls"); + wb.write(out); + out.close(); + + } + + private static void drawStar( EscherGraphics2d g2d ) + { + g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); + for (double i = 0; i < Math.PI; i += 0.1) + { + g2d.setColor( new Color((int)(i * 5343062d) ) ); + int x1 = (int) ( Math.cos(i) * 160.0 ) + 160; + int y1 = (int) ( Math.sin(i) * 138.0 ) + 138; + int x2 = (int) ( -Math.cos(i) * 160.0 ) + 160; + int y2 = (int) ( -Math.sin(i) * 138.0 ) + 138; + g2d.setStroke(new BasicStroke(2)); + g2d.drawLine(x1,y1,x2,y2); + } + g2d.setFont(new Font("SansSerif",Font.BOLD | Font.ITALIC, 20)); + g2d.drawString("EscherGraphics2d",70,100); + g2d.setColor(Color.yellow); + g2d.fillOval( 160-20,138-20,40,40); + g2d.setColor(Color.black); + g2d.fillPolygon(new int[] {-10+160,0+160,10+160,0+160}, new int[] {0+138,10+138,0+138,-10+138}, 4); + g2d.drawPolygon(new int[] {-160+160,0+160,160+160,0+160}, new int[] {0+138,138+138,0+138,-138+138}, 4); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/Outlines.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/Outlines.java new file mode 100644 index 0000000000..c04d608ed0 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/Outlines.java @@ -0,0 +1,259 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFCell; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Creates outlines. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class Outlines { + public static void main(String[] args) throws IOException { + createCase1( "outline1.xls" ); + System.out.println( "outline1.xls written. Two expanded groups." ); + createCase2( "outline2.xls" ); + System.out.println( "outline2.xls written. Two groups. Inner group collapsed." ); + createCase3( "outline3.xls" ); + System.out.println( "outline3.xls written. Two groups. Both collapsed." ); + createCase4( "outline4.xls" ); + System.out.println( "outline4.xls written. Two groups. Collapsed then inner group expanded." ); + createCase5( "outline5.xls" ); + System.out.println( "outline5.xls written. Two groups. Collapsed then reexpanded." ); + createCase6( "outline6.xls" ); + System.out.println( "outline6.xls written. Two groups with matching end points. Second group collapsed." ); + createCase7( "outline7.xls" ); + System.out.println( "outline7.xls written. Row outlines." ); + createCase8( "outline8.xls" ); + System.out.println( "outline8.xls written. Row outlines. Inner group collapsed." ); + createCase9( "outline9.xls" ); + System.out.println( "outline9.xls written. Row outlines. Both collapsed." ); + createCase10( "outline10.xls" ); + System.out.println( "outline10.xls written. Row outlines. Collapsed then inner group expanded." ); + createCase11( "outline11.xls" ); + System.out.println( "outline11.xls written. Row outlines. Collapsed then expanded." ); + createCase12( "outline12.xls" ); + System.out.println( "outline12.xls written. Row outlines. Two row groups with matching end points. Second group collapsed." ); + createCase13( "outline13.xls" ); + System.out.println( "outline13.xls written. Mixed bag." ); + } + + private static void createCase1(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupColumn(4, 7); + + for (int row = 0; row < 200; row++) { + HSSFRow r = sheet1.createRow(row); + for (int column = 0; column < 200; column++) { + HSSFCell c = r.createCell(column); + c.setCellValue(column); + } + } + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase2(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupColumn(2, 10); + sheet1.groupColumn(4, 7); + sheet1.setColumnGroupCollapsed(4, true); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase3(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupColumn(2, 10); + sheet1.groupColumn(4, 7); + sheet1.setColumnGroupCollapsed(4, true); + sheet1.setColumnGroupCollapsed(2, true); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase4(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupColumn(2, 10); + sheet1.groupColumn(4, 7); + sheet1.setColumnGroupCollapsed(4, true); + sheet1.setColumnGroupCollapsed(2, true); + + sheet1.setColumnGroupCollapsed(4, false); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase5(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupColumn(2, 10); + sheet1.groupColumn(4, 7); + sheet1.setColumnGroupCollapsed(4, true); + sheet1.setColumnGroupCollapsed(2, true); + + sheet1.setColumnGroupCollapsed(4, false); + sheet1.setColumnGroupCollapsed(3, false); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase6(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupColumn(2, 10); + sheet1.groupColumn(4, 10); + sheet1.setColumnGroupCollapsed(4, true); + sheet1.setColumnGroupCollapsed(2, true); + + sheet1.setColumnGroupCollapsed(3, false); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase7(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupRow(5, 14); + sheet1.groupRow(7, 10); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase8(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupRow(5, 14); + sheet1.groupRow(7, 10); + sheet1.setRowGroupCollapsed(7, true); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase9(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupRow(5, 14); + sheet1.groupRow(7, 10); + sheet1.setRowGroupCollapsed(7, true); + sheet1.setRowGroupCollapsed(5, true); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase10(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupRow(5, 14); + sheet1.groupRow(7, 10); + sheet1.setRowGroupCollapsed(7, true); + sheet1.setRowGroupCollapsed(5, true); + sheet1.setRowGroupCollapsed(8, false); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase11(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupRow(5, 14); + sheet1.groupRow(7, 10); + sheet1.setRowGroupCollapsed(7, true); + sheet1.setRowGroupCollapsed(5, true); + sheet1.setRowGroupCollapsed(8, false); + sheet1.setRowGroupCollapsed(14, false); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase12(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupRow(5, 14); + sheet1.groupRow(7, 14); + sheet1.setRowGroupCollapsed(7, true); + sheet1.setRowGroupCollapsed(5, true); + sheet1.setRowGroupCollapsed(6, false); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } + + private static void createCase13(String filename) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupRow(5, 14); + sheet1.groupRow(7, 14); + sheet1.groupRow(16, 19); + + sheet1.groupColumn(4, 7); + sheet1.groupColumn(9, 12); + sheet1.groupColumn(10, 11); + + FileOutputStream fileOut = new FileOutputStream(filename); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/ReadWriteWorkbook.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/ReadWriteWorkbook.java new file mode 100644 index 0000000000..26bba44674 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/ReadWriteWorkbook.java @@ -0,0 +1,66 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFCell; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * This example demonstrates opening a workbook, modifying it and writing + * the results back out. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class ReadWriteWorkbook { + public static void main(String[] args) throws IOException { + FileInputStream fileIn = null; + FileOutputStream fileOut = null; + + try + { + fileIn = new FileInputStream("workbook.xls"); + POIFSFileSystem fs = new POIFSFileSystem(fileIn); + HSSFWorkbook wb = new HSSFWorkbook(fs); + HSSFSheet sheet = wb.getSheetAt(0); + HSSFRow row = sheet.getRow(2); + if (row == null) + row = sheet.createRow(2); + HSSFCell cell = row.getCell(3); + if (cell == null) + cell = row.createCell(3); + cell.setCellType(HSSFCell.CELL_TYPE_STRING); + cell.setCellValue("a test"); + + // Write the output to a file + fileOut = new FileOutputStream("workbookout.xls"); + wb.write(fileOut); + } finally { + if (fileOut != null) + fileOut.close(); + if (fileIn != null) + fileIn.close(); + } + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java new file mode 100644 index 0000000000..df4e3bb64c --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java @@ -0,0 +1,58 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; + +import java.io.IOException; +import java.io.FileOutputStream; + +/** + * @author Glen Stampoultzis (glens at apache.org) + */ +public class RepeatingRowsAndColumns { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("first sheet"); + wb.createSheet("second sheet"); + wb.createSheet("third sheet"); + + HSSFFont boldFont = wb.createFont(); + boldFont.setFontHeightInPoints((short)22); + boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + + HSSFCellStyle boldStyle = wb.createCellStyle(); + boldStyle.setFont(boldFont); + + HSSFRow row = sheet1.createRow(1); + HSSFCell cell = row.createCell(0); + cell.setCellValue("This quick brown fox"); + cell.setCellStyle(boldStyle); + + // Set the columns to repeat from column 0 to 2 on the first sheet + wb.setRepeatingRowsAndColumns(0,0,2,-1,-1); + // Set the rows to repeat from row 0 to 2 on the second sheet. + wb.setRepeatingRowsAndColumns(1,-1,-1,0,2); + // Set the the repeating rows and columns on the third sheet. + wb.setRepeatingRowsAndColumns(2,4,5,1,2); + + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/SplitAndFreezePanes.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/SplitAndFreezePanes.java new file mode 100644 index 0000000000..6e93a317f0 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/SplitAndFreezePanes.java @@ -0,0 +1,55 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFSheet; + +import java.io.IOException; +import java.io.FileOutputStream; + +/** + * @author Glen Stampoultzis (glens at apache.org) + */ +public class SplitAndFreezePanes +{ + public static void main(String[] args) + throws IOException + { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + HSSFSheet sheet2 = wb.createSheet("second sheet"); + HSSFSheet sheet3 = wb.createSheet("third sheet"); + HSSFSheet sheet4 = wb.createSheet("fourth sheet"); + + // Freeze just one row + sheet1.createFreezePane( 0, 1, 0, 1 ); + // Freeze just one column + sheet2.createFreezePane( 1, 0, 1, 0 ); + // Freeze the columns and rows (forget about scrolling position of the lower right quadrant). + sheet3.createFreezePane( 2, 2 ); + // Create a split with the lower left side being the active quadrant + sheet4.createSplitPane( 2000, 2000, 0, 0, HSSFSheet.PANE_LOWER_LEFT ); + + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/WorkingWithFonts.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/WorkingWithFonts.java new file mode 100644 index 0000000000..6cb15941f2 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/WorkingWithFonts.java @@ -0,0 +1,59 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.*; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Demonstrates how to create and use fonts. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class WorkingWithFonts { + public static void main(String[] args) throws IOException { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet = wb.createSheet("new sheet"); + + // Create a row and put some cells in it. Rows are 0 based. + HSSFRow row = sheet.createRow(1); + + // Create a new font and alter it. + HSSFFont font = wb.createFont(); + font.setFontHeightInPoints((short)24); + font.setFontName("Courier New"); + font.setItalic(true); + font.setStrikeout(true); + + // Fonts are set into a style so create a new one to use. + HSSFCellStyle style = wb.createCellStyle(); + style.setFont(font); + + // Create a cell and put a value in it. + HSSFCell cell = row.createCell(1); + cell.setCellValue("This is a test of fonts"); + cell.setCellStyle(style); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/usermodel/examples/ZoomSheet.java b/poi-examples/src/main/java/poi/hssf/usermodel/examples/ZoomSheet.java new file mode 100644 index 0000000000..c65c62f18f --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/usermodel/examples/ZoomSheet.java @@ -0,0 +1,45 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.hssf.usermodel.examples; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFSheet; + +import java.io.IOException; +import java.io.FileOutputStream; + +/** + * Sets the zoom magnication for a sheet. + * + * @author Glen Stampoultzis (glens at apache.org) + */ +public class ZoomSheet +{ + public static void main(String[] args) + throws IOException + { + HSSFWorkbook wb = new HSSFWorkbook(); + HSSFSheet sheet1 = wb.createSheet("new sheet"); + sheet1.setZoom(3,4); // 75 percent magnification + FileOutputStream fileOut = new FileOutputStream("workbook.xls"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SVBorder.java b/poi-examples/src/main/java/poi/hssf/view/SVBorder.java new file mode 100644 index 0000000000..083b9cc18e --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SVBorder.java @@ -0,0 +1,564 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.view; + +import java.awt.*; + +import javax.swing.border.AbstractBorder; + +import org.apache.poi.hssf.usermodel.HSSFCellStyle; + +/** + * This is an attempt to implement Excel style borders for the SheetViewer. + * Mostly just overrides stuff so the javadoc won't appear here but will + * appear in the generated stuff. + * + * @author Andrew C. Oliver (acoliver at apache dot org) + * @author Jason Height + */ +public class SVBorder extends AbstractBorder { + private Color northColor = null; + private Color eastColor = null; + private Color southColor = null; + private Color westColor = null; + private int northBorderType = HSSFCellStyle.BORDER_NONE; + private int eastBorderType =HSSFCellStyle.BORDER_NONE; + private int southBorderType = HSSFCellStyle.BORDER_NONE; + private int westBorderType = HSSFCellStyle.BORDER_NONE; + private boolean northBorder=false; + private boolean eastBorder=false; + private boolean southBorder=false; + private boolean westBorder=false; + private boolean selected = false; + + public void setBorder(Color northColor, Color eastColor, + Color southColor, Color westColor, + int northBorderType, int eastBorderType, + int southBorderType, int westBorderType, + boolean selected) { + this.eastColor = eastColor; + this.southColor = southColor; + this.westColor = westColor; + this.northBorderType = northBorderType; + this.eastBorderType = eastBorderType; + this.southBorderType = southBorderType; + this.westBorderType = westBorderType; + this.northBorder=northBorderType != HSSFCellStyle.BORDER_NONE; + this.eastBorder=eastBorderType != HSSFCellStyle.BORDER_NONE; + this.southBorder=southBorderType != HSSFCellStyle.BORDER_NONE; + this.westBorder=westBorderType != HSSFCellStyle.BORDER_NONE; + this.selected = selected; + } + + public void paintBorder(Component c, Graphics g, int x, int y, int width, + int height) { + Color oldColor = g.getColor(); + + + paintSelectedBorder(g, x, y, width, height); + paintNormalBorders(g, x, y, width, height); + paintDottedBorders(g, x, y, width, height); + paintDashedBorders(g, x, y, width, height); + paintDoubleBorders(g, x, y, width, height); + paintDashDotDotBorders(g, x, y, width, height); + + + g.setColor(oldColor); + } + + /** + * Called by paintBorder to paint the border of a selected cell. + * The paramaters are the Graphics object, location and dimensions of the + * cell. + */ + private void paintSelectedBorder(Graphics g, int x, int y, int width, + int height) { + if (selected) { + //Need to setup thickness of 2 + g.setColor(Color.black); + //paint the border + g.drawRect(x,y,width-1,height-1); + + //paint the filled rectangle at the bottom left hand position + g.fillRect(x+width-5, y+height-5, 5, 5); + } + } + + + /** + * Called by paintBorder to paint the various versions of normal line + * borders for a cell. + */ + private void paintNormalBorders(Graphics g, int x, int y, int width, + int height) { + + if (northBorder && + ((northBorderType == HSSFCellStyle.BORDER_THIN) || + (northBorderType == HSSFCellStyle.BORDER_MEDIUM) || + (northBorderType == HSSFCellStyle.BORDER_THICK) + ) + ) { + + int thickness = getThickness(northBorderType); + + g.setColor(northColor); + + for (int k=0; k < thickness; k++) { + g.drawLine(x,y+k,width,y+k); + } + } + + if (eastBorder && + ((eastBorderType == HSSFCellStyle.BORDER_THIN) || + (eastBorderType == HSSFCellStyle.BORDER_MEDIUM) || + (eastBorderType == HSSFCellStyle.BORDER_THICK) + ) + ) { + + int thickness = getThickness(eastBorderType); + + g.setColor(eastColor); + + for (int k=0; k < thickness; k++) { + g.drawLine(width-k,y,width-k,height); + } + } + + if (southBorder && + ((southBorderType == HSSFCellStyle.BORDER_THIN) || + (southBorderType == HSSFCellStyle.BORDER_MEDIUM) || + (southBorderType == HSSFCellStyle.BORDER_THICK) + ) + ) { + + int thickness = getThickness(southBorderType); + + g.setColor(southColor); + for (int k=0; k < thickness; k++) { + g.drawLine(x,height - k,width,height - k); + } + } + + if (westBorder && + ((westBorderType == HSSFCellStyle.BORDER_THIN) || + (westBorderType == HSSFCellStyle.BORDER_MEDIUM) || + (westBorderType == HSSFCellStyle.BORDER_THICK) + ) + ) { + + int thickness = getThickness(westBorderType); + + g.setColor(westColor); + + for (int k=0; k < thickness; k++) { + g.drawLine(x+k,y,x+k,height); + } + } + } + + /** + * Called by paintBorder to paint the dotted line + * borders for a cell. + */ + private void paintDottedBorders(Graphics g, int x, int y, int width, + int height) { + if (northBorder && + northBorderType == HSSFCellStyle.BORDER_DOTTED) { + int thickness = getThickness(northBorderType); + + g.setColor(northColor); + + for (int k=0; k < thickness; k++) { + for (int xc = x; xc < width; xc=xc+2) { + g.drawLine(xc,y+k,xc,y+k); + } + } + } + + if (eastBorder && + eastBorderType == HSSFCellStyle.BORDER_DOTTED + ) { + + int thickness = getThickness(eastBorderType); + thickness++; //need for dotted borders to show up east + + g.setColor(eastColor); + + for (int k=0; k < thickness; k++) { + for (int yc=y;yc < height; yc=yc+2) { + g.drawLine(width-k,yc,width-k,yc); + } + } + } + + if (southBorder && + southBorderType == HSSFCellStyle.BORDER_DOTTED + ) { + + int thickness = getThickness(southBorderType); + thickness++; + g.setColor(southColor); + for (int k=0; k < thickness; k++) { + for (int xc = x; xc < width; xc=xc+2) { + g.drawLine(xc,height-k,xc,height-k); + } + } + } + + if (westBorder && + westBorderType == HSSFCellStyle.BORDER_DOTTED + ) { + + int thickness = getThickness(westBorderType); +// thickness++; + + g.setColor(westColor); + + for (int k=0; k < thickness; k++) { + for (int yc=y;yc < height; yc=yc+2) { + g.drawLine(x+k,yc,x+k,yc); + } + } + } + } + + /** + * Called by paintBorder to paint the various versions of dotted line + * borders for a cell. + */ + private void paintDashedBorders(Graphics g, int x, int y, int width, + int height) { + if (northBorder && + ((northBorderType == HSSFCellStyle.BORDER_DASHED) || + (northBorderType == HSSFCellStyle.BORDER_HAIR)) + ) { + int thickness = getThickness(northBorderType); + + int dashlength = 1; + + if (northBorderType == HSSFCellStyle.BORDER_DASHED) + dashlength = 2; + + g.setColor(northColor); + + for (int k=0; k < thickness; k++) { + for (int xc = x; xc < width; xc=xc+5) { + g.drawLine(xc,y+k,xc+dashlength,y+k); + } + } + } + + if (eastBorder && + ((eastBorderType == HSSFCellStyle.BORDER_DASHED) || + (eastBorderType == HSSFCellStyle.BORDER_HAIR)) + ) { + + int thickness = getThickness(eastBorderType); + thickness++; //need for dotted borders to show up east + + + int dashlength = 1; + + if (eastBorderType == HSSFCellStyle.BORDER_DASHED) + dashlength = 2; + + g.setColor(eastColor); + + for (int k=0; k < thickness; k++) { + for (int yc=y;yc < height; yc=yc+5) { + g.drawLine(width-k,yc,width-k,yc+dashlength); + } + } + } + + if (southBorder && + ((southBorderType == HSSFCellStyle.BORDER_DASHED) || + (southBorderType == HSSFCellStyle.BORDER_HAIR)) + ) { + + int thickness = getThickness(southBorderType); + thickness++; + + int dashlength = 1; + + if (southBorderType == HSSFCellStyle.BORDER_DASHED) + dashlength = 2; + + g.setColor(southColor); + for (int k=0; k < thickness; k++) { + for (int xc = x; xc < width; xc=xc+5) { + g.drawLine(xc,height-k,xc+dashlength,height-k); + } + } + } + + if (westBorder && + ((westBorderType == HSSFCellStyle.BORDER_DASHED) || + (westBorderType == HSSFCellStyle.BORDER_HAIR)) + ) { + + int thickness = getThickness(westBorderType); +// thickness++; + + int dashlength = 1; + + if (westBorderType == HSSFCellStyle.BORDER_DASHED) + dashlength = 2; + + g.setColor(westColor); + + for (int k=0; k < thickness; k++) { + for (int yc=y;yc < height; yc=yc+5) { + g.drawLine(x+k,yc,x+k,yc+dashlength); + } + } + } + } + + /** + * Called by paintBorder to paint the double line + * borders for a cell. + */ + private void paintDoubleBorders(Graphics g, int x, int y, int width, + int height) { + if (northBorder && + northBorderType == HSSFCellStyle.BORDER_DOUBLE) { + + g.setColor(northColor); + + int leftx=x; + int rightx=width; + + // if there are borders on the west or east then + // the second line shouldn't cross them + if (westBorder) + leftx = x+3; + + if (eastBorder) + rightx = width-3; + + g.drawLine(x,y,width,y); + g.drawLine(leftx,y+2,rightx,y+2); + } + + if (eastBorder && + eastBorderType == HSSFCellStyle.BORDER_DOUBLE + ) { + + int thickness = getThickness(eastBorderType); + thickness++; //need for dotted borders to show up east + + g.setColor(eastColor); + + int topy=y; + int bottomy=height; + + if (northBorder) + topy=y+3; + + if (southBorder) + bottomy=height-3; + + g.drawLine(width-1,y,width-1,height); + g.drawLine(width-3,topy,width-3,bottomy); + } + + if (southBorder && + southBorderType == HSSFCellStyle.BORDER_DOUBLE + ) { + + g.setColor(southColor); + + int leftx=y; + int rightx=width; + + if (westBorder) + leftx=x+3; + + if (eastBorder) + rightx=width-3; + + + g.drawLine(x,height - 1,width,height - 1); + g.drawLine(leftx,height - 3,rightx,height - 3); + } + + if (westBorder && + westBorderType == HSSFCellStyle.BORDER_DOUBLE + ) { + + int thickness = getThickness(westBorderType); +// thickness++; + + g.setColor(westColor); + + int topy=y; + int bottomy=height-3; + + if (northBorder) + topy=y+2; + + if (southBorder) + bottomy=height-3; + + g.drawLine(x,y,x,height); + g.drawLine(x+2,topy,x+2,bottomy); + } + } + + /** + * Called by paintBorder to paint the various versions of dash dot dot line + * borders for a cell. + */ + private void paintDashDotDotBorders(Graphics g, int x, int y, int width, + int height) { + if (northBorder && + ((northBorderType == HSSFCellStyle.BORDER_DASH_DOT_DOT) || + (northBorderType == HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT)) + ) { + int thickness = getThickness(northBorderType); + + g.setColor(northColor); + for (int l=x; l < width;) { + l=l+drawDashDotDot(g, l, y, thickness, true, true); + } + + } + + if (eastBorder && + ((eastBorderType == HSSFCellStyle.BORDER_DASH_DOT_DOT) || + (eastBorderType == HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT)) + ) { + + int thickness = getThickness(eastBorderType); + + g.setColor(eastColor); + + for (int l=y;l < height;) { + //System.err.println("drawing east"); + l=l+drawDashDotDot(g,width-1,l,thickness,false,false); + } + } + + if (southBorder && + ((southBorderType == HSSFCellStyle.BORDER_DASH_DOT_DOT) || + (southBorderType == HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT)) + ) { + + int thickness = getThickness(southBorderType); + + g.setColor(southColor); + + for (int l=x; l < width;) { + //System.err.println("drawing south"); + l=l+drawDashDotDot(g, l, height-1, thickness, true, false); + } + } + + if (westBorder && + ((westBorderType == HSSFCellStyle.BORDER_DASH_DOT_DOT) || + (westBorderType == HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT)) + ) { + + int thickness = getThickness(westBorderType); + + g.setColor(westColor); + + for (int l=y;l < height;) { + //System.err.println("drawing west"); + l=l+drawDashDotDot(g,x,l,thickness,false,true); + } + + } + } + + /** + * Draws one dash dot dot horizontally or vertically with thickness drawn + * incrementally to either the right or left. + * + * @param g graphics object for drawing with + * @param x the x origin of the line + * @param y the y origin of the line + * @param thickness the thickness of the line + * @param horizontal or vertical (true for horizontal) + * @param right/bottom or left/top thickness (true for right or top), + * if true then the x or y origin will be incremented to provide + * thickness, if false, they'll be decremented. For vertical + * borders, x is incremented or decremented, for horizontal its y. + * Just set to true for north and west, and false for east and + * south. + * @returns length - returns the length of the line. + */ + private int drawDashDotDot(Graphics g,int x, int y, int thickness, + boolean horizontal, + boolean rightBottom) { + + for (int t=0; t < thickness; t++) { + if (!rightBottom) { + t = 0 - t; //add negative thickness so we go the other way + //then we'll decrement instead of increment. + } + if (horizontal) { + g.drawLine(x,y+t,x+5,y+t); + g.drawLine(x+8,y+t,x+10,y+t); + g.drawLine(x+13,y+t,x+15,y+t); + } else { + g.drawLine(x+t,y,x+t,y+5); + g.drawLine(x+t,y+8,x+t,y+10); + g.drawLine(x+t,y+13,x+t,y+15); + } + } + return 18; + } + + /** + * @returns the line thickness for a border based on border type + */ + private int getThickness(int thickness) { + int retval=1; + switch (thickness) { + case HSSFCellStyle.BORDER_THIN: + retval=2; + break; + case HSSFCellStyle.BORDER_MEDIUM: + retval=3; + break; + case HSSFCellStyle.BORDER_THICK: + retval=4; + break; + case HSSFCellStyle.BORDER_DASHED: + retval=1; + break; + case HSSFCellStyle.BORDER_DASH_DOT_DOT: + retval=1; + break; + case HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT: + retval=3; + break; + case HSSFCellStyle.BORDER_HAIR: + retval=1; + break; + default: + retval=1; + } + return retval; + } + + +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SVFractionalFormat.java b/poi-examples/src/main/java/poi/hssf/view/SVFractionalFormat.java new file mode 100644 index 0000000000..cd6ff6ea72 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SVFractionalFormat.java @@ -0,0 +1,220 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.hssf.view; + +import java.text.*; + +/** + * This class is used to format cells into their fractional format. + * + * I cant be 100% sure that the same fractional value will be displayed as in + * excel but then again it is a lossy formating mode anyway + * + * @author Jason Height + * @since 15 July 2002 + */ +public class SVFractionalFormat extends Format { + private short ONE_DIGIT = 1; + private short TWO_DIGIT = 2; + private short THREE_DIGIT = 3; + private short UNITS = 4; + private int units = 1; + private short mode = -1; + + /** Constructs a new FractionalFormatter + * + * The formatStr defines how the number will be formatted + * # ?/? Up to one digit + * # ??/?? Up to two digits + * # ???/??? Up to three digits + * # ?/2 In halves + * # ?/4 In quarters + * # ?/8 In eighths + * # ?/16 In sixteenths + * # ?/10 In tenths + * # ?/100 In hundredths + */ + public SVFractionalFormat(String formatStr) { + if ("# ?/?".equals(formatStr)) + mode = ONE_DIGIT; + else if ("# ??/??".equals(formatStr)) + mode = TWO_DIGIT; + else if ("# ???/???".equals(formatStr)) + mode = THREE_DIGIT; + else if ("# ?/2".equals(formatStr)) { + mode = UNITS; + units = 2; + } else if ("# ?/4".equals(formatStr)) { + mode = UNITS; + units = 4; + } else if ("# ?/8".equals(formatStr)) { + mode = UNITS; + units = 8; + } else if ("# ?/16".equals(formatStr)) { + mode = UNITS; + units = 16; + } else if ("# ?/10".equals(formatStr)) { + mode = UNITS; + units = 10; + } else if ("# ?/100".equals(formatStr)) { + mode = UNITS; + units = 100; + } + } + + /** + * Returns a fractional string representation of a double to a maximum denominator size + * + * This code has been translated to java from the following web page. + * http://www.codeproject.com/cpp/fraction.asp + * Originally coded in c++ By Dean Wyant dwyant@mindspring.com + * The code on the web page is freely available. + * + * @param f Description of the Parameter + * @param MaxDen Description of the Parameter + * @return Description of the Return Value + */ + private String format(final double f, final int MaxDen) { + long Whole = (long)f; + int sign = 1; + if (f < 0) { + sign = -1; + } + double Precision = 0.00001; + double AllowedError = Precision; + double d = Math.abs(f); + d -= Whole; + double Frac = d; + double Diff = Frac; + long Num = 1; + long Den = 0; + long A = 0; + long B = 0; + long i = 0; + if (Frac > Precision) { + while (true) { + d = 1.0 / d; + i = (long) (d + Precision); + d -= i; + if (A > 0) { + Num = i * Num + B; + } + Den = (long) (Num / Frac + 0.5); + Diff = Math.abs((double) Num / Den - Frac); + if (Den > MaxDen) { + if (A > 0) { + Num = A; + Den = (long) (Num / Frac + 0.5); + Diff = Math.abs((double) Num / Den - Frac); + } else { + Den = MaxDen; + Num = 1; + Diff = Math.abs((double) Num / Den - Frac); + if (Diff > Frac) { + Num = 0; + Den = 1; + // Keeps final check below from adding 1 and keeps Den from being 0 + Diff = Frac; + } + } + break; + } + if ((Diff <= AllowedError) || (d < Precision)) { + break; + } + Precision = AllowedError / Diff; + // This calcualtion of Precision does not always provide results within + // Allowed Error. It compensates for loss of significant digits that occurs. + // It helps to round the inprecise reciprocal values to i. + B = A; + A = Num; + } + } + if (Num == Den) { + Whole++; + Num = 0; + Den = 0; + } else if (Den == 0) { + Num = 0; + } + if (sign < 0) { + if (Whole == 0) { + Num = -Num; + } else { + Whole = -Whole; + } + } + return new StringBuffer().append(Whole).append(" ").append(Num).append("/").append(Den).toString(); + } + + /** This method formats the double in the units specified. + * The usints could be any number but in this current implementation it is + * halves (2), quaters (4), eigths (8) etc + */ + private String formatUnit(double f, int units) { + long Whole = (long)f; + f -= Whole; + long Num = Math.round(f * units); + + return new StringBuffer().append(Whole).append(" ").append(Num).append("/").append(units).toString(); + } + + public final String format(double val) { + if (mode == ONE_DIGIT) { + return format(val, 9); + } else if (mode == TWO_DIGIT) { + return format(val, 99); + } else if (mode == THREE_DIGIT) { + return format(val, 999); + } else if (mode == UNITS) { + return formatUnit(val , units); + } + throw new RuntimeException("Unexpected Case"); + } + + public StringBuffer format(Object obj, + StringBuffer toAppendTo, + FieldPosition pos) { + if (obj instanceof Number) { + toAppendTo.append(format(((Number)obj).doubleValue())); + return toAppendTo; + } + throw new IllegalArgumentException("Can only handle Numbers"); + } + + public Object parseObject(String source, + ParsePosition status) { + //JMH TBD + return null; + } + + public Object parseObject(String source) + throws ParseException { + //JMH TBD + return null; + } + + public Object clone() { + //JMH TBD + return null; + } + + +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SVRowHeader.java b/poi-examples/src/main/java/poi/hssf/view/SVRowHeader.java new file mode 100644 index 0000000000..c6db2f71a4 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SVRowHeader.java @@ -0,0 +1,96 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + + +package org.apache.poi.hssf.view; + +import java.awt.*; +import javax.swing.*; +import javax.swing.table.*; + +import org.apache.poi.hssf.usermodel.*; + +/** + * This class presents the row header to the table. + * + * + * @author Jason Height + */ +public class SVRowHeader extends JList { + /** This model simply returns an integer number up to the number of rows + * that are present in the sheet. + * + */ + private class SVRowHeaderModel extends AbstractListModel { + private HSSFSheet sheet; + + public SVRowHeaderModel(HSSFSheet sheet) { + this.sheet = sheet; + } + + public int getSize() { + return sheet.getLastRowNum() + 1; + } + public Object getElementAt(int index) { + return Integer.toString(index+1); + } + } + + /** Renderes the row number*/ + private class RowHeaderRenderer extends JLabel implements ListCellRenderer { + private HSSFSheet sheet; + private int extraHeight; + + RowHeaderRenderer(HSSFSheet sheet, JTable table, int extraHeight) { + this.sheet = sheet; + this.extraHeight = extraHeight; + JTableHeader header = table.getTableHeader(); + setOpaque(true); + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + setHorizontalAlignment(CENTER); + setForeground(header.getForeground()); + setBackground(header.getBackground()); + setFont(header.getFont()); + } + + public Component getListCellRendererComponent( JList list, + Object value, int index, boolean isSelected, boolean cellHasFocus) { + Dimension d = getPreferredSize(); + HSSFRow row = sheet.getRow(index); + int rowHeight; + if(row == null) { + rowHeight = (int)sheet.getDefaultRowHeightInPoints(); + } else { + rowHeight = (int)row.getHeightInPoints(); + } + d.height = rowHeight+extraHeight; + setPreferredSize(d); + setText((value == null) ? "" : value.toString()); + return this; + } + } + + public SVRowHeader(HSSFSheet sheet, JTable table, int extraHeight) { + ListModel lm = new SVRowHeaderModel(sheet); + this.setModel(lm); + + setFixedCellWidth(50); + setCellRenderer(new RowHeaderRenderer(sheet, table, extraHeight)); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SVSheetTable.java b/poi-examples/src/main/java/poi/hssf/view/SVSheetTable.java new file mode 100644 index 0000000000..ed2fd8fb6d --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SVSheetTable.java @@ -0,0 +1,241 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.hssf.view; + +import org.apache.poi.hssf.view.brush.PendingPaintings; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; + +import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.table.*; +import javax.swing.text.JTextComponent; +import java.awt.*; +import java.awt.event.HierarchyEvent; +import java.awt.event.HierarchyListener; + +/** + * This class is a table that represents the values in a single worksheet. + * + * @author Ken Arnold, Industrious Media LLC + */ +public class SVSheetTable extends JTable { + private final HSSFSheet sheet; + private final PendingPaintings pendingPaintings; + private FormulaDisplayListener formulaListener; + private JScrollPane scroll; + + private static final Color HEADER_BACKGROUND = new Color(235, 235, 235); + + /** + * This field is the magic number to convert from a Character width to a java + * pixel width. + *

    + * When the "normal" font size in a workbook changes, this effects all of the + * heights and widths. Unfortunately there is no way to retrieve this + * information, hence the MAGIC number. + *

    + * This number may only work for the normal style font size of Arial size 10. + */ + private static final int magicCharFactor = 7; + + private class HeaderCell extends JLabel { + private final int row; + + public HeaderCell(Object value, int row) { + super(value.toString(), CENTER); + this.row = row; + setBackground(HEADER_BACKGROUND); + setOpaque(true); + setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); + setRowSelectionAllowed(false); + } + + @Override + public Dimension getPreferredSize() { + Dimension d = super.getPreferredSize(); + if (row >= 0) { + d.height = getRowHeight(row); + } + return d; + } + + @Override + public Dimension getMaximumSize() { + Dimension d = super.getMaximumSize(); + if (row >= 0) { + d.height = getRowHeight(row); + } + return d; + } + + @Override + public Dimension getMinimumSize() { + Dimension d = super.getMinimumSize(); + if (row >= 0) { + d.height = getRowHeight(row); + } + return d; + } + } + + private class HeaderCellRenderer implements TableCellRenderer { + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + + return new HeaderCell(value, row); + } + } + + private class FormulaDisplayListener implements ListSelectionListener { + private final JTextComponent formulaDisplay; + + public FormulaDisplayListener(JTextComponent formulaDisplay) { + this.formulaDisplay = formulaDisplay; + } + + public void valueChanged(ListSelectionEvent e) { + int row = getSelectedRow(); + int col = getSelectedColumn(); + if (row < 0 || col < 0) { + return; + } + + if (e.getValueIsAdjusting()) { + return; + } + + HSSFCell cell = (HSSFCell) getValueAt(row, col); + String formula = ""; + if (cell != null) { + if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { + formula = cell.getCellFormula(); + } else { + formula = cell.toString(); + } + if (formula == null) + formula = ""; + } + formulaDisplay.setText(formula); + } + } + + public SVSheetTable(HSSFSheet sheet) { + super(new SVTableModel(sheet)); + this.sheet = sheet; + + setIntercellSpacing(new Dimension(0, 0)); + setAutoResizeMode(AUTO_RESIZE_OFF); + JTableHeader header = getTableHeader(); + header.setDefaultRenderer(new HeaderCellRenderer()); + pendingPaintings = new PendingPaintings(this); + + //Set the columns the correct size + TableColumnModel columns = getColumnModel(); + for (int i = 0; i < columns.getColumnCount(); i++) { + TableColumn column = columns.getColumn(i); + int width = sheet.getColumnWidth(i); + //256 is because the width is in 256ths of a character + column.setPreferredWidth(width / 256 * magicCharFactor); + } + + Toolkit t = getToolkit(); + int res = t.getScreenResolution(); + TableModel model = getModel(); + for (int i = 0; i < model.getRowCount(); i++) { + Row row = sheet.getRow(i - sheet.getFirstRowNum()); + if (row != null) { + short h = row.getHeight(); + int height = Math.round(Math.max(1, h / (res / 70 * 20) + 3)); + System.out.printf("%d: %d (%d @ %d)%n", i, height, h, res); + setRowHeight(i, height); + } + } + + addHierarchyListener(new HierarchyListener() { + public void hierarchyChanged(HierarchyEvent e) { + if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) { + Container changedParent = e.getChangedParent(); + if (changedParent instanceof JViewport) { + Container grandparent = changedParent.getParent(); + if (grandparent instanceof JScrollPane) { + JScrollPane jScrollPane = (JScrollPane) grandparent; + setupScroll(jScrollPane); + } + } + } + } + }); + } + + public void setupScroll(JScrollPane scroll) { + if (scroll == this.scroll) + return; + + this.scroll = scroll; + if (scroll == null) + return; + + SVRowHeader rowHeader = new SVRowHeader(sheet, this, 0); + scroll.setRowHeaderView(rowHeader); + scroll.setCorner(JScrollPane.UPPER_LEADING_CORNER, headerCell("?")); + } + + public void setFormulaDisplay(JTextComponent formulaDisplay) { + ListSelectionModel rowSelMod = getSelectionModel(); + ListSelectionModel colSelMod = getColumnModel().getSelectionModel(); + + if (formulaDisplay == null) { + rowSelMod.removeListSelectionListener(formulaListener); + colSelMod.removeListSelectionListener(formulaListener); + formulaListener = null; + } + + if (formulaDisplay != null) { + formulaListener = new FormulaDisplayListener(formulaDisplay); + rowSelMod.addListSelectionListener(formulaListener); + colSelMod.addListSelectionListener(formulaListener); + } + } + + public JTextComponent getFormulaDisplay() { + if (formulaListener == null) + return null; + else + return formulaListener.formulaDisplay; + } + + public Component headerCell(String text) { + return new HeaderCell(text, -1); + } + + @Override + public void paintComponent(Graphics g1) { + Graphics2D g = (Graphics2D) g1; + + pendingPaintings.clear(); + + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + super.paintComponent(g); + + pendingPaintings.paint(g); + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/hssf/view/SVTableCellEditor.java b/poi-examples/src/main/java/poi/hssf/view/SVTableCellEditor.java new file mode 100644 index 0000000000..b0c57b0fe0 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SVTableCellEditor.java @@ -0,0 +1,203 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.view; + +import java.awt.*; +import java.awt.event.*; +import java.util.*; + +import javax.swing.*; +import javax.swing.table.*; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.util.HSSFColor; + +/** + * Sheet Viewer Table Cell Editor -- not commented via javadoc as it + * nearly completely consists of overridden methods. + * + * @author Jason Height + */ +public class SVTableCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener { + private static final Color black = getAWTColor(new HSSFColor.BLACK()); + private static final Color white = getAWTColor(new HSSFColor.WHITE()); + private Map colors = HSSFColor.getIndexHash(); + + + private HSSFWorkbook wb; + private JTextField editor; + + private HSSFCell editorValue; + + + public SVTableCellEditor(HSSFWorkbook wb) { + this.wb = wb; + this.editor = new JTextField(); + } + + + /** + * Gets the cellEditable attribute of the SVTableCellEditor object + * + * @return The cellEditable value + */ + public boolean isCellEditable(java.util.EventObject e) { + if (e instanceof MouseEvent) { + return ((MouseEvent) e).getClickCount() >= 2; + } + return false; + } + + + public boolean shouldSelectCell(EventObject anEvent) { + return true; + } + + + public boolean startCellEditing(EventObject anEvent) { + System.out.println("Start Cell Editing"); + return true; + } + + + public boolean stopCellEditing() { + System.out.println("Stop Cell Editing"); + fireEditingStopped(); + return true; + } + + + public void cancelCellEditing() { + System.out.println("Cancel Cell Editing"); + fireEditingCanceled(); + } + + + public void actionPerformed(ActionEvent e) { + System.out.println("Action performed"); + stopCellEditing(); + } + + + /** + * Gets the cellEditorValue attribute of the SVTableCellEditor object + * + * @return The cellEditorValue value + */ + public Object getCellEditorValue() { + System.out.println("GetCellEditorValue"); + //JMH Look at when this method is called. Should it return a HSSFCell? + return editor.getText(); + } + + + /** + * Gets the tableCellEditorComponent attribute of the SVTableCellEditor object + * + * @return The tableCellEditorComponent value + */ + public Component getTableCellEditorComponent(JTable table, Object value, + boolean isSelected, + int row, + int column) { + System.out.println("GetTableCellEditorComponent"); + HSSFCell cell = (HSSFCell) value; + if (cell != null) { + HSSFCellStyle style = cell.getCellStyle(); + HSSFFont f = wb.getFontAt(style.getFontIndex()); + boolean isbold = f.getBoldweight() > HSSFFont.BOLDWEIGHT_NORMAL; + boolean isitalics = f.getItalic(); + + int fontstyle = Font.PLAIN; + + if (isbold) fontstyle = Font.BOLD; + if (isitalics) fontstyle = fontstyle | Font.ITALIC; + + int fontheight = f.getFontHeightInPoints(); + if (fontheight == 9) fontheight = 10; //fix for stupid ol Windows + + Font font = new Font(f.getFontName(),fontstyle,fontheight); + editor.setFont(font); + + if (style.getFillPattern() == HSSFCellStyle.SOLID_FOREGROUND) { + editor.setBackground(getAWTColor(style.getFillForegroundColor(), white)); + } else editor.setBackground(white); + + editor.setForeground(getAWTColor(f.getColor(), black)); + + + //Set the value that is rendered for the cell + switch (cell.getCellType()) { + case HSSFCell.CELL_TYPE_BLANK: + editor.setText(""); + break; + case HSSFCell.CELL_TYPE_BOOLEAN: + if (cell.getBooleanCellValue()) { + editor.setText("true"); + } else { + editor.setText("false"); + } + break; + case HSSFCell.CELL_TYPE_NUMERIC: + editor.setText(Double.toString(cell.getNumericCellValue())); + break; + case HSSFCell.CELL_TYPE_STRING: + editor.setText(cell.getRichStringCellValue().getString()); + break; + case HSSFCell.CELL_TYPE_FORMULA: + default: + editor.setText("?"); + } + switch (style.getAlignment()) { + case HSSFCellStyle.ALIGN_LEFT: + case HSSFCellStyle.ALIGN_JUSTIFY: + case HSSFCellStyle.ALIGN_FILL: + editor.setHorizontalAlignment(SwingConstants.LEFT); + break; + case HSSFCellStyle.ALIGN_CENTER: + case HSSFCellStyle.ALIGN_CENTER_SELECTION: + editor.setHorizontalAlignment(SwingConstants.CENTER); + break; + case HSSFCellStyle.ALIGN_GENERAL: + case HSSFCellStyle.ALIGN_RIGHT: + editor.setHorizontalAlignment(SwingConstants.RIGHT); + break; + default: + editor.setHorizontalAlignment(SwingConstants.LEFT); + break; + } + + } + return editor; + } + + /** This method retrieves the AWT Color representation from the colour hash table + * + */ + private final Color getAWTColor(int index, Color deflt) { + HSSFColor clr = (HSSFColor)colors.get(Integer.valueOf(index)); + if (clr == null) return deflt; + return getAWTColor(clr); + } + + private static final Color getAWTColor(HSSFColor clr) { + short[] rgb = clr.getTriplet(); + return new Color(rgb[0],rgb[1],rgb[2]); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SVTableCellRenderer.java b/poi-examples/src/main/java/poi/hssf/view/SVTableCellRenderer.java new file mode 100644 index 0000000000..4b2e634bb3 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SVTableCellRenderer.java @@ -0,0 +1,274 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.hssf.view; + +import javax.swing.*; +import javax.swing.table.TableCellRenderer; +import javax.swing.border.*; + +import java.awt.Component; +import java.awt.Color; +import java.awt.Rectangle; + +import java.io.Serializable; +import java.text.*; + +import org.apache.poi.hssf.usermodel.*; + + +/** + * Sheet Viewer Table Cell Render -- not commented via javadoc as it + * nearly completely consists of overridden methods. + * + * @author Andrew C. Oliver + */ +public class SVTableCellRenderer extends JLabel + implements TableCellRenderer, Serializable +{ + protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); + protected SVBorder cellBorder = new SVBorder(); + + + private HSSFWorkbook wb = null; + + /** This class holds the references to the predefined cell formats. + */ + private class CellFormatter { + private Format[] textFormatter; + + private DecimalFormat generalNumberFormat = new DecimalFormat("0"); + + public CellFormatter() { + textFormatter = new Format[0x31]; + + textFormatter[0x01] = new DecimalFormat("0"); + textFormatter[0x02] = new DecimalFormat("0.00"); + textFormatter[0x03] = new DecimalFormat("#,##0"); + textFormatter[0x04] = new DecimalFormat("#,##0.00"); + textFormatter[0x05] = new DecimalFormat("$#,##0;$#,##0"); + textFormatter[0x06] = new DecimalFormat("$#,##0;$#,##0"); + textFormatter[0x07] = new DecimalFormat("$#,##0.00;$#,##0.00"); + textFormatter[0x08] = new DecimalFormat("$#,##0.00;$#,##0.00"); + textFormatter[0x09] = new DecimalFormat("0%"); + textFormatter[0x0A] = new DecimalFormat("0.00%"); + textFormatter[0x0B] = new DecimalFormat("0.00E0"); + textFormatter[0x0C] = new SVFractionalFormat("# ?/?"); + textFormatter[0x0D] = new SVFractionalFormat("# ??/??"); + textFormatter[0x0E] = new SimpleDateFormat("M/d/yy"); + textFormatter[0x0F] = new SimpleDateFormat("d-MMM-yy"); + textFormatter[0x10] = new SimpleDateFormat("d-MMM"); + textFormatter[0x11] = new SimpleDateFormat("MMM-yy"); + textFormatter[0x12] = new SimpleDateFormat("h:mm a"); + textFormatter[0x13] = new SimpleDateFormat("h:mm:ss a"); + textFormatter[0x14] = new SimpleDateFormat("h:mm"); + textFormatter[0x15] = new SimpleDateFormat("h:mm:ss"); + textFormatter[0x16] = new SimpleDateFormat("M/d/yy h:mm"); + // 0x17 - 0x24 reserved for international and undocumented 0x25, "(#,##0_);(#,##0)" + //start at 0x26 + //jmh need to do colour + //"(#,##0_);[Red](#,##0)" + textFormatter[0x26] = new DecimalFormat("#,##0;#,##0"); + //jmh need to do colour + //(#,##0.00_);(#,##0.00) + textFormatter[0x27] = new DecimalFormat("#,##0.00;#,##0.00"); + textFormatter[0x28] = new DecimalFormat("#,##0.00;#,##0.00"); +//?? textFormatter[0x29] = new DecimalFormat("_(*#,##0_);_(*(#,##0);_(* \"-\"_);_(@_)"); +//?? textFormatter[0x2A] = new DecimalFormat("_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"); +//?? textFormatter[0x2B] = new DecimalFormat("_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"); +//?? textFormatter[0x2C] = new DecimalFormat("_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"); + textFormatter[0x2D] = new SimpleDateFormat("mm:ss"); +//?? textFormatter[0x2E] = new SimpleDateFormat("[h]:mm:ss"); + textFormatter[0x2F] = new SimpleDateFormat("mm:ss.0"); + textFormatter[0x30] = new DecimalFormat("##0.0E0"); + } + + public String format(short index, Object value) { + if (index == 0) + return value.toString(); + if (textFormatter[index] == null) + throw new RuntimeException("Sorry. I cant handle the format code :"+Integer.toHexString(index)); + return textFormatter[index].format(value); + } + + public String format(short index, double value) { + if ( index <= 0 ) + return generalNumberFormat.format(value); + if (textFormatter[index] == null) + throw new RuntimeException("Sorry. I cant handle the format code :"+Integer.toHexString(index)); + if (textFormatter[index] instanceof DecimalFormat) { + return ((DecimalFormat)textFormatter[index]).format(value); + } + if (textFormatter[index] instanceof SVFractionalFormat) { + return ((SVFractionalFormat)textFormatter[index]).format(value); + } + throw new RuntimeException("Sorry. I cant handle a non decimal formatter for a decimal value :"+Integer.toHexString(index)); + } + + public boolean useRedColor(short index, double value) { + return (((index == 0x06)||(index == 0x08)||(index == 0x26) || (index == 0x27)) && (value < 0)); + } + } + + private final CellFormatter cellFormatter = new CellFormatter(); + + public SVTableCellRenderer(HSSFWorkbook wb) { + super(); + setOpaque(true); + setBorder(noFocusBorder); + this.wb = wb; + } + + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + boolean isBorderSet = false; + + //If the JTables default cell renderer has been setup correctly the + //value will be the HSSFCell that we are trying to render + HSSFCell c = (HSSFCell)value; + + if (c != null) { + HSSFCellStyle s = c.getCellStyle(); + HSSFFont f = wb.getFontAt(s.getFontIndex()); + setFont(SVTableUtils.makeFont(f)); + + if (s.getFillPattern() == HSSFCellStyle.SOLID_FOREGROUND) { + setBackground(SVTableUtils.getAWTColor(s.getFillForegroundColor(), SVTableUtils.white)); + } else setBackground(SVTableUtils.white); + + setForeground(SVTableUtils.getAWTColor(f.getColor(), SVTableUtils.black)); + + cellBorder.setBorder(SVTableUtils.getAWTColor(s.getTopBorderColor(), SVTableUtils.black), + SVTableUtils.getAWTColor(s.getRightBorderColor(), SVTableUtils.black), + SVTableUtils.getAWTColor(s.getBottomBorderColor(), SVTableUtils.black), + SVTableUtils.getAWTColor(s.getLeftBorderColor(), SVTableUtils.black), + s.getBorderTop(), s.getBorderRight(), + s.getBorderBottom(), s.getBorderLeft(), + hasFocus); + setBorder(cellBorder); + isBorderSet=true; + + //Set the value that is rendered for the cell + switch (c.getCellType()) { + case HSSFCell.CELL_TYPE_BLANK: + setValue(""); + break; + case HSSFCell.CELL_TYPE_BOOLEAN: + if (c.getBooleanCellValue()) { + setValue("true"); + } else { + setValue("false"); + } + break; + case HSSFCell.CELL_TYPE_NUMERIC: + short format = s.getDataFormat(); + double numericValue = c.getNumericCellValue(); + if (cellFormatter.useRedColor(format, numericValue)) + setForeground(Color.red); + else setForeground(null); + setValue(cellFormatter.format(format, c.getNumericCellValue())); + break; + case HSSFCell.CELL_TYPE_STRING: + setValue(c.getRichStringCellValue().getString()); + break; + case HSSFCell.CELL_TYPE_FORMULA: + default: + setValue("?"); + } + //Set the text alignment of the cell + switch (s.getAlignment()) { + case HSSFCellStyle.ALIGN_LEFT: + case HSSFCellStyle.ALIGN_JUSTIFY: + case HSSFCellStyle.ALIGN_FILL: + setHorizontalAlignment(SwingConstants.LEFT); + break; + case HSSFCellStyle.ALIGN_CENTER: + case HSSFCellStyle.ALIGN_CENTER_SELECTION: + setHorizontalAlignment(SwingConstants.CENTER); + break; + case HSSFCellStyle.ALIGN_GENERAL: + case HSSFCellStyle.ALIGN_RIGHT: + setHorizontalAlignment(SwingConstants.RIGHT); + break; + default: + setHorizontalAlignment(SwingConstants.LEFT); + break; + } + } else { + setValue(""); + setBackground(SVTableUtils.white); + } + + + if (hasFocus) { + if (!isBorderSet) { + //This is the border to paint when there is no border + //and the cell has focus + cellBorder.setBorder(SVTableUtils.black, + SVTableUtils.black, + SVTableUtils.black, + SVTableUtils.black, + HSSFCellStyle.BORDER_NONE, + HSSFCellStyle.BORDER_NONE, + HSSFCellStyle.BORDER_NONE, + HSSFCellStyle.BORDER_NONE, + isSelected); + setBorder(cellBorder); + } + if (table.isCellEditable(row, column)) { + setForeground( UIManager.getColor("Table.focusCellForeground") ); + setBackground( UIManager.getColor("Table.focusCellBackground") ); + } + } else if (!isBorderSet) { + setBorder(noFocusBorder); + } + + // ---- begin optimization to avoid painting background ---- + Color back = getBackground(); + boolean colorMatch = (back != null) && ( back.equals(table.getBackground()) ) && table.isOpaque(); + setOpaque(!colorMatch); + // ---- end optimization to aviod painting background ---- + return this; + } + + public void validate() {} + + public void revalidate() {} + + public void repaint(long tm, int x, int y, int width, int height) {} + + public void repaint(Rectangle r) { } + + protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + // Strings get interned... + if (propertyName=="text") { + super.firePropertyChange(propertyName, oldValue, newValue); + } + } + + public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { } + + /** + * Sets the string to either the value or "" if the value is null. + * + */ + protected void setValue(Object value) { + setText((value == null) ? "" : value.toString()); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SVTableModel.java b/poi-examples/src/main/java/poi/hssf/view/SVTableModel.java new file mode 100644 index 0000000000..170dacb697 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SVTableModel.java @@ -0,0 +1,87 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + + +package org.apache.poi.hssf.view; + +import java.util.Iterator; +import javax.swing.table.*; + +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFCell; + +/** + * Sheet Viewer Table Model - The model for the Sheet Viewer just overrides things. + * @author Andrew C. Oliver + */ + +public class SVTableModel extends AbstractTableModel { + private HSSFSheet st = null; + int maxcol = 0; + + public SVTableModel(HSSFSheet st, int maxcol) { + this.st = st; + this.maxcol=maxcol; + } + + public SVTableModel(HSSFSheet st) { + this.st = st; + Iterator i = st.rowIterator(); + + while (i.hasNext()) { + HSSFRow row = (HSSFRow)i.next(); + if (maxcol < (row.getLastCellNum()+1)) { + this.maxcol = row.getLastCellNum(); + } + } + } + + + public int getColumnCount() { + return this.maxcol+1; + } + public Object getValueAt(int row, int col) { + HSSFRow r = st.getRow(row); + HSSFCell c = null; + if (r != null) { + c = r.getCell(col); + } + return c; + } + public int getRowCount() { + return st.getLastRowNum() + 1; + } + + public Class getColumnClass(int c) { + return HSSFCell.class; + } + + public boolean isCellEditable(int rowIndex, int columnIndex) { + return true; + } + + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + if (aValue != null) + System.out.println("SVTableModel.setValueAt. value type = "+aValue.getClass().getName()); + else System.out.println("SVTableModel.setValueAt. value type = null"); + } + + +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SVTableUtils.java b/poi-examples/src/main/java/poi/hssf/view/SVTableUtils.java new file mode 100644 index 0000000000..23ffb851bd --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SVTableUtils.java @@ -0,0 +1,93 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.view; + +import java.util.*; +import java.awt.*; +import javax.swing.border.*; + +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.util.*; + +/** + * SVTableCell Editor and Renderer helper functions. + * + * @author Jason Height + */ +public class SVTableUtils { + private final static Map colors = HSSFColor.getIndexHash(); + /** Description of the Field */ + public final static Color black = getAWTColor(new HSSFColor.BLACK()); + /** Description of the Field */ + public final static Color white = getAWTColor(new HSSFColor.WHITE()); + /** Description of the Field */ + public static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); + + + /** + * Creates a new font for a specific cell style + */ + public static Font makeFont(HSSFFont font) { + boolean isbold = font.getBoldweight() > HSSFFont.BOLDWEIGHT_NORMAL; + boolean isitalics = font.getItalic(); + int fontstyle = Font.PLAIN; + if (isbold) { + fontstyle = Font.BOLD; + } + if (isitalics) { + fontstyle = fontstyle | Font.ITALIC; + } + + int fontheight = font.getFontHeightInPoints(); + if (fontheight == 9) { + //fix for stupid ol Windows + fontheight = 10; + } + + return new Font(font.getFontName(), fontstyle, fontheight); + } + + + /** + * This method retrieves the AWT Color representation from the colour hash table + * + * @param index Description of the Parameter + * @param deflt Description of the Parameter + * @return The aWTColor value + */ + public final static Color getAWTColor(int index, Color deflt) { + HSSFColor clr = (HSSFColor) colors.get(Integer.valueOf(index)); + if (clr == null) { + return deflt; + } + return getAWTColor(clr); + } + + + /** + * Gets the aWTColor attribute of the SVTableUtils class + * + * @param clr Description of the Parameter + * @return The aWTColor value + */ + public final static Color getAWTColor(HSSFColor clr) { + short[] rgb = clr.getTriplet(); + return new Color(rgb[0], rgb[1], rgb[2]); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SViewer.java b/poi-examples/src/main/java/poi/hssf/view/SViewer.java new file mode 100644 index 0000000000..de2cfb1f6d --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SViewer.java @@ -0,0 +1,172 @@ + +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + + +package org.apache.poi.hssf.view; + +import java.awt.*; +import java.awt.event.*; +import java.net.*; +import java.io.*; +import javax.swing.*; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +/** + * Sheet Viewer - Views XLS files via HSSF. Can be used as an applet with + * filename="" or as a applications (pass the filename as the first parameter). + * Or you can pass it a URL in a "url" parameter when run as an applet or just + * that first parameter must start with http:// and it will guess its a url. I + * only tested it as an applet though, so it probably won't work...you fix it. + * + * @author Andrew C. Oliver + * @author Jason Height + */ +public class SViewer extends JApplet { + private SViewerPanel panel; + boolean isStandalone = false; + String filename = null; + + /**Get a parameter value*/ + public String getParameter(String key, String def) { + return isStandalone ? System.getProperty(key, def) : + (getParameter(key) != null ? getParameter(key) : def); + } + + /**Construct the applet*/ + public SViewer() { + } + + /**Initialize the applet*/ + public void init() { + try { + jbInit(); + } + catch(Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + /**Component initialization*/ + private void jbInit() throws Exception { + InputStream i = null; + boolean isurl = false; + if (filename == null) filename = getParameter("filename"); + + if (filename == null || filename.substring(0,7).equals("http://")) { + isurl = true; + if (filename == null) filename = getParameter("url"); + i = getXLSFromURL(filename); + } + + HSSFWorkbook wb = null; + if (isurl) { + wb = constructWorkbook(i); + } else { + wb = constructWorkbook(filename); + } + panel = new SViewerPanel(wb, false); + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(panel, BorderLayout.CENTER); + } + + private HSSFWorkbook constructWorkbook(String filename) throws FileNotFoundException, IOException { + HSSFWorkbook wb = null; + FileInputStream in = new FileInputStream(filename); + wb = new HSSFWorkbook(in); + in.close(); + return wb; + } + + private HSSFWorkbook constructWorkbook(InputStream in) throws IOException { + HSSFWorkbook wb = null; + + wb = new HSSFWorkbook(in); + in.close(); + return wb; + } + + /**Start the applet*/ + public void start() { + } + /**Stop the applet*/ + public void stop() { + } + /**Destroy the applet*/ + public void destroy() { + } + /**Get Applet information*/ + public String getAppletInfo() { + return "Applet Information"; + } + /**Get parameter info*/ + public String[][] getParameterInfo() { + return null; + } + + /** + * opens a url and returns an inputstream + * + */ + private InputStream getXLSFromURL(String urlstring) throws MalformedURLException, IOException { + URL url = new URL(urlstring); + URLConnection uc = url.openConnection(); + String field = uc.getHeaderField(0); + for (int i=0;field != null; i++) { + System.out.println(field); + field = uc.getHeaderField(i); + } + BufferedInputStream is = new BufferedInputStream(uc.getInputStream()); + return is; + } + + + /**Main method*/ + public static void main(String[] args) { + if(args.length < 1) { + throw new IllegalArgumentException("A filename to view must be supplied as the first argument, but none was given"); + } + + SViewer applet = new SViewer(); + applet.isStandalone = true; + applet.filename = args[0]; + Frame frame; + frame = new Frame() { + protected void processWindowEvent(WindowEvent e) { + super.processWindowEvent(e); + if (e.getID() == WindowEvent.WINDOW_CLOSING) { + System.exit(0); + } + } + public synchronized void setTitle(String title) { + super.setTitle(title); + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + } + }; + frame.setTitle("Applet Frame"); + frame.add(applet, BorderLayout.CENTER); + applet.init(); + applet.start(); + frame.setSize(400,320); + Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); + frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2); + frame.setVisible(true); + } +} diff --git a/poi-examples/src/main/java/poi/hssf/view/SViewerPanel.java b/poi-examples/src/main/java/poi/hssf/view/SViewerPanel.java new file mode 100644 index 0000000000..5fe596220a --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/SViewerPanel.java @@ -0,0 +1,292 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hssf.view; + +import java.awt.*; +import java.awt.event.*; +import java.io.*; +import javax.swing.*; +import javax.swing.table.*; + +import org.apache.poi.hssf.usermodel.*; + +/** + * This class presents the sheets to the user. + * + * + * @author Andrew C. Oliver + * @author Jason Height + */ +public class SViewerPanel extends JPanel { + /** This field is the magic number to convert from a Character width to a + * java pixel width. + * + * When the "normal" font size in a workbook changes, this effects all + * of the heights and widths. Unfortunately there is no way to retrieve this + * information, hence the MAGIC number. + * + * This number may only work for the normal style font size of Arial size 10. + * + */ + private static final int magicCharFactor = 7; + /** Reference to the wookbook that is being displayed*/ + /* package */ HSSFWorkbook wb; + /** Reference to the tabs component*/ + /* package */ JTabbedPane sheetPane; + /** Reference to the cell renderer that is used to render all cells*/ + private SVTableCellRenderer cellRenderer; + /** Reference to the cell editor that is used to edit all cells. + * Only constructed if editing is allowed + */ + private SVTableCellEditor cellEditor; + /** Flag indicating if editing is allowed. Otherwise the viewer is in + * view only mode. + */ + private boolean allowEdits; + + /**Construct the representation of the workbook*/ + public SViewerPanel(HSSFWorkbook wb, boolean allowEdits) { + this.wb = wb; + this.allowEdits = allowEdits; + + initialiseGui(); + } + + private void initialiseGui() { + cellRenderer = new SVTableCellRenderer(this.wb); + if (allowEdits) + cellEditor = new SVTableCellEditor(this.wb); + + //Initialise the Panel + sheetPane = new JTabbedPane(JTabbedPane.BOTTOM); + + if (allowEdits) + sheetPane.addMouseListener(createTabListener()); + int sheetCount = wb.getNumberOfSheets(); + for (int i=0; i + * It is up to the parent component to invoke the {@link #paint(Graphics2D)} + * method of this objet at that appropriate time. + * + * @author Ken Arnold, Industrious Media LLC + */ +public class PendingPaintings { + /** + * The name of the client property that holds this object in the parent + * component. + */ + public static final String PENDING_PAINTINGS = + PendingPaintings.class.getSimpleName(); + + private final List paintings; + + /** A single painting description. */ + public static class Painting { + final Stroke stroke; + final Color color; + final Shape shape; + final AffineTransform transform; + + /** + * Creates a new painting description. + * + * @param stroke The stroke to paint. + * @param color The color of the stroke. + * @param shape The shape of the stroke. + * @param transform The transformation matrix to use. + */ + public Painting(Stroke stroke, Color color, Shape shape, + AffineTransform transform) { + + this.color = color; + this.shape = shape; + this.stroke = stroke; + this.transform = transform; + } + + /** + * Draw the painting. + * + * @param g The graphics object to use to draw with. + */ + public void draw(Graphics2D g) { + g.setTransform(transform); + g.setStroke(stroke); + g.setColor(color); + g.draw(shape); + } + } + + /** + * Creates a new object on the given parent. The created object will be + * stored as a client property. + * + * @param parent + */ + public PendingPaintings(JComponent parent) { + paintings = new ArrayList(); + parent.putClientProperty(PENDING_PAINTINGS, this); + } + + /** Drops all pending paintings. */ + public void clear() { + paintings.clear(); + } + + /** + * Paints all pending paintings. Once they have been painted they are + * removed from the list of pending paintings (they aren't pending anymore, + * after all). + * + * @param g The graphics object to draw with. + */ + public void paint(Graphics2D g) { + g.setBackground(Color.CYAN); + AffineTransform origTransform = g.getTransform(); + for (Painting c : paintings) { + c.draw(g); + } + g.setTransform(origTransform); + + clear(); + } + + /** + * Adds a new pending painting to the list on the given component. This + * will find the first ancestor that has a {@link PendingPaintings} client + * property, starting with the component itself. + * + * @param c The component for which the painting is being added. + * @param g The graphics object to draw with. + * @param stroke The stroke to draw. + * @param color The color to draw with. + * @param shape The shape to stroke. + */ + public static void add(JComponent c, Graphics2D g, Stroke stroke, + Color color, Shape shape) { + + add(c, new Painting(stroke, color, shape, g.getTransform())); + } + + /** + * Adds a new pending painting to the list on the given component. This + * will find the first ancestor that has a {@link PendingPaintings} client + * property, starting with the component itself. + * + * @param c The component for which the painting is being added. + * @param newPainting The new painting. + */ + public static void add(JComponent c, Painting newPainting) { + PendingPaintings pending = pendingPaintingsFor(c); + if (pending != null) { + pending.paintings.add(newPainting); + } + } + + /** + * Returns the pending painting object for the given component, if any. This + * is retrieved from the first object found that has a {@link + * #PENDING_PAINTINGS} client property, starting with this component and + * looking up its ancestors (parent, parent's parent, etc.) + *

    + * This allows any descendant of a component that has a {@link + * PendingPaintings} property to add its own pending paintings. + * + * @param c The component for which the painting is being added. + * + * @return The pending painting object for that component, or null + * if there is none. + */ + public static PendingPaintings pendingPaintingsFor(JComponent c) { + for (Component parent = c; + parent != null; + parent = parent.getParent()) { + if (parent instanceof JComponent) { + JComponent jc = (JComponent) parent; + Object pd = jc.getClientProperty(PENDING_PAINTINGS); + if (pd != null) + return (PendingPaintings) pd; + } + } + return null; + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/hssf/view/brush/package.html b/poi-examples/src/main/java/poi/hssf/view/brush/package.html new file mode 100644 index 0000000000..d9819fb669 --- /dev/null +++ b/poi-examples/src/main/java/poi/hssf/view/brush/package.html @@ -0,0 +1,26 @@ + + + + + +This package contains some brushes that are used when drawing borders for Excel +cells. + + diff --git a/poi-examples/src/main/java/poi/hwpf/Word2Forrest.java b/poi-examples/src/main/java/poi/hwpf/Word2Forrest.java new file mode 100644 index 0000000000..82d3a8a230 --- /dev/null +++ b/poi-examples/src/main/java/poi/hwpf/Word2Forrest.java @@ -0,0 +1,225 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.hwpf; + +import org.apache.poi.hwpf.HWPFDocument; +import org.apache.poi.hwpf.usermodel.*; +import org.apache.poi.hwpf.model.*; + +import java.io.*; + +public final class Word2Forrest +{ + Writer _out; + HWPFDocument _doc; + + public Word2Forrest(HWPFDocument doc, OutputStream stream) + throws IOException, UnsupportedEncodingException + { + OutputStreamWriter out = new OutputStreamWriter (stream, "UTF-8"); + _out = out; + _doc = doc; + + init (); + openDocument (); + openBody (); + + Range r = doc.getRange (); + StyleSheet styleSheet = doc.getStyleSheet (); + + int sectionLevel = 0; + int lenParagraph = r.numParagraphs (); + boolean inCode = false; + for (int x = 0; x < lenParagraph; x++) + { + Paragraph p = r.getParagraph (x); + String text = p.text (); + if (text.trim ().length () == 0) + { + continue; + } + StyleDescription paragraphStyle = styleSheet.getStyleDescription (p. + getStyleIndex ()); + String styleName = paragraphStyle.getName(); + if (styleName.startsWith ("Heading")) + { + if (inCode) + { + closeSource(); + inCode = false; + } + + int headerLevel = Integer.parseInt (styleName.substring (8)); + if (headerLevel > sectionLevel) + { + openSection (); + } + else + { + for (int y = 0; y < (sectionLevel - headerLevel) + 1; y++) + { + closeSection (); + } + openSection (); + } + sectionLevel = headerLevel; + openTitle (); + writePlainText (text); + closeTitle (); + } + else + { + int cruns = p.numCharacterRuns (); + CharacterRun run = p.getCharacterRun (0); + String fontName = run.getFontName(); + if (fontName.startsWith ("Courier")) + { + if (!inCode) + { + openSource (); + inCode = true; + } + writePlainText (p.text()); + } + else + { + if (inCode) + { + inCode = false; + closeSource(); + } + openParagraph(); + writePlainText(p.text()); + closeParagraph(); + } + } + } + for (int x = 0; x < sectionLevel; x++) + { + closeSection(); + } + closeBody(); + closeDocument(); + _out.flush(); + + } + + public void init () + throws IOException + { + _out.write ("\r\n"); + _out.write ("\r\n"); + } + + public void openDocument () + throws IOException + { + _out.write ("\r\n"); + } + public void closeDocument () + throws IOException + { + _out.write ("\r\n"); + } + + + public void openBody () + throws IOException + { + _out.write ("\r\n"); + } + + public void closeBody () + throws IOException + { + _out.write ("\r\n"); + } + + + public void openSection () + throws IOException + { + _out.write ("

    "); + + } + + public void closeSection () + throws IOException + { + _out.write ("
    "); + + } + + public void openTitle () + throws IOException + { + _out.write (""); + } + + public void closeTitle () + throws IOException + { + _out.write (""); + } + + public void writePlainText (String text) + throws IOException + { + _out.write (text); + } + + public void openParagraph () + throws IOException + { + _out.write ("

    "); + } + + public void closeParagraph () + throws IOException + { + _out.write ("

    "); + } + + public void openSource () + throws IOException + { + _out.write (""); + } + + + public static void main(String[] args) + { + try + { + OutputStream out = new FileOutputStream("c:\\test.xml"); + + new Word2Forrest(new HWPFDocument(new FileInputStream(args[0])), out); + out.close(); + } + catch (Throwable t) + { + t.printStackTrace(); + } + + } +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/Codec.java b/poi-examples/src/main/java/poi/poifs/poibrowser/Codec.java new file mode 100644 index 0000000000..2660f5cc67 --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/Codec.java @@ -0,0 +1,241 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import org.apache.poi.hpsf.ClassID; + + + +/** + *

    Provides utility methods for encoding and decoding hexadecimal + * data.

    + * + * @author Rainer Klute (klute@rainer-klute.de) - with portions from Tomcat + */ +public class Codec +{ + + /** + *

    The nibbles' hexadecimal values. A nibble is a half byte.

    + */ + protected static final byte hexval[] = + {(byte) '0', (byte) '1', (byte) '2', (byte) '3', + (byte) '4', (byte) '5', (byte) '6', (byte) '7', + (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', + (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F'}; + + + + /** + *

    Converts a string into its hexadecimal notation.

    + */ + public static String hexEncode(final String s) + { + return hexEncode(s.getBytes()); + } + + + + /** + *

    Converts a byte array into its hexadecimal notation.

    + */ + public static String hexEncode(final byte[] s) + { + return hexEncode(s, 0, s.length); + } + + + + /** + *

    Converts a part of a byte array into its hexadecimal + * notation.

    + */ + public static String hexEncode(final byte[] s, final int offset, + final int length) + { + StringBuffer b = new StringBuffer(length * 2); + for (int i = offset; i < offset + length; i++) + { + int c = s[i]; + b.append((char) hexval[(c & 0xF0) >> 4]); + b.append((char) hexval[(c & 0x0F) >> 0]); + } + return b.toString(); + } + + + + /** + *

    Converts a single byte into its hexadecimal notation.

    + */ + public static String hexEncode(final byte b) + { + StringBuffer sb = new StringBuffer(2); + sb.append((char) hexval[(b & 0xF0) >> 4]); + sb.append((char) hexval[(b & 0x0F) >> 0]); + return sb.toString(); + } + + + + /** + *

    Converts a short value (16-bit) into its hexadecimal + * notation.

    + */ + public static String hexEncode(final short s) + { + StringBuffer sb = new StringBuffer(4); + sb.append((char) hexval[(s & 0xF000) >> 12]); + sb.append((char) hexval[(s & 0x0F00) >> 8]); + sb.append((char) hexval[(s & 0x00F0) >> 4]); + sb.append((char) hexval[(s & 0x000F) >> 0]); + return sb.toString(); + } + + + + /** + *

    Converts an int value (32-bit) into its hexadecimal + * notation.

    + */ + public static String hexEncode(final int i) + { + StringBuffer sb = new StringBuffer(8); + sb.append((char) hexval[(i & 0xF0000000) >> 28]); + sb.append((char) hexval[(i & 0x0F000000) >> 24]); + sb.append((char) hexval[(i & 0x00F00000) >> 20]); + sb.append((char) hexval[(i & 0x000F0000) >> 16]); + sb.append((char) hexval[(i & 0x0000F000) >> 12]); + sb.append((char) hexval[(i & 0x00000F00) >> 8]); + sb.append((char) hexval[(i & 0x000000F0) >> 4]); + sb.append((char) hexval[(i & 0x0000000F) >> 0]); + return sb.toString(); + } + + + + /** + *

    Converts a long value (64-bit) into its hexadecimal + * notation.

    + */ + public static String hexEncode(final long l) + { + StringBuffer sb = new StringBuffer(16); + sb.append(hexEncode((int) (l & 0xFFFFFFFF00000000L) >> 32)); + sb.append(hexEncode((int) (l & 0x00000000FFFFFFFFL) >> 0)); + return sb.toString(); + } + + + + /** + *

    Converts a class ID into its hexadecimal notation.

    + */ + public static String hexEncode(final ClassID classID) + { + return hexEncode(classID.getBytes()); + } + + + + /** + *

    Decodes the hexadecimal representation of a sequence of + * bytes into a byte array. Each character in the string + * represents a nibble (half byte) and must be one of the + * characters '0'-'9', 'A'-'F' or 'a'-'f'.

    + * + * @param s The string to be decoded + * + * @return The bytes + * + * @throws IllegalArgumentException if the string does not contain + * a valid representation of a byte sequence. + */ + public static byte[] hexDecode(final String s) + { + final int length = s.length(); + + /* The string to be converted must have an even number of + characters. */ + if (length % 2 == 1) + throw new IllegalArgumentException + ("String has odd length " + length); + byte[] b = new byte[length / 2]; + char[] c = new char[length]; + s.toUpperCase().getChars(0, length, c, 0); + for (int i = 0; i < length; i += 2) + b[i/2] = (byte) (decodeNibble(c[i]) << 4 & 0xF0 | + decodeNibble(c[i+1]) & 0x0F); + return b; + } + + + + /** + *

    Decodes a nibble.

    + * + * @param c A character in the range '0'-'9' or 'A'-'F'. Lower + * case is not supported here. + * + * @return The decoded nibble in the range 0-15 + * + * @throws IllegalArgumentException if c is not a + * permitted character + */ + protected static byte decodeNibble(final char c) + { + for (byte i = 0; i < hexval.length; i++) + if ((byte) c == hexval[i]) + return i; + throw new IllegalArgumentException("\"" + c + "\"" + + " does not represent a nibble."); + } + + + + /** + *

    For testing.

    + */ + public static void main(final String args[]) + throws IOException + { + final BufferedReader in = + new BufferedReader(new InputStreamReader(System.in)); + String s; + do + { + s = in.readLine(); + if (s != null) + { + String bytes = hexEncode(s); + System.out.print("Hex encoded (String): "); + System.out.println(bytes); + System.out.print("Hex encoded (byte[]): "); + System.out.println(hexEncode(s.getBytes())); + System.out.print("Re-decoded (byte[]): "); + System.out.println(new String(hexDecode(bytes))); + } + } + while (s != null); + } + +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/DocumentDescriptor.java b/poi-examples/src/main/java/poi/poifs/poibrowser/DocumentDescriptor.java new file mode 100644 index 0000000000..c9647f9a22 --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/DocumentDescriptor.java @@ -0,0 +1,79 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.io.*; +import org.apache.poi.poifs.filesystem.*; + +/** + *

    Describes the most important (whatever that is) features of a + * {@link POIFSDocument}.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class DocumentDescriptor +{ + String name; + POIFSDocumentPath path; + DocumentInputStream stream; + + int size; + byte[] bytes; + + + /** + *

    Creates a {@link DocumentDescriptor}.

    + * + * @param name The stream's name. + * + * @param path The stream's path in the POI filesystem hierarchy. + * + * @param stream The stream. + * + * @param nrOfBytes The maximum number of bytes to display in a + * dump starting at the beginning of the stream. + */ + public DocumentDescriptor(final String name, + final POIFSDocumentPath path, + final DocumentInputStream stream, + final int nrOfBytes) + { + this.name = name; + this.path = path; + this.stream = stream; + try + { + size = stream.available(); + if (stream.markSupported()) + { + stream.mark(nrOfBytes); + final byte[] b = new byte[nrOfBytes]; + final int read = stream.read(b, 0, Math.min(size, b.length)); + bytes = new byte[read]; + System.arraycopy(b, 0, bytes, 0, read); + stream.reset(); + } + } + catch (IOException ex) + { + System.out.println(ex); + } + } + +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/DocumentDescriptorRenderer.java b/poi-examples/src/main/java/poi/poifs/poibrowser/DocumentDescriptorRenderer.java new file mode 100644 index 0000000000..599ea7cc1c --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/DocumentDescriptorRenderer.java @@ -0,0 +1,78 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.awt.*; +import javax.swing.*; +import javax.swing.tree.*; + +/** + *

    {@link TreeCellRenderer} for a {@link DocumentDescriptor}. The + * renderer is extremly rudimentary since displays only the document's + * name, its size and its fist few bytes.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class DocumentDescriptorRenderer extends DefaultTreeCellRenderer +{ + + public Component getTreeCellRendererComponent(final JTree tree, + final Object value, + final boolean selected, + final boolean expanded, + final boolean leaf, + final int row, + final boolean hasFocus) + { + final DocumentDescriptor d = (DocumentDescriptor) + ((DefaultMutableTreeNode) value).getUserObject(); + final JPanel p = new JPanel(); + final JTextArea text = new JTextArea(); + text.append(renderAsString(d)); + text.setFont(new Font("Monospaced", Font.PLAIN, 10)); + p.add(text); + if (selected) + Util.invert(text); + return p; + } + + + /** + *

    Renders {@link DocumentDescriptor} as a string.

    + */ + protected String renderAsString(final DocumentDescriptor d) + { + final StringBuffer b = new StringBuffer(); + b.append("Name: "); + b.append(d.name); + b.append(" ("); + b.append(Codec.hexEncode(d.name)); + b.append(") \n"); + + b.append("Size: "); + b.append(d.size); + b.append(" bytes\n"); + + b.append("First bytes: "); + b.append(Codec.hexEncode(d.bytes)); + + return b.toString(); + } + +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java b/poi-examples/src/main/java/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java new file mode 100644 index 0000000000..7f73ebce46 --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java @@ -0,0 +1,145 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.awt.*; +import javax.swing.*; +import javax.swing.tree.*; +import java.util.*; + +/** + *

    This is a {@link TreeCellRenderer} implementation which is able + * to render arbitrary objects. The {@link ExtendableTreeCellRenderer} + * does not do the rendering itself but instead dispatches to + * class-specific renderers. A class/renderer pair must be registered + * using the {@link #register} method. If a class has no registered + * renderer, the renderer of its closest superclass is used. Since the + * {@link ExtendableTreeCellRenderer} always has a default renderer + * for the {@link Object} class, rendering is always possible. The + * default {@link Object} renderer can be replaced by another renderer + * but it cannot be unregistered.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class ExtendableTreeCellRenderer implements TreeCellRenderer +{ + + /** + *

    Maps classes to renderers.

    + */ + protected Map renderers; + + + + public ExtendableTreeCellRenderer() + { + renderers = new HashMap(); + register(Object.class, new DefaultTreeCellRenderer() + { + public Component getTreeCellRendererComponent + (JTree tree, Object value, boolean selected, + boolean expanded, boolean leaf, int row, boolean hasFocus) + { + final String s = value.toString(); + final JLabel l = new JLabel(s + " "); + if (selected) + { + Util.invert(l); + l.setOpaque(true); + } + return l; + } + }); + } + + + + /** + *

    Registers a renderer for a class.

    + **/ + public void register(final Class c, final TreeCellRenderer renderer) + { + renderers.put(c, renderer); + } + + + + /** + *

    Unregisters a renderer for a class. The renderer for the + * {@link Object} class cannot be unregistered.

    + */ + public void unregister(final Class c) + { + if (c == Object.class) + throw new IllegalArgumentException + ("Renderer for Object cannot be unregistered."); + renderers.put(c, null); + } + + + + /** + *

    Renders an object in a tree cell depending of the object's + * class.

    + * + * @see TreeCellRenderer#getTreeCellRendererComponent + */ + public Component getTreeCellRendererComponent + (final JTree tree, final Object value, final boolean selected, + final boolean expanded, final boolean leaf, final int row, + final boolean hasFocus) + { + final String NULL = "null"; + TreeCellRenderer r; + Object userObject; + if (value == null) + userObject = NULL; + else + { + userObject = ((DefaultMutableTreeNode) value).getUserObject(); + if (userObject == null) + userObject = NULL; + } + r = findRenderer(userObject.getClass()); + return r.getTreeCellRendererComponent + (tree, value, selected, expanded, leaf, row, + hasFocus); + } + + + + /** + *

    Find the renderer for the specified class.

    + */ + protected TreeCellRenderer findRenderer(final Class c) + { + final TreeCellRenderer r = (TreeCellRenderer) renderers.get(c); + if (r != null) + /* The class has a renderer. */ + return r; + + /* The class has no renderer, try the superclass, if any. */ + final Class superclass = c.getSuperclass(); + if (superclass != null) { + return findRenderer(superclass); + } + return null; + } + +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/POIBrowser.java b/poi-examples/src/main/java/poi/poifs/poibrowser/POIBrowser.java new file mode 100644 index 0000000000..7dc487db85 --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/POIBrowser.java @@ -0,0 +1,132 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.FileInputStream; +import java.io.IOException; + +import javax.swing.JFrame; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.MutableTreeNode; + +import org.apache.poi.poifs.eventfilesystem.POIFSReader; + +/** + *

    The main class of the POI Browser. It shows the structure of POI + * filesystems (Microsoft Office documents) in a {@link + * JTree}. Specify their filenames on the command line!

    + * + * @see POIFSReader + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class POIBrowser extends JFrame +{ + + /** + *

    The tree's root node must be visible to all methods.

    + */ + protected MutableTreeNode rootNode; + + + + /** + *

    Takes a bunch of file names as command line parameters, + * opens each of them as a POI filesystem and displays their + * internal structures in a {@link JTree}.

    + */ + public static void main(String[] args) + { + new POIBrowser().run(args); + } + + + + protected void run(String[] args) + { + addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + System.exit(0); + } + }); + + /* Create the tree model with a root node. The latter is + * invisible but it must be present because a tree model + * always needs a root. */ + rootNode = new DefaultMutableTreeNode("POI Filesystems"); + DefaultTreeModel treeModel = new DefaultTreeModel(rootNode); + + /* Create the tree UI element. */ + final JTree treeUI = new JTree(treeModel); + getContentPane().add(new JScrollPane(treeUI)); + + /* Add the POI filesystems to the tree. */ + int displayedFiles = 0; + for (int i = 0; i < args.length; i++) + { + final String filename = args[i]; + try + { + POIFSReader r = new POIFSReader(); + r.registerListener(new TreeReaderListener(filename, rootNode)); + r.read(new FileInputStream(filename)); + displayedFiles++; + } + catch (IOException ex) + { + System.err.println(filename + ": " + ex); + } + catch (Throwable t) + { + System.err.println("Unexpected exception while reading \"" + + filename + "\":"); + t.printStackTrace(System.err); + } + } + + /* Exit if there is no file to display (none specified or only + * files with problems). */ + if (displayedFiles == 0) + { + System.out.println("No POI filesystem(s) to display."); + System.exit(0); + } + + /* Make the tree UI element visible. */ + treeUI.setRootVisible(true); + treeUI.setShowsRootHandles(true); + ExtendableTreeCellRenderer etcr = new ExtendableTreeCellRenderer(); + etcr.register(DocumentDescriptor.class, + new DocumentDescriptorRenderer()); + etcr.register(PropertySetDescriptor.class, + new PropertySetDescriptorRenderer()); + treeUI.setCellRenderer(etcr); + setSize(600, 450); + setTitle("POI Browser 0.09"); + setVisible(true); + } + +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/PropertySetDescriptor.java b/poi-examples/src/main/java/poi/poifs/poibrowser/PropertySetDescriptor.java new file mode 100644 index 0000000000..4596d0260d --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/PropertySetDescriptor.java @@ -0,0 +1,77 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import org.apache.poi.hpsf.MarkUnsupportedException; +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.PropertySet; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.poifs.filesystem.DocumentInputStream; +import org.apache.poi.poifs.filesystem.POIFSDocumentPath; + +/** + *

    Describes the most important (whatever that is) features of a + * stream containing a {@link PropertySet}.

    + * + * @author Rainer Klute (klute@rainer-klute.de) + */ +public class PropertySetDescriptor extends DocumentDescriptor +{ + + protected PropertySet propertySet; + + /** + *

    Returns this {@link PropertySetDescriptor}'s {@link + * PropertySet}.

    + */ + public PropertySet getPropertySet() + { + return propertySet; + } + + + + /** + *

    Creates a {@link PropertySetDescriptor} by reading a {@link + * PropertySet} from a {@link DocumentInputStream}.

    + * + * @param name The stream's name. + * + * @param path The stream's path in the POI filesystem hierarchy. + * + * @param stream The stream. + * + * @param nrOfBytesToDump The maximum number of bytes to display in a + * dump starting at the beginning of the stream. + */ + public PropertySetDescriptor(final String name, + final POIFSDocumentPath path, + final DocumentInputStream stream, + final int nrOfBytesToDump) + throws NoPropertySetStreamException, + MarkUnsupportedException, UnsupportedEncodingException, + IOException + { + super(name, path, stream, nrOfBytesToDump); + propertySet = PropertySetFactory.create(stream); + } + +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java b/poi-examples/src/main/java/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java new file mode 100644 index 0000000000..75277d2f34 --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java @@ -0,0 +1,171 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; +import java.util.Iterator; +import java.util.List; + +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; + +import org.apache.poi.hpsf.Property; +import org.apache.poi.hpsf.PropertySet; +import org.apache.poi.hpsf.Section; +import org.apache.poi.hpsf.SummaryInformation; + +/** + *

    Renders a {@link PropertySetDescriptor} by more or less dumping + * the stuff into a {@link JTextArea}.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class PropertySetDescriptorRenderer extends DocumentDescriptorRenderer +{ + + public Component getTreeCellRendererComponent(final JTree tree, + final Object value, + final boolean selected, + final boolean expanded, + final boolean leaf, + final int row, + final boolean hasFocus) + { + final PropertySetDescriptor d = (PropertySetDescriptor) + ((DefaultMutableTreeNode) value).getUserObject(); + final PropertySet ps = d.getPropertySet(); + final JPanel p = new JPanel(); + final JTextArea text = new JTextArea(); + text.setBackground(new Color(200, 255, 200)); + text.setFont(new Font("Monospaced", Font.PLAIN, 10)); + text.append(renderAsString(d)); + text.append("\nByte order: " + + Codec.hexEncode((short) ps.getByteOrder())); + text.append("\nFormat: " + + Codec.hexEncode((short) ps.getFormat())); + text.append("\nOS version: " + + Codec.hexEncode(ps.getOSVersion())); + text.append("\nClass ID: " + + Codec.hexEncode(ps.getClassID())); + text.append("\nSection count: " + ps.getSectionCount()); + text.append(sectionsToString(ps.getSections())); + p.add(text); + + if (ps instanceof SummaryInformation) + { + /* Use the convenience methods. */ + final SummaryInformation si = (SummaryInformation) ps; + text.append("\n"); + text.append("\nTitle: " + si.getTitle()); + text.append("\nSubject: " + si.getSubject()); + text.append("\nAuthor: " + si.getAuthor()); + text.append("\nKeywords: " + si.getKeywords()); + text.append("\nComments: " + si.getComments()); + text.append("\nTemplate: " + si.getTemplate()); + text.append("\nLast Author: " + si.getLastAuthor()); + text.append("\nRev. Number: " + si.getRevNumber()); + text.append("\nEdit Time: " + si.getEditTime()); + text.append("\nLast Printed: " + si.getLastPrinted()); + text.append("\nCreate Date/Time: " + si.getCreateDateTime()); + text.append("\nLast Save Date/Time: " + si.getLastSaveDateTime()); + text.append("\nPage Count: " + si.getPageCount()); + text.append("\nWord Count: " + si.getWordCount()); + text.append("\nChar Count: " + si.getCharCount()); + // text.append("\nThumbnail: " + si.getThumbnail()); + text.append("\nApplication Name: " + si.getApplicationName()); + text.append("\nSecurity: " + si.getSecurity()); + } + + if (selected) + Util.invert(text); + return p; + } + + + + /** + *

    Returns a string representation of a list of {@link + * Section}s.

    + */ + protected String sectionsToString(final List sections) + { + final StringBuffer b = new StringBuffer(); + int count = 1; + for (Iterator i = sections.iterator(); i.hasNext();) + { + Section s = (Section) i.next(); + String d = toString(s, "Section " + count++); + b.append(d); + } + return b.toString(); + } + + + + /** + *

    Returns a string representation of a {@link Section}.

    + * @param s the section + * @param name the section's name + * @return a string representation of the {@link Section} + */ + protected String toString(final Section s, final String name) + { + final StringBuffer b = new StringBuffer(); + b.append("\n" + name + " Format ID: "); + b.append(Codec.hexEncode(s.getFormatID())); + b.append("\n" + name + " Offset: " + s.getOffset()); + b.append("\n" + name + " Section size: " + s.getSize()); + b.append("\n" + name + " Property count: " + s.getPropertyCount()); + + final Property[] properties = s.getProperties(); + for (int i = 0; i < properties.length; i++) + { + final Property p = properties[i]; + final long id = p.getID(); + final long type = p.getType(); + final Object value = p.getValue(); + b.append('\n'); + b.append(name); + b.append(", Name: "); + b.append(id); + b.append(" ("); + b.append(s.getPIDString(id)); + b.append("), Type: "); + b.append(type); + b.append(", Value: "); + if (value instanceof byte[]) + { + byte[] b2 = (byte[]) value; + b.append("0x" + Codec.hexEncode(b2, 0, 4)); + b.append(' '); + b.append("0x" + Codec.hexEncode(b2, 4, b2.length - 4)); + } + else if (value != null) + b.append(value.toString()); + else + b.append("null"); + } + return b.toString(); + } + +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/TreeReaderListener.java b/poi-examples/src/main/java/poi/poifs/poibrowser/TreeReaderListener.java new file mode 100644 index 0000000000..34b59eb458 --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/TreeReaderListener.java @@ -0,0 +1,219 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.util.HashMap; +import java.util.Map; + +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.MutableTreeNode; + +import org.apache.poi.hpsf.HPSFException; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; +import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; +import org.apache.poi.poifs.filesystem.DocumentInputStream; +import org.apache.poi.poifs.filesystem.POIFSDocumentPath; + +/** + *

    Organizes document information in a tree model in order to be + * e.g. displayed in a Swing {@link javax.swing.JTree}. An instance of this + * class is created with a root tree node ({@link MutableTreeNode}) and + * registered as a {@link POIFSReaderListener} with a {@link + * org.apache.poi.poifs.eventfilesystem.POIFSReader}. While the latter processes + * a POI filesystem it calls this class' {@link #processPOIFSReaderEvent} for + * each document it has been registered for. This method appends the document it + * processes at the appropriate position into the tree rooted at the + * above mentioned root tree node.

    + * + *

    The root tree node should be the root tree node of a {@link + * javax.swing.tree.TreeModel}.

    + * + *

    A top-level element in the tree model, i.e. an immediate child + * node of the root node, describes a POI filesystem as such. It is + * suggested to use the file's name (as seen by the operating system) + * but it could be any other string.

    + * + *

    The value of a tree node is a {@link DocumentDescriptor}. Unlike + * a {@link org.apache.poi.poifs.filesystem.POIFSDocument} which may be as heavy + * as many megabytes, an instance of {@link DocumentDescriptor} is a + * light-weight object and contains only some meta-information about a + * document.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class TreeReaderListener implements POIFSReaderListener +{ + + /** + *

    The tree's root node. POI filesystems get attached to this + * node as children.

    + */ + protected MutableTreeNode rootNode; + + /** + *

    Maps filenames and POI document paths to their associated + * tree nodes.

    + */ + protected Map pathToNode; + + /** + *

    The name of the file this {@link TreeReaderListener} + * processes. It is used to identify a top-level element in the + * tree. Alternatively any other string can be used. It is just a + * label which should identify a POI filesystem.

    + */ + protected String filename; + + + + /** + *

    Creates a {@link TreeReaderListener} which should then be + * registered with a + * {@link org.apache.poi.poifs.eventfilesystem.POIFSReader}.

    + * + * @param filename The name of the POI filesystem, i.e. the name + * of the file the POI filesystem resides in. Alternatively any + * other string can be used. + * + * @param rootNode All document information will be attached as + * descendands to this tree node. + */ + public TreeReaderListener(final String filename, + final MutableTreeNode rootNode) + { + this.filename = filename; + this.rootNode = rootNode; + pathToNode = new HashMap(15); // Should be a reasonable guess. + } + + + + /**

    The number of bytes to dump.

    */ + private int nrOfBytes = 50; + + public void setNrOfBytes(final int nrOfBytes) + { + this.nrOfBytes = nrOfBytes; + } + + public int getNrOfBytes() + { + return nrOfBytes; + } + + + + /** + *

    A document in the POI filesystem has been opened for + * reading. This method retrieves properties of the document and + * adds them to a tree model.

    + */ + public void processPOIFSReaderEvent(final POIFSReaderEvent event) + { + DocumentDescriptor d; + final DocumentInputStream is = event.getStream(); + if (!is.markSupported()) + throw new UnsupportedOperationException(is.getClass().getName() + + " does not support mark()."); + + /* Try do handle this document as a property set. We receive + * an exception if is no property set and handle it as a + * document of some other format. We are not concerned about + * that document's details. */ + try + { + d = new PropertySetDescriptor(event.getName(), event.getPath(), + is, nrOfBytes); + } + catch (HPSFException ex) + { + d = new DocumentDescriptor(event.getName(), event.getPath(), + is, nrOfBytes); + } + catch (Throwable t) + { + System.err.println + ("Unexpected exception while processing " + + event.getName() + " in " + event.getPath().toString()); + t.printStackTrace(System.err); + throw new RuntimeException(t.getMessage()); + } + + is.close(); + + final MutableTreeNode parentNode = getNode(d.path, filename, rootNode); + final MutableTreeNode nameNode = new DefaultMutableTreeNode(d.name); + parentNode.insert(nameNode, 0); + final MutableTreeNode dNode = new DefaultMutableTreeNode(d); + nameNode.insert(dNode, 0); + } + + + + /** + *

    Locates the parent node for a document entry in the tree + * model. If the parent node does not yet exist it will be + * created, too. This is done recursively, if needed.

    + * + * @param path The tree node for this path is located. + * + * @param fsName The name of the POI filesystem. This is just a + * string which is displayed in the tree at the top lovel. + * + * @param root The root node. + */ + private MutableTreeNode getNode(final POIFSDocumentPath path, + final String fsName, + final MutableTreeNode root) + { + MutableTreeNode n = (MutableTreeNode) pathToNode.get(path); + if (n != null) + /* Node found in map, just return it. */ + return n; + if (path.length() == 0) + { + /* This is the root path of the POI filesystem. Its tree + * node is resp. must be located below the tree node of + * the POI filesystem itself. This is a tree node with the + * POI filesystem's name (this the operating system file's + * name) as its key it the path-to-node map. */ + n = (MutableTreeNode) pathToNode.get(fsName); + if (n == null) + { + /* A tree node for the POI filesystem does not yet + * exist. */ + n = new DefaultMutableTreeNode(fsName); + pathToNode.put(fsName, n); + root.insert(n, 0); + } + return n; + } + /* else - The path is somewhere down in the POI filesystem's + * hierarchy. We need the tree node of this path's parent + * and attach our new node to it. */ + final String name = path.getComponent(path.length() - 1); + final POIFSDocumentPath parentPath = path.getParent(); + final MutableTreeNode parentNode = + getNode(parentPath, fsName, root); + n = new DefaultMutableTreeNode(name); + pathToNode.put(path, n); + parentNode.insert(n, 0); + return n; + } +} diff --git a/poi-examples/src/main/java/poi/poifs/poibrowser/Util.java b/poi-examples/src/main/java/poi/poifs/poibrowser/Util.java new file mode 100644 index 0000000000..6f5bc6f424 --- /dev/null +++ b/poi-examples/src/main/java/poi/poifs/poibrowser/Util.java @@ -0,0 +1,44 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.poifs.poibrowser; + +import java.awt.*; +import javax.swing.*; + +/** + *

    Contains various (well, just one at the moment) static utility + * methods.

    + * + * @author Rainer Klute <klute@rainer-klute.de> + */ +public class Util { + + /** + *

    Makes a Swing component inverted by swapping its foreground + * and background colors. Hint: Depending on your needs it might + * also be a good idea to call c.setOpaque(true).

    + */ + public static void invert(JComponent c) { + Color invBackground = c.getForeground(); + Color invForeground = c.getBackground(); + c.setBackground(invBackground); + c.setForeground(invForeground); + } +} + diff --git a/poi-examples/src/main/java/poi/ss/examples/AddDimensionedImage.java b/poi-examples/src/main/java/poi/ss/examples/AddDimensionedImage.java new file mode 100644 index 0000000000..6eb493ca92 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/AddDimensionedImage.java @@ -0,0 +1,1046 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + + +package org.apache.poi.ss.examples; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.ss.usermodel.ClientAnchor; +import org.apache.poi.ss.usermodel.Drawing; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.util.IOUtils; + + +/** + * Demonstrates how to add an image to a worksheet and set that images size + * to a specific number of millimetres irrespective of the width of the columns + * or height of the rows. Overridden methods are provided so that the location + * of the image - the cells row and column coordinates that define the top + * left hand corners of the image - can be identified either in the familiar + * Excel manner - A1 for instance - or using POI's methodology of a column and + * row index where 0, 0 would indicate cell A1. + * + * The best way to make use of these techniques is to delay adding the image to + * the sheet until all other work has been completed. That way, the sizes of + * all rows and columns will have been adjusted - assuming that step was + * necessary. Even though the anchors type is set to prevent the image moving + * or re-sizing, this setting does not have any effect until the sheet is being + * viewed using the Excel application. + * + * The key to the process is the ClientAnchor class. It defines methods that allow + * us to define the location of an image by specifying the following; + * + * * How far - in terms of coordinate positions - the image should be inset + * from the left hand border of a cell. + * * How far - in terms of coordinate positions - the image should be inset + * from the from the top of the cell. + * * How far - in terms of coordinate positions - the right hand edge of + * the image should protrude into a cell (measured from the cells left hand + * edge to the images right hand edge). + * * How far - in terms of coordinate positions - the bottom edge of the + * image should protrude into a row (measured from the cells top edge to + * the images bottom edge). + * * The index of the column that contains the cell whose top left hand + * corner should be aligned with the top left hand corner of the image. + * * The index of the row that contains the cell whose top left hand corner + * should be aligned with the images top left hand corner. + * * The index of the column that contains the cell whose top left hand + * corner should be aligned with the images bottom right hand corner + * * The index number of the row that contains the cell whose top left + * hand corner should be aligned with the images bottom right hand corner. + * + * It can be used to add an image into cell A1, for example, in the following + * manner; + * + * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); + * + * anchor.setDx1(0); + * anchor.setDy1(0); + * anchor.setDx2(0); + * anchor.setDy2(0); + * anchor.setCol1(0); + * anchor.setRow1(0); + * anchor.setCol2(1); + * anchor.setRow2(1); + * + * Taken together, the first four methods define the locations of the top left + * and bottom right hand corners of the image if you imagine that the image is + * represented by a simple rectangle. The setDx1() and setDy1() methods locate + * the top left hand corner of the image while setDx2() and and Dy2() locate the + * bottom right hand corner of the image. An individual image can be inserted + * into a single cell or is can lie across many cells and the latter four methods + * are used to define just where the image should be positioned. They do this by + * again by identifying where the top left and bottom right hand corners of the + * image should be located but this time in terms of the indexes of the cells + * in which those corners should be located. The setCol1() and setRow1() methods + * together identify the cell that should contain the top left hand corner of + * the image while setCol2() and setRow2() do the same for the images bottom + * right hand corner. + * + * Knowing that, it is possible to look again at the example above and to see + * that the top left hand corner of the image will be located in cell A1 (0, 0) + * and it will be aligned with the very top left hand corner of the cell. Likewise, + * the bottom right hand corner of the image will be located in cell B2 (1, 1) and + * it will again be aligned with the top left hand corner of the cell. This has the + * effect of making the image seem to occupy the whole of cell A1. Interestingly, it + * also has an effect on the images resizing behaviour because testing has + * demonstrated that if the image is wholly contained within one cell and is not + * 'attached' for want of a better word, to a neighbouring cell, then that image + * will not increase in size in response to the user dragging the column wider + * or the cell higher. + * + * The following example demonstrates a slightly different way to insert an + * image into cell A1 and to ensure that it occupies the whole of the cell. This + * is accomplished by specifying the the images bottom right hand corner should be + * aligned with the bottom right hand corner of the cell. It is also a case + * where the image will not increase in size if the user increases the size of + * the enclosing cell - irrespective of the anchors type - but it will reduce in + * size if the cell is made smaller. + * + * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); + * + * anchor.setDx1(0); + * anchor.setDy1(0); + * anchor.setDx2(1023); + * anchor.setDy2(255); + * anchor.setCol1(0); + * anchor.setRow1(0); + * anchor.setCol2(0); + * anchor.setRow2(0); + * + * Note that the final four method calls all pass the same value and seem to + * indicate that the images top left hand corner is aligned with the top left + * hand corner of cell A1 and that it's bottom right hand corner is also + * aligned with the top left hand corner of cell A1. Yet, running this code + * would see the image fully occupying cell A1. That is the result of the + * values passed to parameters three and four; these I have referred to as + * determining the images coordinates within the cell. They indicate that the + * image should occupy - in order - the full width of the column and the full + * height of the row. + * + * The co-ordinate values shown are the maxima; and they are independent of + * row height/column width and of the font used. Passing 255 will always result + * in the image occupying the full height of the row and passing 1023 will + * always result in the image occupying the full width of the column. They help + * in situations where an image is larger than a column/row and must overlap + * into the next column/row. Using them does mean, however, that it is often + * necessary to perform conversions between Excels characters units, points, + * pixels and millimetres in order to establish how many rows/columns an image + * should occupy and just what the various insets ought to be. + * + * Note that the setDx1(int) and setDy1(int) methods of the ClientAchor class + * are not made use of in the code that follows. It would be fairly trivial + * however to extend this example further and provide methods that would centre + * an image within a cell or allow the user to specify that a plain border a + * fixed number of millimetres wide should wrap around the image. Those first + * two parameters would make this sort of functionality perfectly possible. + * + * Owing to the various conversions used, the actual size of the image may vary + * from that required; testing has so far found this to be in the region of + * plus or minus two millimetres. Most likely by modifying the way the + * calculations are performed - possibly using double(s) throughout and + * rounding the values at the correct point - it is likely that these errors + * could be reduced or removed. + * + * A note concerning Excels image resizing behaviour. The ClientAnchor + * class contains a method called setAnchorType(int) which can be used to + * determine how Excel will resize an image in response to the user increasing + * or decreasing the dimensions of the cell containing the image. There are + * three values that can be passed to this method; 0 = To move and size the + * image with the cell, 2 = To move but don't size the image with the cell, + * 3 = To prevent the image from moving or being resized along with the cell. If + * an image is inserted using this class and placed into a single cell then if + * the setAnchorType(int) method is called and a value of either 0 or 2 passed + * to it, the resultant resizing behaviour may be a surprise. The image will not + * grow in size of the column is made wider or the row higher but it will shrink + * if the columns width or rows height are reduced. + * + * @author Mark Beardsley [msb at apache.org] and Mark Southern [southern at scripps.edu] + * @version 1.00 5th August 2009. + * 2.00 26th February 2010. + * Ported to make use of the the SS usermodel classes. + * Ability to reuse the Drawing Patriarch so that multiple images + * can be inserted without unintentionally erasing earlier images. + * Check on image type added; i.e. jpg, jpeg or png. + * The String used to contain the files name is now converted + * into a URL. + * 2.10 17th May 2012 + * Corrected gross error that occurred when using the code with + * XSSF or SXSSF workbooks. In short, the code did not correctly + * calculate the size of the image(s) owing to the use of EMUs + * within the OOXML file format. That problem has largely been + * corrected although it should be mentioned that images are not + * sized with the same level of accuracy. Discrepancies of up to + * 2mm have been noted in testing. Further investigation will + * continue to rectify this issue. + */ +public class AddDimensionedImage { + + // Four constants that determine how - and indeed whether - the rows + // and columns an image may overlie should be expanded to accomodate that + // image. + // Passing EXPAND_ROW will result in the height of a row being increased + // to accomodate the image if it is not already larger. The image will + // be layed across one or more columns. + // Passing EXPAND_COLUMN will result in the width of the column being + // increased to accomodate the image if it is not already larger. The image + // will be layed across one or many rows. + // Passing EXPAND_ROW_AND_COLUMN will result in the height of the row + // bing increased along with the width of the column to accomdate the + // image if either is not already larger. + // Passing OVERLAY_ROW_AND_COLUMN will result in the image being layed + // over one or more rows and columns. No row or column will be resized, + // instead, code will determine how many rows and columns the image should + // overlie. + public static final int EXPAND_ROW = 1; + public static final int EXPAND_COLUMN = 2; + public static final int EXPAND_ROW_AND_COLUMN = 3; + public static final int OVERLAY_ROW_AND_COLUMN = 7; + + // Modified to support EMU - English Metric Units - used within the OOXML + // workbooks, this multoplier is used to convert between measurements in + // millimetres and in EMUs + private static final int EMU_PER_MM = 36000; + + /** + * Add an image to a worksheet. + * + * @param cellNumber A String that contains the location of the cell whose + * top left hand corner should be aligned with the top + * left hand corner of the image; for example "A1", "A2" + * etc. This is to support the familiar Excel syntax. + * Whilst images are are not actually inserted into cells + * this provides a convenient method of indicating where + * the image should be positioned on the sheet. + * @param sheet A reference to the sheet that contains the cell referenced + * above. + * @param drawing An instance of the DrawingPatriarch class. This is now + * passed into the method where it was, previously, recovered + * from the sheet in order to allow multiple pictures be + * inserted. If the patriarch was not 'cached in this manner + * each time it was created any previously positioned images + * would be simply over-written. + * @param imageFile An instance of the URL class that encapsulates the name + * of and path to the image that is to be 'inserted into' + * the sheet. + * @param reqImageWidthMM A primitive double that contains the required + * width of the image in millimetres. + * @param reqImageHeightMM A primitive double that contains the required + * height of the image in millimetres. + * @param resizeBehaviour A primitive int whose value will determine how + * the code should react if the image is larger than + * the cell referenced by the cellNumber parameter. + * Four constants are provided to determine what + * should happen; + * AddDimensionedImage.EXPAND_ROW + * AddDimensionedImage.EXPAND_COLUMN + * AddDimensionedImage.EXPAND_ROW_AND_COLUMN + * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN + * @throws java.io.FileNotFoundException If the file containing the image + * cannot be located. + * @throws java.io.IOException If a problem occurs whilst reading the file + * of image data. + * @throws java.lang.IllegalArgumentException If an invalid value is passed + * to the resizeBehaviour + * parameter. + */ + public void addImageToSheet(String cellNumber, Sheet sheet, Drawing drawing, + URL imageFile, double reqImageWidthMM, double reqImageHeightMM, + int resizeBehaviour) throws IOException, IllegalArgumentException { + // Convert the String into column and row indices then chain the + // call to the overridden addImageToSheet() method. + CellReference cellRef = new CellReference(cellNumber); + this.addImageToSheet(cellRef.getCol(), cellRef.getRow(), sheet, drawing, + imageFile, reqImageWidthMM, reqImageHeightMM,resizeBehaviour); + } + + /** + * Add an image to a worksheet. + * + * @param colNumber A primitive int that contains the index number of a + * column on the worksheet; POI column indices are zero + * based. Together with the rowNumber parameter's value, + * this parameter identifies a cell on the worksheet. The + * images top left hand corner will be aligned with the + * top left hand corner of this cell. + * @param rowNumber A primitive int that contains the index number of a row + * on the worksheet; POI row indices are zero based. + * Together with the rowNumber parameter's value, this + * parameter identifies a cell on the worksheet. The + * images top left hand corner will be aligned with the + * top left hand corner of this cell. + * @param sheet A reference to the sheet that contains the cell identified + * by the two parameters above. + * @param drawing An instance of the DrawingPatriarch class. This is now + * passed into the method where it was, previously, recovered + * from the sheet in order to allow multiple pictures be + * inserted. If the patriarch was not 'cached in this manner + * each time it was created any previously positioned images + * would be simply over-written. + * @param imageFile An instance of the URL class that encapsulates the name + * of and path to the image that is to be 'inserted into' + * the sheet. + * @param reqImageWidthMM A primitive double that contains the required + * width of the image in millimetres. + * @param reqImageHeightMM A primitive double that contains the required + * height of the image in millimetres. + * @param resizeBehaviour A primitive int whose value will determine how + * the code should react if the image is larger than + * the cell referenced by the colNumber and + * rowNumber parameters. Four constants are provided + * to determine what should happen; + * AddDimensionedImage.EXPAND_ROW + * AddDimensionedImage.EXPAND_COLUMN + * AddDimensionedImage.EXPAND_ROW_AND_COLUMN + * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN + * @throws java.io.FileNotFoundException If the file containing the image + * cannot be located. + * @throws java.io.IOException If a problem occurs whilst reading the file + * of image data. + * @throws java.lang.IllegalArgumentException If an invalid value is passed + * to the resizeBehaviour + * parameter or if the extension + * of the image file indicates that + * it is of a type that cannot + * currently be added to the worksheet. + */ + public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing drawing, + URL imageFile, double reqImageWidthMM, double reqImageHeightMM, + int resizeBehaviour) throws IOException, + IllegalArgumentException { + ClientAnchor anchor = null; + ClientAnchorDetail rowClientAnchorDetail = null; + ClientAnchorDetail colClientAnchorDetail = null; + int imageType = 0; + + // Validate the resizeBehaviour parameter. + if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) && + (resizeBehaviour != AddDimensionedImage.EXPAND_ROW) && + (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN) && + (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) { + throw new IllegalArgumentException("Invalid value passed to the " + + "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()"); + } + + // Call methods to calculate how the image and sheet should be + // manipulated to accomodate the image; columns and then rows. + colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, + reqImageWidthMM, resizeBehaviour); + rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, + reqImageHeightMM, resizeBehaviour); + + // Having determined if and how to resize the rows, columns and/or the + // image, create the ClientAnchor object to position the image on + // the worksheet. Note how the two ClientAnchorDetail records are + // interrogated to recover the row/column co-ordinates and any insets. + // The first two parameters are not used currently but could be if the + // need arose to extend the functionality of this code by adding the + // ability to specify that a clear 'border' be placed around the image. + anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); + + anchor.setDx1(0); + anchor.setDy1(0); + anchor.setDx2(colClientAnchorDetail.getInset()); + anchor.setDy2(rowClientAnchorDetail.getInset()); + anchor.setCol1(colClientAnchorDetail.getFromIndex()); + anchor.setRow1(rowClientAnchorDetail.getFromIndex()); + anchor.setCol2(colClientAnchorDetail.getToIndex()); + anchor.setRow2(rowClientAnchorDetail.getToIndex()); + + // For now, set the anchor type to do not move or resize the + // image as the size of the row/column is adjusted. This could easilly + // become another parameter passed to the method. Please read the note + // above regarding the behaviour of image resizing. + anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE); + + // Now, add the picture to the workbook. Note that unlike the similar + // method in the HSSF Examples section, the image type is checked. First, + // the image files location is identified by interrogating the URL passed + // to the method, the images type is identified before it is added to the + // sheet. + String sURL = imageFile.toString().toLowerCase(); + if( sURL.endsWith(".png") ) { + imageType = Workbook.PICTURE_TYPE_PNG; + } + else if( sURL.endsWith("jpg") || sURL.endsWith(".jpeg") ) { + imageType = Workbook.PICTURE_TYPE_JPEG; + } + else { + throw new IllegalArgumentException("Invalid Image file : " + + sURL); + } + int index = sheet.getWorkbook().addPicture( + IOUtils.toByteArray(imageFile.openStream()), imageType); + drawing.createPicture(anchor, index); + } + + /** + * Determines whether the sheets columns should be re-sized to accomodate + * the image, adjusts the columns width if necessary and creates then + * returns a ClientAnchorDetail object that facilitates construction of + * an ClientAnchor that will fix the image on the sheet and establish + * it's size. + * + * @param sheet A reference to the sheet that will 'contain' the image. + * @param colNumber A primtive int that contains the index number of a + * column on the sheet. + * @param reqImageWidthMM A primitive double that contains the required + * width of the image in millimetres + * @param resizeBehaviour A primitive int whose value will indicate how the + * width of the column should be adjusted if the + * required width of the image is greater than the + * width of the column. + * @return An instance of the ClientAnchorDetail class that will contain + * the index number of the column containing the cell whose top + * left hand corner also defines the top left hand corner of the + * image, the index number column containing the cell whose top + * left hand corner also defines the bottom right hand corner of + * the image and an inset that determines how far the right hand + * edge of the image can protrude into the next column - expressed + * as a specific number of coordinate positions. + */ + private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber, + double reqImageWidthMM, int resizeBehaviour) { + + double colWidthMM = 0.0D; + double colCoordinatesPerMM = 0.0D; + int pictureWidthCoordinates = 0; + ClientAnchorDetail colClientAnchorDetail = null; + + // Get the colum's width in millimetres + colWidthMM = ConvertImageUnits.widthUnits2Millimetres( + (short)sheet.getColumnWidth(colNumber)); + + // Check that the column's width will accomodate the image at the + // required dimension. If the width of the column is LESS than the + // required width of the image, decide how the application should + // respond - resize the column or overlay the image across one or more + // columns. + if(colWidthMM < reqImageWidthMM) { + + // Should the column's width simply be expanded? + if((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN) || + (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { + // Set the width of the column by converting the required image + // width from millimetres into Excel's column width units. + sheet.setColumnWidth(colNumber, + ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM)); + // To make the image occupy the full width of the column, convert + // the required width of the image into co-ordinates. This value + // will become the inset for the ClientAnchorDetail class that + // is then instantiated. + if(sheet instanceof HSSFSheet) { + colWidthMM = reqImageWidthMM; + colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / + colWidthMM; + pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); + + } + else { + pictureWidthCoordinates = (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM; + } + colClientAnchorDetail = new ClientAnchorDetail(colNumber, + colNumber, pictureWidthCoordinates); + } + // If the user has chosen to overlay both rows and columns or just + // to expand ONLY the size of the rows, then calculate how to lay + // the image out across one or more columns. + else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || + (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) { + colClientAnchorDetail = this.calculateColumnLocation(sheet, + colNumber, reqImageWidthMM); + } + } + // If the column is wider than the image. + else { + if(sheet instanceof HSSFSheet) { + // Mow many co-ordinate positions are there per millimetre? + colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / + colWidthMM; + // Given the width of the image, what should be it's co-ordinate? + pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); + } + else { + pictureWidthCoordinates = (int)reqImageWidthMM * + AddDimensionedImage.EMU_PER_MM; + } + colClientAnchorDetail = new ClientAnchorDetail(colNumber, + colNumber, pictureWidthCoordinates); + } + return(colClientAnchorDetail); + } + + /** + * Determines whether the sheets row should be re-sized to accomodate + * the image, adjusts the rows height if necessary and creates then + * returns a ClientAnchorDetail object that facilitates construction of + * a ClientAnchor that will fix the image on the sheet and establish + * it's size. + * + * @param sheet A reference to the sheet that will 'contain' the image. + * @param rowNumber A primitive int that contains the index number of a + * row on the sheet. + * @param reqImageHeightMM A primitive double that contains the required + * height of the image in millimetres + * @param resizeBehaviour A primitive int whose value will indicate how the + * height of the row should be adjusted if the + * required height of the image is greater than the + * height of the row. + * @return An instance of the ClientAnchorDetail class that will contain + * the index number of the row containing the cell whose top + * left hand corner also defines the top left hand corner of the + * image, the index number of the row containing the cell whose + * top left hand corner also defines the bottom right hand + * corner of the image and an inset that determines how far the + * bottom edge of the image can protrude into the next (lower) + * row - expressed as a specific number of coordinate positions. + */ + private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber, + double reqImageHeightMM, int resizeBehaviour) { + Row row = null; + double rowHeightMM = 0.0D; + double rowCoordinatesPerMM = 0.0D; + int pictureHeightCoordinates = 0; + ClientAnchorDetail rowClientAnchorDetail = null; + + // Get the row and it's height + row = sheet.getRow(rowNumber); + if(row == null) { + // Create row if it does not exist. + row = sheet.createRow(rowNumber); + } + + // Get the row's height in millimetres + rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE; + + // Check that the row's height will accomodate the image at the required + // dimensions. If the height of the row is LESS than the required height + // of the image, decide how the application should respond - resize the + // row or overlay the image across a series of rows. + if(rowHeightMM < reqImageHeightMM) { + if((resizeBehaviour == AddDimensionedImage.EXPAND_ROW) || + (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { + row.setHeightInPoints((float)(reqImageHeightMM * + ConvertImageUnits.POINTS_PER_MILLIMETRE)); + if(sheet instanceof HSSFSheet) { + rowHeightMM = reqImageHeightMM; + rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / + rowHeightMM; + pictureHeightCoordinates = (int)(reqImageHeightMM * + rowCoordinatesPerMM); + } + else { + pictureHeightCoordinates = (int)(reqImageHeightMM * + AddDimensionedImage.EMU_PER_MM); + } + rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, + rowNumber, pictureHeightCoordinates); + } + // If the user has chosen to overlay both rows and columns or just + // to expand ONLY the size of the columns, then calculate how to lay + // the image out ver one or more rows. + else if((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || + (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) { + rowClientAnchorDetail = this.calculateRowLocation(sheet, + rowNumber, reqImageHeightMM); + } + } + // Else, if the image is smaller than the space available + else { + if(sheet instanceof HSSFSheet) { + rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / + rowHeightMM; + pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); + } + else { + pictureHeightCoordinates = (int)(reqImageHeightMM * + AddDimensionedImage.EMU_PER_MM); + } + rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, + rowNumber, pictureHeightCoordinates); + } + return(rowClientAnchorDetail); + } + + /** + * If the image is to overlie more than one column, calculations need to be + * performed to determine how many columns and whether the image will + * overlie just a part of one column in order to be presented at the + * required size. + * + * @param sheet The sheet that will 'contain' the image. + * @param startingColumn A primitive int whose value is the index of the + * column that contains the cell whose top left hand + * corner should be aligned with the top left hand + * corner of the image. + * @param reqImageWidthMM A primitive double whose value will indicate the + * required width of the image in millimetres. + * @return An instance of the ClientAnchorDetail class that will contain + * the index number of the column containing the cell whose top + * left hand corner also defines the top left hand corner of the + * image, the index number column containing the cell whose top + * left hand corner also defines the bottom right hand corner of + * the image and an inset that determines how far the right hand + * edge of the image can protrude into the next column - expressed + * as a specific number of coordinate positions. + */ + private ClientAnchorDetail calculateColumnLocation(Sheet sheet, + int startingColumn, + double reqImageWidthMM) { + ClientAnchorDetail anchorDetail = null; + double totalWidthMM = 0.0D; + double colWidthMM = 0.0D; + double overlapMM = 0.0D; + double coordinatePositionsPerMM = 0.0D; + int toColumn = startingColumn; + int inset = 0; + + // Calculate how many columns the image will have to + // span in order to be presented at the required size. + while(totalWidthMM < reqImageWidthMM) { + colWidthMM = ConvertImageUnits.widthUnits2Millimetres( + (short)(sheet.getColumnWidth(toColumn))); + // Note use of the cell border width constant. Testing with an image + // declared to fit exactly into one column demonstrated that it's + // width was greater than the width of the column the POI returned. + // Further, this difference was a constant value that I am assuming + // related to the cell's borders. Either way, that difference needs + // to be allowed for in this calculation. + totalWidthMM += (colWidthMM + ConvertImageUnits.CELL_BORDER_WIDTH_MILLIMETRES); + toColumn++; + } + // De-crement by one the last column value. + toColumn--; + // Highly unlikely that this will be true but, if the width of a series + // of columns is exactly equal to the required width of the image, then + // simply build a ClientAnchorDetail object with an inset equal to the + // total number of co-ordinate positions available in a column, a + // from column co-ordinate (top left hand corner) equal to the value + // of the startingColumn parameter and a to column co-ordinate equal + // to the toColumn variable. + // + // Convert both values to ints to perform the test. + if((int)totalWidthMM == (int)reqImageWidthMM) { + // A problem could occur if the image is sized to fit into one or + // more columns. If that occurs, the value in the toColumn variable + // will be in error. To overcome this, there are two options, to + // ibcrement the toColumn variable's value by one or to pass the + // total number of co-ordinate positions to the third paramater + // of the ClientAnchorDetail constructor. For no sepcific reason, + // the latter option is used below. + if(sheet instanceof HSSFSheet) { + anchorDetail = new ClientAnchorDetail(startingColumn, + toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS); + } + else { + anchorDetail = new ClientAnchorDetail(startingColumn, + toColumn, (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM); + } + } + // In this case, the image will overlap part of another column and it is + // necessary to calculate just how much - this will become the inset + // for the ClientAnchorDetail object. + else { + // Firstly, claculate how much of the image should overlap into + // the next column. + overlapMM = reqImageWidthMM - (totalWidthMM - colWidthMM); + + // When the required size is very close indded to the column size, + // the calcaulation above can produce a negative value. To prevent + // problems occuring in later caculations, this is simply removed + // be setting the overlapMM value to zero. + if(overlapMM < 0) { + overlapMM = 0.0D; + } + + if(sheet instanceof HSSFSheet) { + // Next, from the columns width, calculate how many co-ordinate + // positons there are per millimetre + coordinatePositionsPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / + colWidthMM; + // From this figure, determine how many co-ordinat positions to + // inset the left hand or bottom edge of the image. + inset = (int)(coordinatePositionsPerMM * overlapMM); + } + else { + inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM; + } + + // Now create the ClientAnchorDetail object, setting the from and to + // columns and the inset. + anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, inset); + } + return(anchorDetail); + } + + /** + * If the image is to overlie more than one rows, calculations need to be + * performed to determine how many rows and whether the image will + * overlie just a part of one row in order to be presented at the + * required size. + * + * @param sheet The sheet that will 'contain' the image. + * @param startingRow A primitive int whose value is the index of the row + * that contains the cell whose top left hand corner + * should be aligned with the top left hand corner of + * the image. + * @param reqImageHeightMM A primitive double whose value will indicate the + * required height of the image in millimetres. + * @return An instance of the ClientAnchorDetail class that will contain + * the index number of the row containing the cell whose top + * left hand corner also defines the top left hand corner of the + * image, the index number of the row containing the cell whose top + * left hand corner also defines the bottom right hand corner of + * the image and an inset that determines how far the bottom edge + * can protrude into the next (lower) row - expressed as a specific + * number of co-ordinate positions. + */ + private ClientAnchorDetail calculateRowLocation(Sheet sheet, + int startingRow, double reqImageHeightMM) { + ClientAnchorDetail clientAnchorDetail = null; + Row row = null; + double rowHeightMM = 0.0D; + double totalRowHeightMM = 0.0D; + double overlapMM = 0.0D; + double rowCoordinatesPerMM = 0.0D; + int toRow = startingRow; + int inset = 0; + + // Step through the rows in the sheet and accumulate a total of their + // heights. + while(totalRowHeightMM < reqImageHeightMM) { + row = sheet.getRow(toRow); + // Note, if the row does not already exist on the sheet then create + // it here. + if(row == null) { + row = sheet.createRow(toRow); + } + // Get the row's height in millimetres and add to the running total. + rowHeightMM = row.getHeightInPoints() / + ConvertImageUnits.POINTS_PER_MILLIMETRE; + totalRowHeightMM += rowHeightMM; + toRow++; + } + // Owing to the way the loop above works, the rowNumber will have been + // incremented one row too far. Undo that here. + toRow--; + // Check to see whether the image should occupy an exact number of + // rows. If so, build the ClientAnchorDetail record to point + // to those rows and with an inset of the total number of co-ordinate + // position in the row. + // + // To overcome problems that can occur with comparing double values for + // equality, cast both to int(s) to truncate the value; VERY crude and + // I do not really like it!! + if((int)totalRowHeightMM == (int)reqImageHeightMM) { + if(sheet instanceof HSSFSheet) { + clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, + ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS); + } + else { + clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, + (int)reqImageHeightMM * AddDimensionedImage.EMU_PER_MM); + } + } + else { + // Calculate how far the image will project into the next row. Note + // that the height of the last row assessed is subtracted from the + // total height of all rows assessed so far. + overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM); + + // To prevent an exception being thrown when the required width of + // the image is very close indeed to the column size. + if(overlapMM < 0) { + overlapMM = 0.0D; + } + + if(sheet instanceof HSSFSheet) { + rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / + rowHeightMM; + inset = (int)(overlapMM * rowCoordinatesPerMM); + } + else { + inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM; + } + clientAnchorDetail = new ClientAnchorDetail(startingRow, + toRow, inset); + } + return(clientAnchorDetail); + } + + /** + * The main entry point to the program. It contains code that demonstrates + * one way to use the program. + * + * Note, the code is not restricted to use on new workbooks only. If an + * image is to be inserted into an existing workbook. just open that + * workbook, gat a reference to a sheet and pass that; + * + * AddDimensionedImage addImage = new AddDimensionedImage(); + * + * File file = new File("....... Existing Workbook ......."); + * FileInputStream fis = new FileInputStream(file); + * Workbook workbook = new HSSFWorkbook(fis); + * HSSFSheet sheet = workbook.getSheetAt(0); + * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20, + * AddDimensionedImage.EXPAND.ROW); + * + * @param args the command line arguments + */ + public static void main(String[] args) { + String imageFile = null; + String outputFile = null; + FileOutputStream fos = null; + Workbook workbook = null; + Sheet sheet = null; + try { + if(args.length < 2){ + System.err.println("Usage: AddDimensionedImage imageFile outputFile"); + return; + } + workbook = new HSSFWorkbook(); // OR XSSFWorkbook + sheet = workbook.createSheet("Picture Test"); + imageFile = args[0]; + outputFile = args[1]; + new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(), + new File(imageFile).toURI().toURL(), 100, 40, + AddDimensionedImage.EXPAND_ROW_AND_COLUMN); + fos = new FileOutputStream(outputFile); + workbook.write(fos); + } + catch(FileNotFoundException fnfEx) { + System.out.println("Caught an: " + fnfEx.getClass().getName()); + System.out.println("Message: " + fnfEx.getMessage()); + System.out.println("Stacktrace follows..........."); + fnfEx.printStackTrace(System.out); + } + catch(IOException ioEx) { + System.out.println("Caught an: " + ioEx.getClass().getName()); + System.out.println("Message: " + ioEx.getMessage()); + System.out.println("Stacktrace follows..........."); + ioEx.printStackTrace(System.out); + } + finally { + if(fos != null) { + try { + fos.close(); + fos = null; + } + catch(IOException ioEx) { + // I G N O R E + } + } + } + } + + /** + * The HSSFClientAnchor class accepts eight arguments. In order, these are; + * + * * How far the left hand edge of the image is inset from the left hand + * edge of the cell + * * How far the top edge of the image is inset from the top of the cell + * * How far the right hand edge of the image is inset from the left + * hand edge of the cell + * * How far the bottom edge of the image is inset from the top of the + * cell. + * * Together, arguments five and six determine the column and row + * coordinates of the cell whose top left hand corner will be aligned + * with the images top left hand corner. + * * Together, arguments seven and eight determine the column and row + * coordinates of the cell whose top left hand corner will be aligned + * with the images bottom right hand corner. + * + * An instance of the ClientAnchorDetail class provides three of the eight + * parameters, one of the coordinates for the images top left hand corner, + * one of the coordinates for the images bottom right hand corner and + * either how far the image should be inset from the top or the left hand + * edge of the cell. + * + * @author Mark Beardsley [msb at apache.org] + * @version 1.00 5th August 2009. + */ + public class ClientAnchorDetail { + + public int fromIndex = 0; + public int toIndex = 0; + public int inset = 0; + + /** + * Create a new instance of the ClientAnchorDetail class using the + * following parameters. + * + * @param fromIndex A primitive int that contains one of the + * coordinates (row or column index) for the top left + * hand corner of the image. + * @param toIndex A primitive int that contains one of the + * coordinates (row or column index) for the bottom + * right hand corner of the image. + * @param inset A primitive int that contains a value which indicates + * how far the image should be inset from the top or the + * left hand edge of a cell. + */ + public ClientAnchorDetail(int fromIndex, int toIndex, int inset) { + this.fromIndex = fromIndex; + this.toIndex = toIndex; + this.inset = inset; + } + + /** + * Get one of the number of the column or row that contains the cell + * whose top left hand corner will be aligned with the top left hand + * corner of the image. + * + * @return The value - row or column index - for one of the coordinates + * of the top left hand corner of the image. + */ + public int getFromIndex() { + return(this.fromIndex); + } + + /** + * Get one of the number of the column or row that contains the cell + * whose top left hand corner will be aligned with the bottom right hand + * corner of the image. + * + * @return The value - row or column index - for one of the coordinates + * of the bottom right hand corner of the image. + */ + public int getToIndex() { + return(this.toIndex); + } + + /** + * Get the images offset from the edge of a cell. + * + * @return How far either the right hand or bottom edge of the image is + * inset from the left hand or top edge of a cell. + */ + public int getInset() { + return(this.inset); + } + } + + /** + * Utility methods used to convert Excels character based column and row + * size measurements into pixels and/or millimetres. The class also contains + * various constants that are required in other calculations. + * + * @author xio[darjino@hotmail.com] + * @version 1.01 30th July 2009. + * Added by Mark Beardsley [msb at apache.org]. + * Additional constants. + * widthUnits2Millimetres() and millimetres2Units() methods. + */ + public static class ConvertImageUnits { + + // Each cell conatins a fixed number of co-ordinate points; this number + // does not vary with row height or column width or with font. These two + // constants are defined below. + public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB + public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB + // The resoultion of an image can be expressed as a specific number + // of pixels per inch. Displays and printers differ but 96 pixels per + // inch is an acceptable standard to beging with. + public static final int PIXELS_PER_INCH = 96; // MB + // Cnstants that defines how many pixels and points there are in a + // millimetre. These values are required for the conversion algorithm. + public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB + public static final double POINTS_PER_MILLIMETRE = 2.83; // MB + // The column width returned by HSSF and the width of a picture when + // positioned to exactly cover one cell are different by almost exactly + // 2mm - give or take rounding errors. This constant allows that + // additional amount to be accounted for when calculating how many + // celles the image ought to overlie. + public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB + public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; + public static final int UNIT_OFFSET_LENGTH = 7; + public static final int[] UNIT_OFFSET_MAP = new int[] + { 0, 36, 73, 109, 146, 182, 219 }; + + /** + * pixel units to excel width units(units of 1/256th of a character width) + * @param pxs + * @return + */ + public static short pixel2WidthUnits(int pxs) { + short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * + (pxs / UNIT_OFFSET_LENGTH)); + widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)]; + return widthUnits; + } + + /** + * excel width units(units of 1/256th of a character width) to pixel + * units. + * + * @param widthUnits + * @return + */ + public static int widthUnits2Pixel(short widthUnits) { + int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) + * UNIT_OFFSET_LENGTH; + int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; + pixels += Math.round(offsetWidthUnits / + ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); + return pixels; + } + + /** + * Convert Excels width units into millimetres. + * + * @param widthUnits The width of the column or the height of the + * row in Excels units. + * @return A primitive double that contains the columns width or rows + * height in millimetres. + */ + public static double widthUnits2Millimetres(short widthUnits) { + return(ConvertImageUnits.widthUnits2Pixel(widthUnits) / + ConvertImageUnits.PIXELS_PER_MILLIMETRES); + } + + /** + * Convert into millimetres Excels width units.. + * + * @param millimetres A primitive double that contains the columns + * width or rows height in millimetres. + * @return A primitive int that contains the columns width or rows + * height in Excels units. + */ + public static int millimetres2WidthUnits(double millimetres) { + return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres * + ConvertImageUnits.PIXELS_PER_MILLIMETRES))); + } + + public static int pointsToPixels(double points) { + return (int) Math.round(points / 72D * PIXELS_PER_INCH); + } + + public static double pointsToMillimeters(double points) { + return points / 72D * 25.4; + } + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/ss/examples/AligningCells.java b/poi-examples/src/main/java/poi/ss/examples/AligningCells.java new file mode 100644 index 0000000000..6571ff9dd9 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/AligningCells.java @@ -0,0 +1,72 @@ +/* ==================================================================== +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==================================================================== */ +package org.apache.poi.ss.examples; + +import java.io.FileOutputStream; +import java.io.IOException; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.*; + +/** + * Shows how various alignment options work. + */ +public class AligningCells { + + public static void main(String[] args) throws IOException { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + + Sheet sheet = wb.createSheet(); + Row row = sheet.createRow((short) 2); + row.setHeightInPoints(30); + for (int i = 0; i < 8; i++) { + //column width is set in units of 1/256th of a character width + sheet.setColumnWidth(i, 256 * 15); + } + + createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM); + createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM); + createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER); + createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER); + createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY); + createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP); + createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("ss-example-align.xlsx"); + wb.write(fileOut); + fileOut.close(); + } + + /** + * Creates a cell and aligns it a certain way. + * + * @param wb the workbook + * @param row the row to create the cell in + * @param column the column number to create the cell in + * @param halign the horizontal alignment for the cell. + */ + private static void createCell(Workbook wb, Row row, short column, short halign, short valign) { + CreationHelper ch = wb.getCreationHelper(); + Cell cell = row.createCell(column); + cell.setCellValue(ch.createRichTextString("Align It")); + CellStyle cellStyle = wb.createCellStyle(); + cellStyle.setAlignment(halign); + cellStyle.setVerticalAlignment(valign); + cell.setCellStyle(cellStyle); + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/ss/examples/BusinessPlan.java b/poi-examples/src/main/java/poi/ss/examples/BusinessPlan.java new file mode 100644 index 0000000000..101eceda7b --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/BusinessPlan.java @@ -0,0 +1,325 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.ss.examples; + +import org.apache.poi.xssf.usermodel.*; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +import java.util.Map; +import java.util.HashMap; +import java.util.Calendar; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; + +/** + * A business plan demo + * Usage: + * BusinessPlan -xls|xlsx + * + * @author Yegor Kozlov + */ +public class BusinessPlan { + + private static SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM"); + + private static final String[] titles = { + "ID", "Project Name", "Owner", "Days", "Start", "End"}; + + //sample data to fill the sheet. + private static final String[][] data = { + {"1.0", "Marketing Research Tactical Plan", "J. Dow", "70", "9-Jul", null, + "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"}, + null, + {"1.1", "Scope Definition Phase", "J. Dow", "10", "9-Jul", null, + "x", "x", null, null, null, null, null, null, null, null, null}, + {"1.1.1", "Define research objectives", "J. Dow", "3", "9-Jul", null, + "x", null, null, null, null, null, null, null, null, null, null}, + {"1.1.2", "Define research requirements", "S. Jones", "7", "10-Jul", null, + "x", "x", null, null, null, null, null, null, null, null, null}, + {"1.1.3", "Determine in-house resource or hire vendor", "J. Dow", "2", "15-Jul", null, + "x", "x", null, null, null, null, null, null, null, null, null}, + null, + {"1.2", "Vendor Selection Phase", "J. Dow", "19", "19-Jul", null, + null, "x", "x", "x", "x", null, null, null, null, null, null}, + {"1.2.1", "Define vendor selection criteria", "J. Dow", "3", "19-Jul", null, + null, "x", null, null, null, null, null, null, null, null, null}, + {"1.2.2", "Develop vendor selection questionnaire", "S. Jones, T. Wates", "2", "22-Jul", null, + null, "x", "x", null, null, null, null, null, null, null, null}, + {"1.2.3", "Develop Statement of Work", "S. Jones", "4", "26-Jul", null, + null, null, "x", "x", null, null, null, null, null, null, null}, + {"1.2.4", "Evaluate proposal", "J. Dow, S. Jones", "4", "2-Aug", null, + null, null, null, "x", "x", null, null, null, null, null, null}, + {"1.2.5", "Select vendor", "J. Dow", "1", "6-Aug", null, + null, null, null, null, "x", null, null, null, null, null, null}, + null, + {"1.3", "Research Phase", "G. Lee", "47", "9-Aug", null, + null, null, null, null, "x", "x", "x", "x", "x", "x", "x"}, + {"1.3.1", "Develop market research information needs questionnaire", "G. Lee", "2", "9-Aug", null, + null, null, null, null, "x", null, null, null, null, null, null}, + {"1.3.2", "Interview marketing group for market research needs", "G. Lee", "2", "11-Aug", null, + null, null, null, null, "x", "x", null, null, null, null, null}, + {"1.3.3", "Document information needs", "G. Lee, S. Jones", "1", "13-Aug", null, + null, null, null, null, null, "x", null, null, null, null, null}, + }; + + public static void main(String[] args) throws Exception { + Workbook wb; + + if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); + else wb = new XSSFWorkbook(); + + Map styles = createStyles(wb); + + Sheet sheet = wb.createSheet("Business Plan"); + + //turn off gridlines + sheet.setDisplayGridlines(false); + sheet.setPrintGridlines(false); + sheet.setFitToPage(true); + sheet.setHorizontallyCenter(true); + PrintSetup printSetup = sheet.getPrintSetup(); + printSetup.setLandscape(true); + + //the following three statements are required only for HSSF + sheet.setAutobreaks(true); + printSetup.setFitHeight((short)1); + printSetup.setFitWidth((short)1); + + //the header row: centered text in 48pt font + Row headerRow = sheet.createRow(0); + headerRow.setHeightInPoints(12.75f); + for (int i = 0; i < titles.length; i++) { + Cell cell = headerRow.createCell(i); + cell.setCellValue(titles[i]); + cell.setCellStyle(styles.get("header")); + } + //columns for 11 weeks starting from 9-Jul + Calendar calendar = Calendar.getInstance(); + int year = calendar.get(Calendar.YEAR); + + calendar.setTime(fmt.parse("9-Jul")); + calendar.set(Calendar.YEAR, year); + for (int i = 0; i < 11; i++) { + Cell cell = headerRow.createCell(titles.length + i); + cell.setCellValue(calendar); + cell.setCellStyle(styles.get("header_date")); + calendar.roll(Calendar.WEEK_OF_YEAR, true); + } + //freeze the first row + sheet.createFreezePane(0, 1); + + Row row; + Cell cell; + int rownum = 1; + for (int i = 0; i < data.length; i++, rownum++) { + row = sheet.createRow(rownum); + if(data[i] == null) continue; + + for (int j = 0; j < data[i].length; j++) { + cell = row.createCell(j); + String styleName; + boolean isHeader = i == 0 || data[i-1] == null; + switch(j){ + case 0: + if(isHeader) { + styleName = "cell_b"; + cell.setCellValue(Double.parseDouble(data[i][j])); + } else { + styleName = "cell_normal"; + cell.setCellValue(data[i][j]); + } + break; + case 1: + if(isHeader) { + styleName = i == 0 ? "cell_h" : "cell_bb"; + } else { + styleName = "cell_indented"; + } + cell.setCellValue(data[i][j]); + break; + case 2: + styleName = isHeader ? "cell_b" : "cell_normal"; + cell.setCellValue(data[i][j]); + break; + case 3: + styleName = isHeader ? "cell_b_centered" : "cell_normal_centered"; + cell.setCellValue(Integer.parseInt(data[i][j])); + break; + case 4: { + calendar.setTime(fmt.parse(data[i][j])); + calendar.set(Calendar.YEAR, year); + cell.setCellValue(calendar); + styleName = isHeader ? "cell_b_date" : "cell_normal_date"; + break; + } + case 5: { + int r = rownum + 1; + String fmla = "IF(AND(D"+r+",E"+r+"),E"+r+"+D"+r+",\"\")"; + cell.setCellFormula(fmla); + styleName = isHeader ? "cell_bg" : "cell_g"; + break; + } + default: + styleName = data[i][j] != null ? "cell_blue" : "cell_normal"; + } + + cell.setCellStyle(styles.get(styleName)); + } + } + + //group rows for each phase, row numbers are 0-based + sheet.groupRow(4, 6); + sheet.groupRow(9, 13); + sheet.groupRow(16, 18); + + //set column widths, the width is measured in units of 1/256th of a character width + sheet.setColumnWidth(0, 256*6); + sheet.setColumnWidth(1, 256*33); + sheet.setColumnWidth(2, 256*20); + sheet.setZoom(3, 4); + + + // Write the output to a file + String file = "businessplan.xls"; + if(wb instanceof XSSFWorkbook) file += "x"; + FileOutputStream out = new FileOutputStream(file); + wb.write(out); + out.close(); + } + + /** + * create a library of cell styles + */ + private static Map createStyles(Workbook wb){ + Map styles = new HashMap(); + DataFormat df = wb.createDataFormat(); + + CellStyle style; + Font headerFont = wb.createFont(); + headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setFont(headerFont); + styles.put("header", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setFont(headerFont); + style.setDataFormat(df.getFormat("d-mmm")); + styles.put("header_date", style); + + Font font1 = wb.createFont(); + font1.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_LEFT); + style.setFont(font1); + styles.put("cell_b", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setFont(font1); + styles.put("cell_b_centered", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(font1); + style.setDataFormat(df.getFormat("d-mmm")); + styles.put("cell_b_date", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(font1); + style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setDataFormat(df.getFormat("d-mmm")); + styles.put("cell_g", style); + + Font font2 = wb.createFont(); + font2.setColor(IndexedColors.BLUE.getIndex()); + font2.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_LEFT); + style.setFont(font2); + styles.put("cell_bb", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(font1); + style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setDataFormat(df.getFormat("d-mmm")); + styles.put("cell_bg", style); + + Font font3 = wb.createFont(); + font3.setFontHeightInPoints((short)14); + font3.setColor(IndexedColors.DARK_BLUE.getIndex()); + font3.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_LEFT); + style.setFont(font3); + style.setWrapText(true); + styles.put("cell_h", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_LEFT); + style.setWrapText(true); + styles.put("cell_normal", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setWrapText(true); + styles.put("cell_normal_centered", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setWrapText(true); + style.setDataFormat(df.getFormat("d-mmm")); + styles.put("cell_normal_date", style); + + style = createBorderedStyle(wb); + style.setAlignment(CellStyle.ALIGN_LEFT); + style.setIndention((short)1); + style.setWrapText(true); + styles.put("cell_indented", style); + + style = createBorderedStyle(wb); + style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + styles.put("cell_blue", style); + + return styles; + } + + private static CellStyle createBorderedStyle(Workbook wb){ + CellStyle style = wb.createCellStyle(); + style.setBorderRight(CellStyle.BORDER_THIN); + style.setRightBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderTop(CellStyle.BORDER_THIN); + style.setTopBorderColor(IndexedColors.BLACK.getIndex()); + return style; + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/CalendarDemo.java b/poi-examples/src/main/java/poi/ss/examples/CalendarDemo.java new file mode 100644 index 0000000000..bb120861f6 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/CalendarDemo.java @@ -0,0 +1,243 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.ss.examples; + +import org.apache.poi.xssf.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.usermodel.Font; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +import java.io.FileOutputStream; +import java.util.Calendar; +import java.util.Map; +import java.util.HashMap; + +/** + * A monthly calendar created using Apache POI. Each month is on a separate sheet. + *
    + * Usage:
    + * CalendarDemo -xls|xlsx 
    + * 
    + * + * @author Yegor Kozlov + */ +public class CalendarDemo { + + private static final String[] days = { + "Sunday", "Monday", "Tuesday", + "Wednesday", "Thursday", "Friday", "Saturday"}; + + private static final String[] months = { + "January", "February", "March","April", "May", "June","July", "August", + "September","October", "November", "December"}; + + public static void main(String[] args) throws Exception { + + Calendar calendar = Calendar.getInstance(); + boolean xlsx = true; + for (int i = 0; i < args.length; i++) { + if(args[i].charAt(0) == '-'){ + xlsx = args[i].equals("-xlsx"); + } else { + calendar.set(Calendar.YEAR, Integer.parseInt(args[i])); + } + } + int year = calendar.get(Calendar.YEAR); + + Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook(); + + Map styles = createStyles(wb); + + for (int month = 0; month < 12; month++) { + calendar.set(Calendar.MONTH, month); + calendar.set(Calendar.DAY_OF_MONTH, 1); + //create a sheet for each month + Sheet sheet = wb.createSheet(months[month]); + + //turn off gridlines + sheet.setDisplayGridlines(false); + sheet.setPrintGridlines(false); + sheet.setFitToPage(true); + sheet.setHorizontallyCenter(true); + PrintSetup printSetup = sheet.getPrintSetup(); + printSetup.setLandscape(true); + + //the following three statements are required only for HSSF + sheet.setAutobreaks(true); + printSetup.setFitHeight((short)1); + printSetup.setFitWidth((short)1); + + //the header row: centered text in 48pt font + Row headerRow = sheet.createRow(0); + headerRow.setHeightInPoints(80); + Cell titleCell = headerRow.createCell(0); + titleCell.setCellValue(months[month] + " " + year); + titleCell.setCellStyle(styles.get("title")); + sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1")); + + //header with month titles + Row monthRow = sheet.createRow(1); + for (int i = 0; i < days.length; i++) { + //set column widths, the width is measured in units of 1/256th of a character width + sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide + sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide + sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1)); + Cell monthCell = monthRow.createCell(i*2); + monthCell.setCellValue(days[i]); + monthCell.setCellStyle(styles.get("month")); + } + + int cnt = 1, day=1; + int rownum = 2; + for (int j = 0; j < 6; j++) { + Row row = sheet.createRow(rownum++); + row.setHeightInPoints(100); + for (int i = 0; i < days.length; i++) { + Cell dayCell_1 = row.createCell(i*2); + Cell dayCell_2 = row.createCell(i*2 + 1); + + int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); + if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) { + dayCell_1.setCellValue(day); + calendar.set(Calendar.DAY_OF_MONTH, ++day); + + if(i == 0 || i == days.length-1) { + dayCell_1.setCellStyle(styles.get("weekend_left")); + dayCell_2.setCellStyle(styles.get("weekend_right")); + } else { + dayCell_1.setCellStyle(styles.get("workday_left")); + dayCell_2.setCellStyle(styles.get("workday_right")); + } + } else { + dayCell_1.setCellStyle(styles.get("grey_left")); + dayCell_2.setCellStyle(styles.get("grey_right")); + } + cnt++; + } + if(calendar.get(Calendar.MONTH) > month) break; + } + } + + // Write the output to a file + String file = "calendar.xls"; + if(wb instanceof XSSFWorkbook) file += "x"; + FileOutputStream out = new FileOutputStream(file); + wb.write(out); + out.close(); + } + + /** + * cell styles used for formatting calendar sheets + */ + private static Map createStyles(Workbook wb){ + Map styles = new HashMap(); + + short borderColor = IndexedColors.GREY_50_PERCENT.getIndex(); + + CellStyle style; + Font titleFont = wb.createFont(); + titleFont.setFontHeightInPoints((short)48); + titleFont.setColor(IndexedColors.DARK_BLUE.getIndex()); + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); + style.setFont(titleFont); + styles.put("title", style); + + Font monthFont = wb.createFont(); + monthFont.setFontHeightInPoints((short)12); + monthFont.setColor(IndexedColors.WHITE.getIndex()); + monthFont.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); + style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setFont(monthFont); + styles.put("month", style); + + Font dayFont = wb.createFont(); + dayFont.setFontHeightInPoints((short)14); + dayFont.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_LEFT); + style.setVerticalAlignment(CellStyle.VERTICAL_TOP); + style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setLeftBorderColor(borderColor); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(borderColor); + style.setFont(dayFont); + styles.put("weekend_left", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_TOP); + style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setBorderRight(CellStyle.BORDER_THIN); + style.setRightBorderColor(borderColor); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(borderColor); + styles.put("weekend_right", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_LEFT); + style.setVerticalAlignment(CellStyle.VERTICAL_TOP); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setLeftBorderColor(borderColor); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(borderColor); + style.setFont(dayFont); + styles.put("workday_left", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_TOP); + style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setBorderRight(CellStyle.BORDER_THIN); + style.setRightBorderColor(borderColor); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(borderColor); + styles.put("workday_right", style); + + style = wb.createCellStyle(); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(borderColor); + styles.put("grey_left", style); + + style = wb.createCellStyle(); + style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setBorderRight(CellStyle.BORDER_THIN); + style.setRightBorderColor(borderColor); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(borderColor); + styles.put("grey_right", style); + + return styles; + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/CellStyleDetails.java b/poi-examples/src/main/java/poi/ss/examples/CellStyleDetails.java new file mode 100644 index 0000000000..8dab14fa7a --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/CellStyleDetails.java @@ -0,0 +1,94 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.ss.examples; + +import java.io.File; + +import org.apache.poi.hssf.usermodel.HSSFFont; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Color; +import org.apache.poi.ss.usermodel.DataFormatter; +import org.apache.poi.ss.usermodel.Font; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.usermodel.XSSFColor; +import org.apache.poi.xssf.usermodel.XSSFFont; + +/** + * Demonstrates how to read excel styles for cells + */ +public class CellStyleDetails { + public static void main(String[] args) throws Exception { + if(args.length == 0) { + throw new IllegalArgumentException("Filename must be given"); + } + + Workbook wb = WorkbookFactory.create(new File(args[0])); + DataFormatter formatter = new DataFormatter(); + + for(int sn=0; sn + * Based on the code snippets from http://www.contextures.com/xlcondformat03.html + *

    + * + * @author Yegor Kozlov + */ +public class ConditionalFormats { + + public static void main(String[] args) throws IOException { + Workbook wb; + + if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); + else wb = new XSSFWorkbook(); + + sameCell(wb.createSheet("Same Cell")); + multiCell(wb.createSheet("MultiCell")); + errors(wb.createSheet("Errors")); + hideDupplicates(wb.createSheet("Hide Dups")); + formatDuplicates(wb.createSheet("Duplicates")); + inList(wb.createSheet("In List")); + expiry(wb.createSheet("Expiry")); + shadeAlt(wb.createSheet("Shade Alt")); + shadeBands(wb.createSheet("Shade Bands")); + + // Write the output to a file + String file = "cf-poi.xls"; + if(wb instanceof XSSFWorkbook) file += "x"; + FileOutputStream out = new FileOutputStream(file); + wb.write(out); + out.close(); + + } + + /** + * Highlight cells based on their values + */ + static void sameCell(Sheet sheet) { + sheet.createRow(0).createCell(0).setCellValue(84); + sheet.createRow(1).createCell(0).setCellValue(74); + sheet.createRow(2).createCell(0).setCellValue(50); + sheet.createRow(3).createCell(0).setCellValue(51); + sheet.createRow(4).createCell(0).setCellValue(49); + sheet.createRow(5).createCell(0).setCellValue(41); + + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + // Condition 1: Cell Value Is greater than 70 (Blue Fill) + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.GT, "70"); + PatternFormatting fill1 = rule1.createPatternFormatting(); + fill1.setFillBackgroundColor(IndexedColors.BLUE.index); + fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); + + // Condition 2: Cell Value Is less than 50 (Green Fill) + ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.LT, "50"); + PatternFormatting fill2 = rule2.createPatternFormatting(); + fill2.setFillBackgroundColor(IndexedColors.GREEN.index); + fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A1:A6") + }; + + sheetCF.addConditionalFormatting(regions, rule1, rule2); + + sheet.getRow(0).createCell(2).setCellValue("<== Condition 1: Cell Value Is greater than 70 (Blue Fill)"); + sheet.getRow(4).createCell(2).setCellValue("<== Condition 2: Cell Value Is less than 50 (Green Fill)"); + } + + /** + * Highlight multiple cells based on a formula + */ + static void multiCell(Sheet sheet) { + // header row + Row row0 = sheet.createRow(0); + row0.createCell(0).setCellValue("Units"); + row0.createCell(1).setCellValue("Cost"); + row0.createCell(2).setCellValue("Total"); + + Row row1 = sheet.createRow(1); + row1.createCell(0).setCellValue(71); + row1.createCell(1).setCellValue(29); + row1.createCell(2).setCellValue(2059); + + Row row2 = sheet.createRow(2); + row2.createCell(0).setCellValue(85); + row2.createCell(1).setCellValue(29); + row2.createCell(2).setCellValue(2059); + + Row row3 = sheet.createRow(3); + row3.createCell(0).setCellValue(71); + row3.createCell(1).setCellValue(29); + row3.createCell(2).setCellValue(2059); + + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + // Condition 1: Formula Is =$B2>75 (Blue Fill) + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("$A2>75"); + PatternFormatting fill1 = rule1.createPatternFormatting(); + fill1.setFillBackgroundColor(IndexedColors.BLUE.index); + fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A2:C4") + }; + + sheetCF.addConditionalFormatting(regions, rule1); + + sheet.getRow(2).createCell(4).setCellValue("<== Condition 1: Formula Is =$B2>75 (Blue Fill)"); + } + + /** + * Use Excel conditional formatting to check for errors, + * and change the font colour to match the cell colour. + * In this example, if formula result is #DIV/0! then it will have white font colour. + */ + static void errors(Sheet sheet) { + sheet.createRow(0).createCell(0).setCellValue(84); + sheet.createRow(1).createCell(0).setCellValue(0); + sheet.createRow(2).createCell(0).setCellFormula("ROUND(A1/A2,0)"); + sheet.createRow(3).createCell(0).setCellValue(0); + sheet.createRow(4).createCell(0).setCellFormula("ROUND(A6/A4,0)"); + sheet.createRow(5).createCell(0).setCellValue(41); + + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + // Condition 1: Formula Is =ISERROR(C2) (White Font) + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("ISERROR(A1)"); + FontFormatting font = rule1.createFontFormatting(); + font.setFontColorIndex(IndexedColors.WHITE.index); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A1:A6") + }; + + sheetCF.addConditionalFormatting(regions, rule1); + + sheet.getRow(2).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)"); + sheet.getRow(4).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)"); + } + + /** + * Use Excel conditional formatting to hide the duplicate values, + * and make the list easier to read. In this example, when the table is sorted by Region, + * the second (and subsequent) occurences of each region name will have white font colour. + */ + static void hideDupplicates(Sheet sheet) { + sheet.createRow(0).createCell(0).setCellValue("City"); + sheet.createRow(1).createCell(0).setCellValue("Boston"); + sheet.createRow(2).createCell(0).setCellValue("Boston"); + sheet.createRow(3).createCell(0).setCellValue("Chicago"); + sheet.createRow(4).createCell(0).setCellValue("Chicago"); + sheet.createRow(5).createCell(0).setCellValue("New York"); + + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + // Condition 1: Formula Is =A2=A1 (White Font) + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("A2=A1"); + FontFormatting font = rule1.createFontFormatting(); + font.setFontColorIndex(IndexedColors.WHITE.index); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A2:A6") + }; + + sheetCF.addConditionalFormatting(regions, rule1); + + sheet.getRow(1).createCell(1).setCellValue("<== the second (and subsequent) " + + "occurences of each region name will have white font colour. " + + "Condition: Formula Is =A2=A1 (White Font)"); + } + + /** + * Use Excel conditional formatting to highlight duplicate entries in a column. + */ + static void formatDuplicates(Sheet sheet) { + sheet.createRow(0).createCell(0).setCellValue("Code"); + sheet.createRow(1).createCell(0).setCellValue(4); + sheet.createRow(2).createCell(0).setCellValue(3); + sheet.createRow(3).createCell(0).setCellValue(6); + sheet.createRow(4).createCell(0).setCellValue(3); + sheet.createRow(5).createCell(0).setCellValue(5); + sheet.createRow(6).createCell(0).setCellValue(8); + sheet.createRow(7).createCell(0).setCellValue(0); + sheet.createRow(8).createCell(0).setCellValue(2); + sheet.createRow(9).createCell(0).setCellValue(8); + sheet.createRow(10).createCell(0).setCellValue(6); + + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + // Condition 1: Formula Is =A2=A1 (White Font) + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($A$2:$A$11,A2)>1"); + FontFormatting font = rule1.createFontFormatting(); + font.setFontStyle(false, true); + font.setFontColorIndex(IndexedColors.BLUE.index); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A2:A11") + }; + + sheetCF.addConditionalFormatting(regions, rule1); + + sheet.getRow(2).createCell(1).setCellValue("<== Duplicates numbers in the column are highlighted. " + + "Condition: Formula Is =COUNTIF($A$2:$A$11,A2)>1 (Blue Font)"); + } + + /** + * Use Excel conditional formatting to highlight items that are in a list on the worksheet. + */ + static void inList(Sheet sheet) { + sheet.createRow(0).createCell(0).setCellValue("Codes"); + sheet.createRow(1).createCell(0).setCellValue("AA"); + sheet.createRow(2).createCell(0).setCellValue("BB"); + sheet.createRow(3).createCell(0).setCellValue("GG"); + sheet.createRow(4).createCell(0).setCellValue("AA"); + sheet.createRow(5).createCell(0).setCellValue("FF"); + sheet.createRow(6).createCell(0).setCellValue("XX"); + sheet.createRow(7).createCell(0).setCellValue("CC"); + + sheet.getRow(0).createCell(2).setCellValue("Valid"); + sheet.getRow(1).createCell(2).setCellValue("AA"); + sheet.getRow(2).createCell(2).setCellValue("BB"); + sheet.getRow(3).createCell(2).setCellValue("CC"); + + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + // Condition 1: Formula Is =A2=A1 (White Font) + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($C$2:$C$4,A2)"); + PatternFormatting fill1 = rule1.createPatternFormatting(); + fill1.setFillBackgroundColor(IndexedColors.LIGHT_BLUE.index); + fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A2:A8") + }; + + sheetCF.addConditionalFormatting(regions, rule1); + + sheet.getRow(2).createCell(3).setCellValue("<== Use Excel conditional formatting to highlight items that are in a list on the worksheet"); + } + + /** + * Use Excel conditional formatting to highlight payments that are due in the next thirty days. + * In this example, Due dates are entered in cells A2:A4. + */ + static void expiry(Sheet sheet) { + CellStyle style = sheet.getWorkbook().createCellStyle(); + style.setDataFormat((short)BuiltinFormats.getBuiltinFormat("d-mmm")); + + sheet.createRow(0).createCell(0).setCellValue("Date"); + sheet.createRow(1).createCell(0).setCellFormula("TODAY()+29"); + sheet.createRow(2).createCell(0).setCellFormula("A2+1"); + sheet.createRow(3).createCell(0).setCellFormula("A3+1"); + + for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style); + + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + // Condition 1: Formula Is =A2=A1 (White Font) + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("AND(A2-TODAY()>=0,A2-TODAY()<=30)"); + FontFormatting font = rule1.createFontFormatting(); + font.setFontStyle(false, true); + font.setFontColorIndex(IndexedColors.BLUE.index); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A2:A4") + }; + + sheetCF.addConditionalFormatting(regions, rule1); + + sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted"); + } + + /** + * Use Excel conditional formatting to shade alternating rows on the worksheet + */ + static void shadeAlt(Sheet sheet) { + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + // Condition 1: Formula Is =A2=A1 (White Font) + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)"); + PatternFormatting fill1 = rule1.createPatternFormatting(); + fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index); + fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A1:Z100") + }; + + sheetCF.addConditionalFormatting(regions, rule1); + + sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows"); + sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),2) (Light Green Fill)"); + } + + /** + * You can use Excel conditional formatting to shade bands of rows on the worksheet. + * In this example, 3 rows are shaded light grey, and 3 are left with no shading. + * In the MOD function, the total number of rows in the set of banded rows (6) is entered. + */ + static void shadeBands(Sheet sheet) { + SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); + + ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),6)<3"); + PatternFormatting fill1 = rule1.createPatternFormatting(); + fill1.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index); + fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); + + CellRangeAddress[] regions = { + CellRangeAddress.valueOf("A1:Z100") + }; + + sheetCF.addConditionalFormatting(regions, rule1); + + sheet.createRow(0).createCell(1).setCellValue("Shade Bands of Rows"); + sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),6)<2 (Light Grey Fill)"); + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/LinkedDropDownLists.java b/poi-examples/src/main/java/poi/ss/examples/LinkedDropDownLists.java new file mode 100644 index 0000000000..b0efc4f0ce --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/LinkedDropDownLists.java @@ -0,0 +1,228 @@ + /* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ==================================================================== */ + +package org.apache.poi.ss.examples; +import java.io.*; +import org.apache.poi.xssf.usermodel.*; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddressList; + +/** + * Demonstrates one technique that may be used to create linked or dependent + * drop down lists. This refers to a situation in which the selection made + * in one drop down list affects the options that are displayed in the second + * or subsequent drop down list(s). In this example, the value the user selects + * from the down list in cell A1 will affect the values displayed in the linked + * drop down list in cell B1. For the sake of simplicity, the data for the drop + * down lists is included on the same worksheet but this does not have to be the + * case; the data could appear on a separate sheet. If this were done, then the + * names for the regions would have to be different, they would have to include + * the name of the sheet. + * + * There are two keys to this technique. The first is the use of named area or + * regions of cells to hold the data for the drop down lists and the second is + * making use of the INDIRECT() function to convert a name into the addresses + * of the cells it refers to. + * + * Note that whilst this class builds just two linked drop down lists, there is + * nothing to prevent more being created. Quite simply, use the value selected + * by the user in one drop down list to determine what is shown in another and the + * value selected in that drop down list to determine what is shown in a third, + * and so on. Also, note that the data for the drop down lists is contained on + * contained on the same sheet as the validations themselves. This is done simply + * for simplicity and there is nothing to prevent a separate sheet being created + * and used to hold the data. If this is done then problems may be encountered + * if the sheet is opened with OpenOffice Calc. To prevent these problems, it is + * better to include the name of the sheet when calling the setRefersToFormula() + * method. + * + * @author Mark Beardsley [msb at apache.org] + * @version 1.00 30th March 2012 + */ +public class LinkedDropDownLists { + + LinkedDropDownLists(String workbookName) { + File file = null; + FileOutputStream fos = null; + Workbook workbook = null; + Sheet sheet = null; + DataValidationHelper dvHelper = null; + DataValidationConstraint dvConstraint = null; + DataValidation validation = null; + CellRangeAddressList addressList = null; + try { + + // Using the ss.usermodel allows this class to support both binary + // and xml based workbooks. The choice of which one to create is + // made by checking the file extension. + if (workbookName.endsWith(".xlsx")) { + workbook = new XSSFWorkbook(); + } else { + workbook = new HSSFWorkbook(); + } + + // Build the sheet that will hold the data for the validations. This + // must be done first as it will create names that are referenced + // later. + sheet = workbook.createSheet("Linked Validations"); + LinkedDropDownLists.buildDataSheet(sheet); + + // Build the first data validation to occupy cell A1. Note + // that it retrieves it's data from the named area or region called + // CHOICES. Further information about this can be found in the + // static buildDataSheet() method below. + addressList = new CellRangeAddressList(0, 0, 0, 0); + dvHelper = sheet.getDataValidationHelper(); + dvConstraint = dvHelper.createFormulaListConstraint("CHOICES"); + validation = dvHelper.createValidation(dvConstraint, addressList); + sheet.addValidationData(validation); + + // Now, build the linked or dependent drop down list that will + // occupy cell B1. The key to the whole process is the use of the + // INDIRECT() function. In the buildDataSheet(0 method, a series of + // named regions are created and the names of three of them mirror + // the options available to the user in the first drop down list + // (in cell A1). Using the INDIRECT() function makes it possible + // to convert the selection the user makes in that first drop down + // into the addresses of a named region of cells and then to use + // those cells to populate the second drop down list. + addressList = new CellRangeAddressList(0, 0, 1, 1); + dvConstraint = dvHelper.createFormulaListConstraint( + "INDIRECT(UPPER($A$1))"); + validation = dvHelper.createValidation(dvConstraint, addressList); + sheet.addValidationData(validation); + + file = new File(workbookName); + fos = new FileOutputStream(file); + workbook.write(fos); + } catch (IOException ioEx) { + System.out.println("Caught a: " + ioEx.getClass().getName()); + System.out.println("Message: " + ioEx.getMessage()); + System.out.println("Stacktrace follws:....."); + ioEx.printStackTrace(System.out); + } finally { + try { + if (fos != null) { + fos.close(); + fos = null; + } + } catch (IOException ioEx) { + System.out.println("Caught a: " + ioEx.getClass().getName()); + System.out.println("Message: " + ioEx.getMessage()); + System.out.println("Stacktrace follws:....."); + ioEx.printStackTrace(System.out); + } + } + } + + /** + * Called to populate the named areas/regions. The contents of the cells on + * row one will be used to populate the first drop down list. The contents of + * the cells on rows two, three and four will be used to populate the second + * drop down list, just which row will be determined by the choice the user + * makes in the first drop down list. + * + * In all cases, the approach is to create a row, create and populate cells + * with data and then specify a name that identifies those cells. With the + * exception of the first range, the names that are chosen for each range + * of cells are quite important. In short, each of the options the user + * could select in the first drop down list is used as the name for another + * range of cells. Thus, in this example, the user can select either + * 'Animal', 'Vegetable' or 'Mineral' in the first drop down and so the + * sheet contains ranges named 'ANIMAL', 'VEGETABLE' and 'MINERAL'. + * + * @param dataSheet An instance of a class that implements the Sheet Sheet + * interface (HSSFSheet or XSSFSheet). + */ + private static final void buildDataSheet(Sheet dataSheet) { + Row row = null; + Cell cell = null; + Name name = null; + + // The first row will hold the data for the first validation. + row = dataSheet.createRow(10); + cell = row.createCell(0); + cell.setCellValue("Animal"); + cell = row.createCell(1); + cell.setCellValue("Vegetable"); + cell = row.createCell(2); + cell.setCellValue("Mineral"); + name = dataSheet.getWorkbook().createName(); + name.setRefersToFormula("$A$11:$C$11"); + name.setNameName("CHOICES"); + + // The next three rows will hold the data that will be used to + // populate the second, or linked, drop down list. + row = dataSheet.createRow(11); + cell = row.createCell(0); + cell.setCellValue("Lion"); + cell = row.createCell(1); + cell.setCellValue("Tiger"); + cell = row.createCell(2); + cell.setCellValue("Leopard"); + cell = row.createCell(3); + cell.setCellValue("Elephant"); + cell = row.createCell(4); + cell.setCellValue("Eagle"); + cell = row.createCell(5); + cell.setCellValue("Horse"); + cell = row.createCell(6); + cell.setCellValue("Zebra"); + name = dataSheet.getWorkbook().createName(); + name.setRefersToFormula("$A$12:$G$12"); + name.setNameName("ANIMAL"); + + row = dataSheet.createRow(12); + cell = row.createCell(0); + cell.setCellValue("Cabbage"); + cell = row.createCell(1); + cell.setCellValue("Cauliflower"); + cell = row.createCell(2); + cell.setCellValue("Potato"); + cell = row.createCell(3); + cell.setCellValue("Onion"); + cell = row.createCell(4); + cell.setCellValue("Beetroot"); + cell = row.createCell(5); + cell.setCellValue("Asparagus"); + cell = row.createCell(6); + cell.setCellValue("Spinach"); + cell = row.createCell(7); + cell.setCellValue("Chard"); + name = dataSheet.getWorkbook().createName(); + name.setRefersToFormula("$A$13:$H$13"); + name.setNameName("VEGETABLE"); + + row = dataSheet.createRow(13); + cell = row.createCell(0); + cell.setCellValue("Bauxite"); + cell = row.createCell(1); + cell.setCellValue("Quartz"); + cell = row.createCell(2); + cell.setCellValue("Feldspar"); + cell = row.createCell(3); + cell.setCellValue("Shist"); + cell = row.createCell(4); + cell.setCellValue("Shale"); + cell = row.createCell(5); + cell.setCellValue("Mica"); + name = dataSheet.getWorkbook().createName(); + name.setRefersToFormula("$A$14:$F$14"); + name.setNameName("MINERAL"); + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/LoanCalculator.java b/poi-examples/src/main/java/poi/ss/examples/LoanCalculator.java new file mode 100644 index 0000000000..9598436589 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/LoanCalculator.java @@ -0,0 +1,305 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.ss.examples; + +import org.apache.poi.xssf.usermodel.*; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +import java.util.Map; +import java.util.HashMap; +import java.io.FileOutputStream; + +/** + * Simple Loan Calculator. Demonstrates advance usage of cell formulas and named ranges. + * + * Usage: + * LoanCalculator -xls|xlsx + * + * @author Yegor Kozlov + */ +public class LoanCalculator { + + public static void main(String[] args) throws Exception { + Workbook wb; + + if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); + else wb = new XSSFWorkbook(); + + Map styles = createStyles(wb); + Sheet sheet = wb.createSheet("Loan Calculator"); + sheet.setPrintGridlines(false); + sheet.setDisplayGridlines(false); + + PrintSetup printSetup = sheet.getPrintSetup(); + printSetup.setLandscape(true); + sheet.setFitToPage(true); + sheet.setHorizontallyCenter(true); + + sheet.setColumnWidth(0, 3*256); + sheet.setColumnWidth(1, 3*256); + sheet.setColumnWidth(2, 11*256); + sheet.setColumnWidth(3, 14*256); + sheet.setColumnWidth(4, 14*256); + sheet.setColumnWidth(5, 14*256); + sheet.setColumnWidth(6, 14*256); + + createNames(wb); + + Row titleRow = sheet.createRow(0); + titleRow.setHeightInPoints(35); + for (int i = 1; i <= 7; i++) { + titleRow.createCell(i).setCellStyle(styles.get("title")); + } + Cell titleCell = titleRow.getCell(2); + titleCell.setCellValue("Simple Loan Calculator"); + sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1")); + + Row row = sheet.createRow(2); + Cell cell = row.createCell(4); + cell.setCellValue("Enter values"); + cell.setCellStyle(styles.get("item_right")); + + row = sheet.createRow(3); + cell = row.createCell(2); + cell.setCellValue("Loan amount"); + cell.setCellStyle(styles.get("item_left")); + cell = row.createCell(4); + cell.setCellStyle(styles.get("input_$")); + cell.setAsActiveCell(); + + row = sheet.createRow(4); + cell = row.createCell(2); + cell.setCellValue("Annual interest rate"); + cell.setCellStyle(styles.get("item_left")); + cell = row.createCell(4); + cell.setCellStyle(styles.get("input_%")); + + row = sheet.createRow(5); + cell = row.createCell(2); + cell.setCellValue("Loan period in years"); + cell.setCellStyle(styles.get("item_left")); + cell = row.createCell(4); + cell.setCellStyle(styles.get("input_i")); + + row = sheet.createRow(6); + cell = row.createCell(2); + cell.setCellValue("Start date of loan"); + cell.setCellStyle(styles.get("item_left")); + cell = row.createCell(4); + cell.setCellStyle(styles.get("input_d")); + + row = sheet.createRow(8); + cell = row.createCell(2); + cell.setCellValue("Monthly payment"); + cell.setCellStyle(styles.get("item_left")); + cell = row.createCell(4); + cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")"); + cell.setCellStyle(styles.get("formula_$")); + + row = sheet.createRow(9); + cell = row.createCell(2); + cell.setCellValue("Number of payments"); + cell.setCellStyle(styles.get("item_left")); + cell = row.createCell(4); + cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")"); + cell.setCellStyle(styles.get("formula_i")); + + row = sheet.createRow(10); + cell = row.createCell(2); + cell.setCellValue("Total interest"); + cell.setCellStyle(styles.get("item_left")); + cell = row.createCell(4); + cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")"); + cell.setCellStyle(styles.get("formula_$")); + + row = sheet.createRow(11); + cell = row.createCell(2); + cell.setCellValue("Total cost of loan"); + cell.setCellStyle(styles.get("item_left")); + cell = row.createCell(4); + cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")"); + cell.setCellStyle(styles.get("formula_$")); + + + // Write the output to a file + String file = "loan-calculator.xls"; + if(wb instanceof XSSFWorkbook) file += "x"; + FileOutputStream out = new FileOutputStream(file); + wb.write(out); + out.close(); + } + + /** + * cell styles used for formatting calendar sheets + */ + private static Map createStyles(Workbook wb){ + Map styles = new HashMap(); + + CellStyle style; + Font titleFont = wb.createFont(); + titleFont.setFontHeightInPoints((short)14); + titleFont.setFontName("Trebuchet MS"); + style = wb.createCellStyle(); + style.setFont(titleFont); + style.setBorderBottom(CellStyle.BORDER_DOTTED); + style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + styles.put("title", style); + + Font itemFont = wb.createFont(); + itemFont.setFontHeightInPoints((short)9); + itemFont.setFontName("Trebuchet MS"); + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_LEFT); + style.setFont(itemFont); + styles.put("item_left", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(itemFont); + styles.put("item_right", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(itemFont); + style.setBorderRight(CellStyle.BORDER_DOTTED); + style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderBottom(CellStyle.BORDER_DOTTED); + style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderLeft(CellStyle.BORDER_DOTTED); + style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderTop(CellStyle.BORDER_DOTTED); + style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setDataFormat(wb.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)")); + styles.put("input_$", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(itemFont); + style.setBorderRight(CellStyle.BORDER_DOTTED); + style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderBottom(CellStyle.BORDER_DOTTED); + style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderLeft(CellStyle.BORDER_DOTTED); + style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderTop(CellStyle.BORDER_DOTTED); + style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setDataFormat(wb.createDataFormat().getFormat("0.000%")); + styles.put("input_%", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(itemFont); + style.setBorderRight(CellStyle.BORDER_DOTTED); + style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderBottom(CellStyle.BORDER_DOTTED); + style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderLeft(CellStyle.BORDER_DOTTED); + style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderTop(CellStyle.BORDER_DOTTED); + style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setDataFormat(wb.createDataFormat().getFormat("0")); + styles.put("input_i", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setFont(itemFont); + style.setDataFormat(wb.createDataFormat().getFormat("m/d/yy")); + styles.put("input_d", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(itemFont); + style.setBorderRight(CellStyle.BORDER_DOTTED); + style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderBottom(CellStyle.BORDER_DOTTED); + style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderLeft(CellStyle.BORDER_DOTTED); + style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderTop(CellStyle.BORDER_DOTTED); + style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setDataFormat(wb.createDataFormat().getFormat("$##,##0.00")); + style.setBorderBottom(CellStyle.BORDER_DOTTED); + style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + styles.put("formula_$", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_RIGHT); + style.setFont(itemFont); + style.setBorderRight(CellStyle.BORDER_DOTTED); + style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderBottom(CellStyle.BORDER_DOTTED); + style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderLeft(CellStyle.BORDER_DOTTED); + style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setBorderTop(CellStyle.BORDER_DOTTED); + style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setDataFormat(wb.createDataFormat().getFormat("0")); + style.setBorderBottom(CellStyle.BORDER_DOTTED); + style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + styles.put("formula_i", style); + + return styles; + } + + //define named ranges for the inputs and formulas + public static void createNames(Workbook wb){ + Name name; + + name = wb.createName(); + name.setNameName("Interest_Rate"); + name.setRefersToFormula("'Loan Calculator'!$E$5"); + + name = wb.createName(); + name.setNameName("Loan_Amount"); + name.setRefersToFormula("'Loan Calculator'!$E$4"); + + name = wb.createName(); + name.setNameName("Loan_Start"); + name.setRefersToFormula("'Loan Calculator'!$E$7"); + + name = wb.createName(); + name.setNameName("Loan_Years"); + name.setRefersToFormula("'Loan Calculator'!$E$6"); + + name = wb.createName(); + name.setNameName("Number_of_Payments"); + name.setRefersToFormula("'Loan Calculator'!$E$10"); + + name = wb.createName(); + name.setNameName("Monthly_Payment"); + name.setRefersToFormula("-PMT(Interest_Rate/12,Number_of_Payments,Loan_Amount)"); + + name = wb.createName(); + name.setNameName("Total_Cost"); + name.setRefersToFormula("'Loan Calculator'!$E$12"); + + name = wb.createName(); + name.setNameName("Total_Interest"); + name.setRefersToFormula("'Loan Calculator'!$E$11"); + + name = wb.createName(); + name.setNameName("Values_Entered"); + name.setRefersToFormula("IF(Loan_Amount*Interest_Rate*Loan_Years*Loan_Start>0,1,0)"); + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/SSPerformanceTest.java b/poi-examples/src/main/java/poi/ss/examples/SSPerformanceTest.java new file mode 100644 index 0000000000..4d6dee448b --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/SSPerformanceTest.java @@ -0,0 +1,204 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.apache.poi.ss.examples; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; + +public class SSPerformanceTest { + public static void main(String[] args) { + if (args.length != 4) usage("need four command arguments"); + + String type = args[0]; + long timeStarted = System.currentTimeMillis(); + Workbook workBook = createWorkbook(type); + boolean isHType = workBook instanceof HSSFWorkbook; + + int rows = parseInt(args[1], "Failed to parse rows value as integer"); + int cols = parseInt(args[2], "Failed to parse cols value as integer"); + boolean saveFile = parseInt(args[3], "Failed to parse saveFile value as integer") != 0; + + Map styles = createStyles(workBook); + + Sheet sheet = workBook.createSheet("Main Sheet"); + + Cell headerCell = sheet.createRow(0).createCell(0); + headerCell.setCellValue("Header text is spanned across multiple cells"); + headerCell.setCellStyle(styles.get("header")); + sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); + + int sheetNo = 0; + int rowIndexInSheet = 1; + double value = 0; + Calendar calendar = Calendar.getInstance(); + for (int rowIndex = 0; rowIndex < rows; rowIndex++) { + if (isHType && sheetNo != rowIndex / 0x10000) { + sheet = workBook.createSheet("Spillover from sheet " + (++sheetNo)); + headerCell.setCellValue("Header text is spanned across multiple cells"); + headerCell.setCellStyle(styles.get("header")); + sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); + rowIndexInSheet = 1; + } + + Row row = sheet.createRow(rowIndexInSheet); + for (int colIndex = 0; colIndex < cols; colIndex++) { + Cell cell = row.createCell(colIndex); + String address = new CellReference(cell).formatAsString(); + switch (colIndex){ + case 0: + // column A: default number format + cell.setCellValue(value++); + break; + case 1: + // column B: #,##0 + cell.setCellValue(value++); + cell.setCellStyle(styles.get("#,##0.00")); + break; + case 2: + // column C: $#,##0.00 + cell.setCellValue(value++); + cell.setCellStyle(styles.get("$#,##0.00")); + break; + case 3: + // column D: red bold text on yellow background + cell.setCellValue(address); + cell.setCellStyle(styles.get("red-bold")); + break; + case 4: + // column E: boolean + // TODO booleans are shown as 1/0 instead of TRUE/FALSE + cell.setCellValue(rowIndex % 2 == 0); + break; + case 5: + // column F: date / time + cell.setCellValue(calendar); + cell.setCellStyle(styles.get("m/d/yyyy")); + calendar.roll(Calendar.DAY_OF_YEAR, -1); + break; + case 6: + // column F: formula + // TODO formulas are not yet supported in SXSSF + //cell.setCellFormula("SUM(A" + (rowIndex+1) + ":E" + (rowIndex+1)+ ")"); + //break; + default: + cell.setCellValue(value++); + break; + } + } + rowIndexInSheet++; + } + if (saveFile) { + String fileName = type + "_" + rows + "_" + cols + "." + getFileSuffix(args[0]); + try { + FileOutputStream out = new FileOutputStream(fileName); + workBook.write(out); + out.close(); + } catch (IOException ioe) { + System.err.println("Error: failed to write to file \"" + fileName + "\", reason=" + ioe.getMessage()); + } + } + long timeFinished = System.currentTimeMillis(); + System.out.println("Elapsed " + (timeFinished-timeStarted)/1000 + " seconds"); + } + + static Map createStyles(Workbook wb) { + Map styles = new HashMap(); + CellStyle style; + + Font headerFont = wb.createFont(); + headerFont.setFontHeightInPoints((short) 14); + headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); + style.setFont(headerFont); + style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + styles.put("header", style); + + Font monthFont = wb.createFont(); + monthFont.setFontHeightInPoints((short)12); + monthFont.setColor(IndexedColors.RED.getIndex()); + monthFont.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); + style.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setFont(monthFont); + styles.put("red-bold", style); + + String[] nfmt = {"#,##0.00", "$#,##0.00", "m/d/yyyy"}; + for(String fmt : nfmt){ + style = wb.createCellStyle(); + style.setDataFormat(wb.createDataFormat().getFormat(fmt)); + styles.put(fmt, style); + } + + return styles; + } + + + static void usage(String message) { + System.err.println(message); + System.err.println("usage: java SSPerformanceTest HSSF|XSSF|SXSSF rows cols saveFile (0|1)? "); + System.exit(1); + } + + static Workbook createWorkbook(String type) { + if ("HSSF".equals(type)) + return new HSSFWorkbook(); + else if ("XSSF".equals(type)) + return new XSSFWorkbook(); + else if ("SXSSF".equals(type)) + return new SXSSFWorkbook(); + else + usage("Unknown type \"" + type + "\""); + return null; + } + + static String getFileSuffix(String type) { + if ("HSSF".equals(type)) + return "xls"; + else if ("XSSF".equals(type)) + return "xlsx"; + else if ("SXSSF".equals(type)) + return "xlsx"; + return null; + } + + static int parseInt(String value, String msg) { + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + usage(msg); + } + return 0; + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/TimesheetDemo.java b/poi-examples/src/main/java/poi/ss/examples/TimesheetDemo.java new file mode 100644 index 0000000000..8093f3c7ce --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/TimesheetDemo.java @@ -0,0 +1,220 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.ss.examples; + +import org.apache.poi.xssf.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +import java.util.Map; +import java.util.HashMap; +import java.io.FileOutputStream; + +/** + * A weekly timesheet created using Apache POI. + * Usage: + * TimesheetDemo -xls|xlsx + * + * @author Yegor Kozlov + */ +public class TimesheetDemo { + private static final String[] titles = { + "Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", + "Total\nHrs", "Overtime\nHrs", "Regular\nHrs" + }; + + private static Object[][] sample_data = { + {"Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0}, + {"Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, null, null, 4.0}, + }; + + public static void main(String[] args) throws Exception { + Workbook wb; + + if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); + else wb = new XSSFWorkbook(); + + Map styles = createStyles(wb); + + Sheet sheet = wb.createSheet("Timesheet"); + PrintSetup printSetup = sheet.getPrintSetup(); + printSetup.setLandscape(true); + sheet.setFitToPage(true); + sheet.setHorizontallyCenter(true); + + //title row + Row titleRow = sheet.createRow(0); + titleRow.setHeightInPoints(45); + Cell titleCell = titleRow.createCell(0); + titleCell.setCellValue("Weekly Timesheet"); + titleCell.setCellStyle(styles.get("title")); + sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1")); + + //header row + Row headerRow = sheet.createRow(1); + headerRow.setHeightInPoints(40); + Cell headerCell; + for (int i = 0; i < titles.length; i++) { + headerCell = headerRow.createCell(i); + headerCell.setCellValue(titles[i]); + headerCell.setCellStyle(styles.get("header")); + } + + int rownum = 2; + for (int i = 0; i < 10; i++) { + Row row = sheet.createRow(rownum++); + for (int j = 0; j < titles.length; j++) { + Cell cell = row.createCell(j); + if(j == 9){ + //the 10th cell contains sum over week days, e.g. SUM(C3:I3) + String ref = "C" +rownum+ ":I" + rownum; + cell.setCellFormula("SUM("+ref+")"); + cell.setCellStyle(styles.get("formula")); + } else if (j == 11){ + cell.setCellFormula("J" +rownum+ "-K" + rownum); + cell.setCellStyle(styles.get("formula")); + } else { + cell.setCellStyle(styles.get("cell")); + } + } + } + + //row with totals below + Row sumRow = sheet.createRow(rownum++); + sumRow.setHeightInPoints(35); + Cell cell; + cell = sumRow.createCell(0); + cell.setCellStyle(styles.get("formula")); + cell = sumRow.createCell(1); + cell.setCellValue("Total Hrs:"); + cell.setCellStyle(styles.get("formula")); + + for (int j = 2; j < 12; j++) { + cell = sumRow.createCell(j); + String ref = (char)('A' + j) + "3:" + (char)('A' + j) + "12"; + cell.setCellFormula("SUM(" + ref + ")"); + if(j >= 9) cell.setCellStyle(styles.get("formula_2")); + else cell.setCellStyle(styles.get("formula")); + } + rownum++; + sumRow = sheet.createRow(rownum++); + sumRow.setHeightInPoints(25); + cell = sumRow.createCell(0); + cell.setCellValue("Total Regular Hours"); + cell.setCellStyle(styles.get("formula")); + cell = sumRow.createCell(1); + cell.setCellFormula("L13"); + cell.setCellStyle(styles.get("formula_2")); + sumRow = sheet.createRow(rownum++); + sumRow.setHeightInPoints(25); + cell = sumRow.createCell(0); + cell.setCellValue("Total Overtime Hours"); + cell.setCellStyle(styles.get("formula")); + cell = sumRow.createCell(1); + cell.setCellFormula("K13"); + cell.setCellStyle(styles.get("formula_2")); + + //set sample data + for (int i = 0; i < sample_data.length; i++) { + Row row = sheet.getRow(2 + i); + for (int j = 0; j < sample_data[i].length; j++) { + if(sample_data[i][j] == null) continue; + + if(sample_data[i][j] instanceof String) { + row.getCell(j).setCellValue((String)sample_data[i][j]); + } else { + row.getCell(j).setCellValue((Double)sample_data[i][j]); + } + } + } + + //finally set column widths, the width is measured in units of 1/256th of a character width + sheet.setColumnWidth(0, 30*256); //30 characters wide + for (int i = 2; i < 9; i++) { + sheet.setColumnWidth(i, 6*256); //6 characters wide + } + sheet.setColumnWidth(10, 10*256); //10 characters wide + + // Write the output to a file + String file = "timesheet.xls"; + if(wb instanceof XSSFWorkbook) file += "x"; + FileOutputStream out = new FileOutputStream(file); + wb.write(out); + out.close(); + } + + /** + * Create a library of cell styles + */ + private static Map createStyles(Workbook wb){ + Map styles = new HashMap(); + CellStyle style; + Font titleFont = wb.createFont(); + titleFont.setFontHeightInPoints((short)18); + titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); + style.setFont(titleFont); + styles.put("title", style); + + Font monthFont = wb.createFont(); + monthFont.setFontHeightInPoints((short)11); + monthFont.setColor(IndexedColors.WHITE.getIndex()); + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); + style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setFont(monthFont); + style.setWrapText(true); + styles.put("header", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setWrapText(true); + style.setBorderRight(CellStyle.BORDER_THIN); + style.setRightBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderTop(CellStyle.BORDER_THIN); + style.setTopBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + styles.put("cell", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); + style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setDataFormat(wb.createDataFormat().getFormat("0.00")); + styles.put("formula", style); + + style = wb.createCellStyle(); + style.setAlignment(CellStyle.ALIGN_CENTER); + style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); + style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + style.setDataFormat(wb.createDataFormat().getFormat("0.00")); + styles.put("formula_2", style); + + return styles; + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/ToCSV.java b/poi-examples/src/main/java/poi/ss/examples/ToCSV.java new file mode 100644 index 0000000000..89b4f38c4d --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/ToCSV.java @@ -0,0 +1,770 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.ss.examples; + + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.util.ArrayList; + +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.DataFormatter; +import org.apache.poi.ss.usermodel.FormulaEvaluator; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; + +/** + * Demonstrates one way to convert an Excel spreadsheet into a CSV + * file. This class makes the following assumptions; + * + *
  • 1. Where the Excel workbook contains more that one worksheet, then a single + * CSV file will contain the data from all of the worksheets.
  • + *
  • 2. The data matrix contained in the CSV file will be square. This means that + * the number of fields in each record of the CSV file will match the number + * of cells in the longest row found in the Excel workbook. Any short records + * will be 'padded' with empty fields - an empty field is represented in the + * the CSV file in this way - ,,.
  • + *
  • 3. Empty fields will represent missing cells.
  • + *
  • 4. A record consisting of empty fields will be used to represent an empty row + * in the Excel workbook.
  • + *
    + * Therefore, if the worksheet looked like this; + * + *
    + *  ___________________________________________
    + *     |       |       |       |       |       |
    + *     |   A   |   B   |   C   |   D   |   E   |
    + *  ___|_______|_______|_______|_______|_______|
    + *     |       |       |       |       |       |
    + *   1 |   1   |   2   |   3   |   4   |   5   |
    + *  ___|_______|_______|_______|_______|_______|
    + *     |       |       |       |       |       |
    + *   2 |       |       |       |       |       |
    + *  ___|_______|_______|_______|_______|_______|
    + *     |       |       |       |       |       |
    + *   3 |       |   A   |       |   B   |       |
    + *  ___|_______|_______|_______|_______|_______|
    + *     |       |       |       |       |       |
    + *   4 |       |       |       |       |   Z   |
    + *  ___|_______|_______|_______|_______|_______|
    + *     |       |       |       |       |       |
    + *   5 | 1,400 |       |  250  |       |       |
    + *  ___|_______|_______|_______|_______|_______|
    + *
    + * 
    + * + * Then, the resulting CSV file will contain the following lines (records); + *
    + * 1,2,3,4,5
    + * ,,,,
    + * ,A,,B,
    + * ,,,,Z
    + * "1,400",,250,,
    + * 

    + * Typically, the comma is used to separate each of the fields that, together, + * constitute a single record or line within the CSV file. This is not however + * a hard and fast rule and so this class allows the user to determine which + * character is used as the field separator and assumes the comma if none other + * is specified. + *

    + * If a field contains the separator then it will be escaped. If the file should + * obey Excel's CSV formatting rules, then the field will be surrounded with + * speech marks whilst if it should obey UNIX conventions, each occurrence of + * the separator will be preceded by the backslash character. + *

    + * If a field contains an end of line (EOL) character then it too will be + * escaped. If the file should obey Excel's CSV formatting rules then the field + * will again be surrounded by speech marks. On the other hand, if the file + * should follow UNIX conventions then a single backslash will precede the + * EOL character. There is no single applicable standard for UNIX and some + * appications replace the CR with \r and the LF with \n but this class will + * not do so. + *

    + * If the field contains double quotes then that character will be escaped. It + * seems as though UNIX does not define a standard for this whilst Excel does. + * Should the CSV file have to obey Excel's formmating rules then the speech + * mark character will be escaped with a second set of speech marks. Finally, an + * enclosing set of speah marks will also surround the entire field. Thus, if + * the following line of text appeared in a cell - "Hello" he said - it would + * look like this when converted into a field within a CSV file - """Hello"" he + * said". + *

    + * Finally, it is worth noting that talk of CSV 'standards' is really slightly + * missleading as there is no such thing. It may well be that the code in this + * class has to be modified to produce files to suit a specific application + * or requirement. + *

    + * @author Mark B + * @version 1.00 9th April 2010 + * 1.10 13th April 2010 - Added support for processing all Excel + * workbooks in a folder along with the ability + * to specify a field separator character. + * 2.00 14th April 2010 - Added support for embedded characters; the + * field separator, EOL and double quotes or + * speech marks. In addition, gave the client + * the ability to select how these are handled, + * either obeying Excel's or UNIX formatting + * conventions. + */ +public class ToCSV { + + private Workbook workbook = null; + private ArrayList csvData = null; + private int maxRowWidth = 0; + private int formattingConvention = 0; + private DataFormatter formatter = null; + private FormulaEvaluator evaluator = null; + private String separator = null; + + private static final String CSV_FILE_EXTENSION = ".csv"; + private static final String DEFAULT_SEPARATOR = ","; + + /** + * Identifies that the CSV file should obey Excel's formatting conventions + * with regard to escaping certain embedded characters - the field separator, + * speech mark and end of line (EOL) character + */ + public static final int EXCEL_STYLE_ESCAPING = 0; + + /** + * Identifies that the CSV file should obey UNIX formatting conventions + * with regard to escaping certain embedded characters - the field separator + * and end of line (EOL) character + */ + public static final int UNIX_STYLE_ESCAPING = 1; + + /** + * Process the contents of a folder, convert the contents of each Excel + * workbook into CSV format and save the resulting file to the specified + * folder using the same name as the original workbook with the .xls or + * .xlsx extension replaced by .csv. This method will ensure that the + * CSV file created contains the comma field separator and that embedded + * characters such as the field separator, the EOL and double quotes are + * escaped in accordance with Excel's convention. + * + * @param strSource An instance of the String class that encapsulates the + * name of and path to either a folder containing those Excel + * workbook(s) or the name of and path to an individual Excel workbook + * that is/are to be converted. + * @param strDestination An instance of the String class encapsulating the + * name of and path to a folder that will contain the resulting CSV + * files. + * @throws java.io.FileNotFoundException Thrown if any file cannot be located + * on the filesystem during processing. + * @throws java.io.IOException Thrown if the filesystem encounters any + * problems during processing. + * @throws java.lang.IllegalArgumentException Thrown if the values passed + * to the strSource parameter refers to a file or folder that does not + * exist or if the value passed to the strDestination paramater refers + * to a folder that does not exist or simply does not refer to a + * folder. + * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown + * if the xml markup encountered whilst parsing a SpreadsheetML + * file (.xlsx) is invalid. + */ + public void convertExcelToCSV(String strSource, String strDestination) + throws FileNotFoundException, IOException, + IllegalArgumentException, InvalidFormatException { + + // Simply chain the call to the overloaded convertExcelToCSV(String, + // String, String, int) method, pass the default separator and ensure + // that certain embedded characters are escaped in accordance with + // Excel's formatting conventions + this.convertExcelToCSV(strSource, strDestination, + ToCSV.DEFAULT_SEPARATOR, ToCSV.EXCEL_STYLE_ESCAPING); + } + + /** + * Process the contents of a folder, convert the contents of each Excel + * workbook into CSV format and save the resulting file to the specified + * folder using the same name as the original workbook with the .xls or + * .xlsx extension replaced by .csv. This method allows the client to + * define the field separator but will ensure that embedded characters such + * as the field separator, the EOL and double quotes are escaped in + * accordance with Excel's convention. + * + * @param strSource An instance of the String class that encapsulates the + * name of and path to either a folder containing those Excel + * workbook(s) or the name of and path to an individual Excel workbook + * that is/are to be converted. + * @param strDestination An instance of the String class encapsulating the + * name of and path to a folder that will contain the resulting CSV + * files. + * @param separator An instance of the String class that encapsulates the + * character or characters the client wishes to use as the field + * separator. + * @throws java.io.FileNotFoundException Thrown if any file cannot be located + * on the filesystem during processing. + * @throws java.io.IOException Thrown if the filesystem encounters any + * problems during processing. + * @throws java.lang.IllegalArgumentException Thrown if the values passed + * to the strSource parameter refers to a file or folder that does not + * exist or if the value passed to the strDestination paramater refers + * to a folder that does not exist or simply does not refer to a + * folder. + * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown + * if the xml markup encounetered whilst parsing a SpreadsheetML + * file (.xlsx) is invalid. + */ + public void convertExcelToCSV(String strSource, String strDestination, + String separator) + throws FileNotFoundException, IOException, + IllegalArgumentException, InvalidFormatException { + + // Simply chain the call to the overloaded convertExcelToCSV(String, + // String, String, int) method and ensure that certain embedded + // characters are escaped in accordance with Excel's formatting + // conventions + this.convertExcelToCSV(strSource, strDestination, + separator, ToCSV.EXCEL_STYLE_ESCAPING); + } + + /** + * Process the contents of a folder, convert the contents of each Excel + * workbook into CSV format and save the resulting file to the specified + * folder using the same name as the original workbook with the .xls or + * .xlsx extension replaced by .csv + * + * @param strSource An instance of the String class that encapsulates the + * name of and path to either a folder containing those Excel + * workbook(s) or the name of and path to an individual Excel workbook + * that is/are to be converted. + * @param strDestination An instance of the String class encapsulating the name + * of and path to a folder that will contain the resulting CSV files. + * @param formattingConvention A primitive int whose value will determine + * whether certain embedded characters should be escaped in accordance + * with Excel's or UNIX formatting conventions. Two constants are + * defined to support this option; ToCSV.EXCEL_STYLE_ESCAPING and + * ToCSV.UNIX_STYLE_ESCAPING + * @param separator An instance of the String class encapsulating the + * characters or characters that should be used to separate items + * on a line within the CSV file. + * @throws java.io.FileNotFoundException Thrown if any file cannot be located + * on the filesystem during processing. + * @throws java.io.IOException Thrown if the filesystem encounters any + * problems during processing. + * @throws java.lang.IllegalArgumentException Thrown if the values passed + * to the strSource parameter refers to a file or folder that does not + * exist, if the value passed to the strDestination paramater refers + * to a folder that does not exist, if the value passed to the + * strDestination parameter does not refer to a folder or if the + * value passed to the formattingConvention parameter is other than + * one of the values defined by the constants ToCSV.EXCEL_STYLE_ESCAPING + * and ToCSV.UNIX_STYLE_ESCAPING. + * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown + * if the xml markup encounetered whilst parsing a SpreadsheetML + * file (.xlsx) is invalid. + */ + public void convertExcelToCSV(String strSource, String strDestination, + String separator, int formattingConvention) + throws FileNotFoundException, IOException, + IllegalArgumentException, InvalidFormatException { + File source = new File(strSource); + File destination = new File(strDestination); + File[] filesList = null; + String destinationFilename = null; + + // Check that the source file/folder exists. + if(!source.exists()) { + throw new IllegalArgumentException("The source for the Excel " + + "file(s) cannot be found."); + } + + // Ensure thaat the folder the user has chosen to save the CSV files + // away into firstly exists and secondly is a folder rather than, for + // instance, a data file. + if(!destination.exists()) { + throw new IllegalArgumentException("The folder/directory for the " + + "converted CSV file(s) does not exist."); + } + if(!destination.isDirectory()) { + throw new IllegalArgumentException("The destination for the CSV " + + "file(s) is not a directory/folder."); + } + + // Ensure the value passed to the formattingConvention parameter is + // within range. + if(formattingConvention != ToCSV.EXCEL_STYLE_ESCAPING && + formattingConvention != ToCSV.UNIX_STYLE_ESCAPING) { + throw new IllegalArgumentException("The value passed to the " + + "formattingConvention parameter is out of range."); + } + + // Copy the spearator character and formatting convention into local + // variables for use in other methods. + this.separator = separator; + this.formattingConvention = formattingConvention; + + // Check to see if the sourceFolder variable holds a reference to + // a file or a folder full of files. + if(source.isDirectory()) { + // Get a list of all of the Excel spreadsheet files (workbooks) in + // the source folder/directory + filesList = source.listFiles(new ExcelFilenameFilter()); + } + else { + // Assume that it must be a file handle - although there are other + // options the code should perhaps check - and store the reference + // into the filesList variable. + filesList = new File[]{source}; + } + + // Step through each of the files in the source folder and for each + // open the workbook, convert it's contents to CSV format and then + // save the resulting file away into the folder specified by the + // contents of the destination variable. Note that the name of the + // csv file will be created by taking the name of the Excel file, + // removing the extension and replacing it with .csv. Note that there + // is one drawback with this approach; if the folder holding the files + // contains two workbooks whose names match but one is a binary file + // (.xls) and the other a SpreadsheetML file (.xlsx), then the names + // for both CSV files will be identical and one CSV file will, + // therefore, over-write the other. + for(File excelFile : filesList) { + // Open the workbook + this.openWorkbook(excelFile); + + // Convert it's contents into a CSV file + this.convertToCSV(); + + // Build the name of the csv folder from that of the Excel workbook. + // Simply replace the .xls or .xlsx file extension with .csv + destinationFilename = excelFile.getName(); + destinationFilename = destinationFilename.substring( + 0, destinationFilename.lastIndexOf(".")) + + ToCSV.CSV_FILE_EXTENSION; + + // Save the CSV file away using the newly constricted file name + // and to the specified directory. + this.saveCSVFile(new File(destination, destinationFilename)); + } + } + + /** + * Open an Excel workbook ready for conversion. + * + * @param file An instance of the File class that encapsulates a handle + * to a valid Excel workbook. Note that the workbook can be in + * either binary (.xls) or SpreadsheetML (.xlsx) format. + * @throws java.io.FileNotFoundException Thrown if the file cannot be located. + * @throws java.io.IOException Thrown if a problem occurs in the file system. + * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown + * if invalid xml is found whilst parsing an input SpreadsheetML + * file. + */ + private void openWorkbook(File file) throws FileNotFoundException, + IOException, InvalidFormatException { + FileInputStream fis = null; + try { + System.out.println("Opening workbook [" + file.getName() + "]"); + + fis = new FileInputStream(file); + + // Open the workbook and then create the FormulaEvaluator and + // DataFormatter instances that will be needed to, respectively, + // force evaluation of forumlae found in cells and create a + // formatted String encapsulating the cells contents. + this.workbook = WorkbookFactory.create(fis); + this.evaluator = this.workbook.getCreationHelper().createFormulaEvaluator(); + this.formatter = new DataFormatter(true); + } + finally { + if(fis != null) { + fis.close(); + } + } + } + + /** + * Called to convert the contents of the currently opened workbook into + * a CSV file. + */ + private void convertToCSV() { + Sheet sheet = null; + Row row = null; + int lastRowNum = 0; + this.csvData = new ArrayList(); + + System.out.println("Converting files contents to CSV format."); + + // Discover how many sheets there are in the workbook.... + int numSheets = this.workbook.getNumberOfSheets(); + + // and then iterate through them. + for(int i = 0; i < numSheets; i++) { + + // Get a reference to a sheet and check to see if it contains + // any rows. + sheet = this.workbook.getSheetAt(i); + if(sheet.getPhysicalNumberOfRows() > 0) { + + // Note down the index number of the bottom-most row and + // then iterate through all of the rows on the sheet starting + // from the very first row - number 1 - even if it is missing. + // Recover a reference to the row and then call another method + // which will strip the data from the cells and build lines + // for inclusion in the resylting CSV file. + lastRowNum = sheet.getLastRowNum(); + for(int j = 0; j <= lastRowNum; j++) { + row = sheet.getRow(j); + this.rowToCSV(row); + } + } + } + } + + /** + * Called to actually save the data recovered from the Excel workbook + * as a CSV file. + * + * @param file An instance of the File class that encapsulates a handle + * referring to the CSV file. + * @throws java.io.FileNotFoundException Thrown if the file cannot be found. + * @throws java.io.IOException Thrown to indicate and error occurred in the + * underylying file system. + */ + private void saveCSVFile(File file) + throws FileNotFoundException, IOException { + FileWriter fw = null; + BufferedWriter bw = null; + ArrayList line = null; + StringBuffer buffer = null; + String csvLineElement = null; + try { + + System.out.println("Saving the CSV file [" + file.getName() + "]"); + + // Open a writer onto the CSV file. + fw = new FileWriter(file); + bw = new BufferedWriter(fw); + + // Step through the elements of the ArrayList that was used to hold + // all of the data recovered from the Excel workbooks' sheets, rows + // and cells. + for(int i = 0; i < this.csvData.size(); i++) { + buffer = new StringBuffer(); + + // Get an element from the ArrayList that contains the data for + // the workbook. This element will itself be an ArrayList + // containing Strings and each String will hold the data recovered + // from a single cell. The for() loop is used to recover elements + // from this 'row' ArrayList one at a time and to write the Strings + // away to a StringBuffer thus assembling a single line for inclusion + // in the CSV file. If a row was empty or if it was short, then + // the ArrayList that contains it's data will also be shorter than + // some of the others. Therefore, it is necessary to check within + // the for loop to ensure that the ArrayList contains data to be + // processed. If it does, then an element will be recovered and + // appended to the StringBuffer. + line = this.csvData.get(i); + for(int j = 0; j < this.maxRowWidth; j++) { + if(line.size() > j) { + csvLineElement = line.get(j); + if(csvLineElement != null) { + buffer.append(this.escapeEmbeddedCharacters( + csvLineElement)); + } + } + if(j < (this.maxRowWidth - 1)) { + buffer.append(this.separator); + } + } + + // Once the line is built, write it away to the CSV file. + bw.write(buffer.toString().trim()); + + // Condition the inclusion of new line characters so as to + // avoid an additional, superfluous, new line at the end of + // the file. + if(i < (this.csvData.size() - 1)) { + bw.newLine(); + } + } + } + finally { + if(bw != null) { + bw.flush(); + bw.close(); + } + } + } + + /** + * Called to convert a row of cells into a line of data that can later be + * output to the CSV file. + * + * @param row An instance of either the HSSFRow or XSSFRow classes that + * encapsulates information about a row of cells recovered from + * an Excel workbook. + */ + private void rowToCSV(Row row) { + Cell cell = null; + int lastCellNum = 0; + ArrayList csvLine = new ArrayList(); + + // Check to ensure that a row was recovered from the sheet as it is + // possible that one or more rows between other populated rows could be + // missing - blank. If the row does contain cells then... + if(row != null) { + + // Get the index for the right most cell on the row and then + // step along the row from left to right recovering the contents + // of each cell, converting that into a formatted String and + // then storing the String into the csvLine ArrayList. + lastCellNum = row.getLastCellNum(); + for(int i = 0; i <= lastCellNum; i++) { + cell = row.getCell(i); + if(cell == null) { + csvLine.add(""); + } + else { + if(cell.getCellType() != Cell.CELL_TYPE_FORMULA) { + csvLine.add(this.formatter.formatCellValue(cell)); + } + else { + csvLine.add(this.formatter.formatCellValue(cell, this.evaluator)); + } + } + } + // Make a note of the index number of the right most cell. This value + // will later be used to ensure that the matrix of data in the CSV file + // is square. + if(lastCellNum > this.maxRowWidth) { + this.maxRowWidth = lastCellNum; + } + } + this.csvData.add(csvLine); + } + + /** + * Checks to see whether the field - which consists of the formatted + * contents of an Excel worksheet cell encapsulated within a String - contains + * any embedded characters that must be escaped. The method is able to + * comply with either Excel's or UNIX formatting conventions in the + * following manner; + * + * With regard to UNIX conventions, if the field contains any embedded + * field separator or EOL characters they will each be escaped by prefixing + * a leading backspace character. These are the only changes that have yet + * emerged following some research as being required. + * + * Excel has other embedded character escaping requirements, some that emerged + * from empirical testing, other through research. Firstly, with regards to + * any embedded speech marks ("), each occurrence should be escaped with + * another speech mark and the whole field then surrounded with speech marks. + * Thus if a field holds "Hello" he said then it should be modified + * to appear as """Hello"" he said". Furthermore, if the field + * contains either embedded separator or EOL characters, it should also + * be surrounded with speech marks. As a result 1,400 would become + * "1,400" assuming that the comma is the required field separator. + * This has one consequence in, if a field contains embedded speech marks + * and embedded separator characters, checks for both are not required as the + * additional set of speech marks that should be placed around ay field + * containing embedded speech marks will also account for the embedded + * separator. + * + * It is worth making one further note with regard to embedded EOL + * characters. If the data in a worksheet is exported as a CSV file using + * Excel itself, then the field will be surounded with speech marks. If the + * resulting CSV file is then re-imports into another worksheet, the EOL + * character will result in the original simgle field occupying more than + * one cell. This same 'feature' is replicated in this classes behaviour. + * + * @param field An instance of the String class encapsulating the formatted + * contents of a cell on an Excel worksheet. + * @return A String that encapsulates the formatted contents of that + * Excel worksheet cell but with any embedded separator, EOL or + * speech mark characters correctly escaped. + */ + private String escapeEmbeddedCharacters(String field) { + StringBuffer buffer = null; + + // If the fields contents should be formatted to confrom with Excel's + // convention.... + if(this.formattingConvention == ToCSV.EXCEL_STYLE_ESCAPING) { + + // Firstly, check if there are any speech marks (") in the field; + // each occurrence must be escaped with another set of spech marks + // and then the entire field should be enclosed within another + // set of speech marks. Thus, "Yes" he said would become + // """Yes"" he said" + if(field.contains("\"")) { + buffer = new StringBuffer(field.replaceAll("\"", "\\\"\\\"")); + buffer.insert(0, "\""); + buffer.append("\""); + } + else { + // If the field contains either embedded separator or EOL + // characters, then escape the whole field by surrounding it + // with speech marks. + buffer = new StringBuffer(field); + if((buffer.indexOf(this.separator)) > -1 || + (buffer.indexOf("\n")) > -1) { + buffer.insert(0, "\""); + buffer.append("\""); + } + } + return(buffer.toString().trim()); + } + // The only other formatting convention this class obeys is the UNIX one + // where any occurrence of the field separator or EOL character will + // be escaped by preceding it with a backslash. + else { + if(field.contains(this.separator)) { + field = field.replaceAll(this.separator, ("\\\\" + this.separator)); + } + if(field.contains("\n")) { + field = field.replaceAll("\n", "\\\\\n"); + } + return(field); + } + } + + /** + * The main() method contains code that demonstrates how to use the class. + * + * @param args An array containing zero, one or more elements all of type + * String. Each element will encapsulate an argument specified by the + * user when running the program from the command prompt. + */ + public static void main(String[] args) { + // Check the number of arguments passed to the main method. There + // must be two, three or four; the name of and path to either the folder + // containing the Excel files or an individual Excel workbook that is/are + // to be converted, the name of and path to the folder to which the CSV + // files should be written, - optionally - the separator character + // that should be used to separate individual items (fields) on the + // lines (records) of the CSV file and - again optionally - an integer + // that idicates whether the CSV file ought to obey Excel's or UNIX + // convnetions with regard to formatting fields that contain embedded + // separator, Speech mark or EOL character(s). + // + // Note that the names of the CSV files will be derived from those + // of the Excel file(s). Put simply the .xls or .xlsx extension will be + // replaced with .csv. Therefore, if the source folder contains files + // with matching names but different extensions - Test.xls and Test.xlsx + // for example - then the CSV file generated from one will overwrite + // that generated from the other. + ToCSV converter = null; + boolean converted = true; + long startTime = System.currentTimeMillis(); + try { + converter = new ToCSV(); + if(args.length == 2) { + // Just the Source File/Folder and Destination Folder were + // passed to the main method. + converter.convertExcelToCSV(args[0], args[1]); + } + else if(args.length == 3){ + // The Source File/Folder, Destination Folder and Separator + // were passed to the main method. + converter.convertExcelToCSV(args[0], args[1], args[2]); + } + else if(args.length == 4) { + // The Source File/Folder, Destination Folder, Separator and + // Formatting Convnetion were passed to the main method. + converter.convertExcelToCSV(args[0], args[1], + args[2], Integer.parseInt(args[3])); + } + else { + // None or more than four parameters were passed so display + //a Usage message. + System.out.println("Usage: java ToCSV [Source File/Folder] " + + "[Destination Folder] [Separator] [Formatting Convention]\n" + + "\tSource File/Folder\tThis argument should contain the name of and\n" + + "\t\t\t\tpath to either a single Excel workbook or a\n" + + "\t\t\t\tfolder containing one or more Excel workbooks.\n" + + "\tDestination Folder\tThe name of and path to the folder that the\n" + + "\t\t\t\tCSV files should be written out into. The\n" + + "\t\t\t\tfolder must exist before running the ToCSV\n" + + "\t\t\t\tcode as it will not check for or create it.\n" + + "\tSeparator\t\tOptional. The character or characters that\n" + + "\t\t\t\tshould be used to separate fields in the CSV\n" + + "\t\t\t\trecord. If no value is passed then the comma\n" + + "\t\t\t\twill be assumed.\n" + + "\tFormatting Convention\tOptional. This argument can take one of two\n" + + "\t\t\t\tvalues. Passing 0 (zero) will result in a CSV\n" + + "\t\t\t\tfile that obeys Excel's formatting conventions\n" + + "\t\t\t\twhilst passing 1 (one) will result in a file\n" + + "\t\t\t\tthat obeys UNIX formatting conventions. If no\n" + + "\t\t\t\tvalue is passed, then the CSV file produced\n" + + "\t\t\t\twill obey Excel's formatting conventions."); + converted = false; + } + } + // It is not wise to have such a wide catch clause - Exception is very + // close to being at the top of the inheritance hierarchy - though it + // will suffice for this example as it is really not possible to recover + // easilly from an exceptional set of circumstances at this point in the + // program. It should however, ideally be replaced with one or more + // catch clauses optimised to handle more specific problems. + catch(Exception ex) { + System.out.println("Caught an: " + ex.getClass().getName()); + System.out.println("Message: " + ex.getMessage()); + System.out.println("Stacktrace follows:....."); + ex.printStackTrace(System.out); + converted = false; + } + + if (converted) { + System.out.println("Conversion took " + + (int)((System.currentTimeMillis() - startTime)/1000) + " seconds"); + } + } + + /** + * An instance of this class can be used to control the files returned + * be a call to the listFiles() method when made on an instance of the + * File class and that object refers to a folder/directory + */ + class ExcelFilenameFilter implements FilenameFilter { + + /** + * Determine those files that will be returned by a call to the + * listFiles() method. In this case, the name of the file must end with + * either of the following two extension; '.xls' or '.xlsx'. For the + * future, it is very possible to parameterise this and allow the + * containing class to pass, for example, an array of Strings to this + * class on instantiation. Each element in that array could encapsulate + * a valid file extension - '.xls', '.xlsx', '.xlt', '.xlst', etc. These + * could then be used to control which files were returned by the call + * to the listFiles() method. + * + * @param file An instance of the File class that encapsulates a handle + * referring to the folder/directory that contains the file. + * @param name An instance of the String class that encapsulates the + * name of the file. + * @return A boolean value that indicates whether the file should be + * included in the array retirned by the call to the listFiles() + * method. In this case true will be returned if the name of the + * file ends with either '.xls' or '.xlsx' and false will be + * returned in all other instances. + */ + public boolean accept(File file, String name) { + return(name.endsWith(".xls") || name.endsWith(".xlsx")); + } + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/formula/CalculateMortgage.java b/poi-examples/src/main/java/poi/ss/examples/formula/CalculateMortgage.java new file mode 100644 index 0000000000..4b9a325cdf --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/formula/CalculateMortgage.java @@ -0,0 +1,93 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.ss.examples.formula; + +import org.apache.poi.ss.formula.OperationEvaluationContext ; +import org.apache.poi.ss.formula.eval.ErrorEval ; +import org.apache.poi.ss.formula.eval.EvaluationException ; +import org.apache.poi.ss.formula.eval.NumberEval ; +import org.apache.poi.ss.formula.eval.OperandResolver ; +import org.apache.poi.ss.formula.eval.ValueEval ; +import org.apache.poi.ss.formula.functions.FreeRefFunction ; + +/** + * A simple user-defined function to calculate principal and interest. + * + * @author Jon Svede ( jon [at] loquatic [dot] com ) + * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) + * + */ +public class CalculateMortgage implements FreeRefFunction { + + public ValueEval evaluate( ValueEval[] args, OperationEvaluationContext ec ) { + + // verify that we have enough data + if (args.length != 3) { + return ErrorEval.VALUE_INVALID; + } + + // declare doubles for values + double principal, rate, years, result; + try { + // extract values as ValueEval + ValueEval v1 = OperandResolver.getSingleValue( args[0], + ec.getRowIndex(), + ec.getColumnIndex() ) ; + ValueEval v2 = OperandResolver.getSingleValue( args[1], + ec.getRowIndex(), + ec.getColumnIndex() ) ; + ValueEval v3 = OperandResolver.getSingleValue( args[2], + ec.getRowIndex(), + ec.getColumnIndex() ) ; + + // get data as doubles + principal = OperandResolver.coerceValueToDouble( v1 ) ; + rate = OperandResolver.coerceValueToDouble( v2 ) ; + years = OperandResolver.coerceValueToDouble( v3 ) ; + + result = calculateMortgagePayment( principal, rate, years ) ; + System.out.println( "Result = " + result ) ; + + checkValue(result); + + } catch (EvaluationException e) { + return e.getErrorEval(); + } + + return new NumberEval( result ) ; + } + + public double calculateMortgagePayment( double p, double r, double y ) { + double i = r / 12 ; + double n = y * 12 ; + + double principalAndInterest = + p * (( i * Math.pow((1 + i),n ) ) / ( Math.pow((1 + i),n) - 1)) ; + + return principalAndInterest ; + } + /** + * Excel does not support infinities and NaNs, rather, it gives a #NUM! error in these cases + * + * @throws EvaluationException (#NUM!) if result is NaN or Infinity + */ + private void checkValue(double result) throws EvaluationException { + if (Double.isNaN(result) || Double.isInfinite(result)) { + throw new EvaluationException(ErrorEval.NUM_ERROR); + } + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/formula/SettingExternalFunction.java b/poi-examples/src/main/java/poi/ss/examples/formula/SettingExternalFunction.java new file mode 100644 index 0000000000..17f4e0dfa8 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/formula/SettingExternalFunction.java @@ -0,0 +1,93 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.ss.examples.formula; + +import org.apache.poi.ss.formula.OperationEvaluationContext; +import org.apache.poi.ss.formula.eval.ErrorEval; +import org.apache.poi.ss.formula.eval.ValueEval; +import org.apache.poi.ss.formula.functions.FreeRefFunction; +import org.apache.poi.ss.formula.udf.UDFFinder; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Demonstrates how to use functions provided by third-party add-ins, e.g. Bloomberg Excel Add-in. + * + * There can be situations when you are not interested in formula evaluation, + * you just need to set the formula and the workbook will be evaluation by the client. + * + * @author Yegor Kozlov + */ +public class SettingExternalFunction { + + /** + * wrap external functions in a plugin + */ + public static class BloombergAddIn implements UDFFinder { + private final Map _functionsByName; + + public BloombergAddIn() { + // dummy function that returns NA + // don't care about the implementation, we are not interested in evaluation + // and this method will never be called + FreeRefFunction NA = new FreeRefFunction() { + public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { + return ErrorEval.NA; + } + }; + _functionsByName = new HashMap(); + _functionsByName.put("BDP", NA); + _functionsByName.put("BDH", NA); + _functionsByName.put("BDS", NA); + } + + public FreeRefFunction findFunction(String name) { + return _functionsByName.get(name.toUpperCase()); + } + + } + + public static void main( String[] args ) throws IOException { + + Workbook wb = new XSSFWorkbook(); // or new HSSFWorkbook() + + // register the add-in + wb.addToolPack(new BloombergAddIn()); + + Sheet sheet = wb.createSheet(); + Row row = sheet.createRow(0); + row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100"); + row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") "); + row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") "); + + FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx"); + wb.write(out); + out.close(); + + } + +} diff --git a/poi-examples/src/main/java/poi/ss/examples/formula/UserDefinedFunctionExample.java b/poi-examples/src/main/java/poi/ss/examples/formula/UserDefinedFunctionExample.java new file mode 100644 index 0000000000..74dca7d1b6 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/formula/UserDefinedFunctionExample.java @@ -0,0 +1,89 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.ss.examples.formula; + +import java.io.File ; +import java.io.FileInputStream ; +import java.io.FileNotFoundException ; +import java.io.IOException ; + +import org.apache.poi.openxml4j.exceptions.InvalidFormatException ; +import org.apache.poi.ss.formula.functions.FreeRefFunction ; +import org.apache.poi.ss.formula.udf.DefaultUDFFinder ; +import org.apache.poi.ss.formula.udf.UDFFinder ; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellReference ; + + +/** + * An example class of how to invoke a User Defined Function for a given + * XLS instance using POI's UDFFinder implementation. + * + * @author Jon Svede ( jon [at] loquatic [dot] com ) + * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) + * + */ +public class UserDefinedFunctionExample { + + public static void main( String[] args ) { + + if( args.length != 2 ) { + System.out.println( "usage: UserDefinedFunctionExample fileName cellId" ) ; + return; + } + + System.out.println( "fileName: " + args[0] ) ; + System.out.println( "cell: " + args[1] ) ; + + File workbookFile = new File( args[0] ) ; + + try { + FileInputStream fis = new FileInputStream(workbookFile); + Workbook workbook = WorkbookFactory.create(fis); + fis.close(); + + String[] functionNames = { "calculatePayment" } ; + FreeRefFunction[] functionImpls = { new CalculateMortgage() } ; + + UDFFinder udfToolpack = new DefaultUDFFinder( functionNames, functionImpls ) ; + + // register the user-defined function in the workbook + workbook.addToolPack(udfToolpack); + + FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); + + CellReference cr = new CellReference( args[1] ) ; + String sheetName = cr.getSheetName() ; + Sheet sheet = workbook.getSheet( sheetName ) ; + int rowIdx = cr.getRow() ; + int colIdx = cr.getCol() ; + Row row = sheet.getRow( rowIdx ) ; + Cell cell = row.getCell( colIdx ) ; + + CellValue value = evaluator.evaluate( cell ) ; + + System.out.println("returns value: " + value ) ; + + } catch( FileNotFoundException e ) { + e.printStackTrace(); + } catch( InvalidFormatException e ) { + e.printStackTrace(); + } catch( IOException e ) { + e.printStackTrace(); + } + } +} diff --git a/poi-examples/src/main/java/poi/ss/examples/formula/mortgage-calculation.xls b/poi-examples/src/main/java/poi/ss/examples/formula/mortgage-calculation.xls new file mode 100644 index 0000000000..4e71ba8e65 Binary files /dev/null and b/poi-examples/src/main/java/poi/ss/examples/formula/mortgage-calculation.xls differ diff --git a/poi-examples/src/main/java/poi/ss/examples/html/HSSFHtmlHelper.java b/poi-examples/src/main/java/poi/ss/examples/html/HSSFHtmlHelper.java new file mode 100644 index 0000000000..1e235f929e --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/html/HSSFHtmlHelper.java @@ -0,0 +1,66 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.ss.examples.html; + +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFPalette; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.CellStyle; + +import java.util.Formatter; + +/** + * Implementation of {@link HtmlHelper} for HSSF files. + * + * @author Ken Arnold, Industrious Media LLC + */ +public class HSSFHtmlHelper implements HtmlHelper { + private final HSSFWorkbook wb; + private final HSSFPalette colors; + + private static final HSSFColor HSSF_AUTO = new HSSFColor.AUTOMATIC(); + + public HSSFHtmlHelper(HSSFWorkbook wb) { + this.wb = wb; + // If there is no custom palette, then this creates a new one that is + // a copy of the default + colors = wb.getCustomPalette(); + } + + public void colorStyles(CellStyle style, Formatter out) { + HSSFCellStyle cs = (HSSFCellStyle) style; + out.format(" /* fill pattern = %d */%n", cs.getFillPattern()); + styleColor(out, "background-color", cs.getFillForegroundColor()); + styleColor(out, "color", cs.getFont(wb).getColor()); + styleColor(out, "border-left-color", cs.getLeftBorderColor()); + styleColor(out, "border-right-color", cs.getRightBorderColor()); + styleColor(out, "border-top-color", cs.getTopBorderColor()); + styleColor(out, "border-bottom-color", cs.getBottomBorderColor()); + } + + private void styleColor(Formatter out, String attr, short index) { + HSSFColor color = colors.getColor(index); + if (index == HSSF_AUTO.getIndex() || color == null) { + out.format(" /* %s: index = %d */%n", attr, index); + } else { + short[] rgb = color.getTriplet(); + out.format(" %s: #%02x%02x%02x; /* index = %d */%n", attr, rgb[0], + rgb[1], rgb[2], index); + } + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/ss/examples/html/HtmlHelper.java b/poi-examples/src/main/java/poi/ss/examples/html/HtmlHelper.java new file mode 100644 index 0000000000..2cb1a91734 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/html/HtmlHelper.java @@ -0,0 +1,40 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.ss.examples.html; + +import org.apache.poi.ss.usermodel.CellStyle; + +import java.util.Formatter; + +/** + * This interface is used where code wants to be independent of the workbook + * formats. If you are writing such code, you can add a method to this + * interface, and then implement it for both HSSF and XSSF workbooks, letting + * the driving code stay independent of format. + * + * @author Ken Arnold, Industrious Media LLC + */ +public interface HtmlHelper { + /** + * Outputs the appropriate CSS style for the given cell style. + * + * @param style The cell style. + * @param out The place to write the output. + */ + void colorStyles(CellStyle style, Formatter out); +} diff --git a/poi-examples/src/main/java/poi/ss/examples/html/ToHtml.java b/poi-examples/src/main/java/poi/ss/examples/html/ToHtml.java new file mode 100644 index 0000000000..b5480cf59e --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/html/ToHtml.java @@ -0,0 +1,443 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.ss.examples.html; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFFont; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.format.CellFormat; +import org.apache.poi.ss.format.CellFormatResult; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import java.io.BufferedReader; +import java.io.Closeable; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Formatter; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import static org.apache.poi.ss.usermodel.CellStyle.*; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; + +/** + * This example shows how to display a spreadsheet in HTML using the classes for + * spreadsheet display. + * + * @author Ken Arnold, Industrious Media LLC + */ +public class ToHtml { + private final Workbook wb; + private final Appendable output; + private boolean completeHTML; + private Formatter out; + private boolean gotBounds; + private int firstColumn; + private int endColumn; + private HtmlHelper helper; + + private static final String DEFAULTS_CLASS = "excelDefaults"; + private static final String COL_HEAD_CLASS = "colHeader"; + private static final String ROW_HEAD_CLASS = "rowHeader"; + + private static final Map ALIGN = mapFor(ALIGN_LEFT, "left", + ALIGN_CENTER, "center", ALIGN_RIGHT, "right", ALIGN_FILL, "left", + ALIGN_JUSTIFY, "left", ALIGN_CENTER_SELECTION, "center"); + + private static final Map VERTICAL_ALIGN = mapFor( + VERTICAL_BOTTOM, "bottom", VERTICAL_CENTER, "middle", VERTICAL_TOP, + "top"); + + private static final Map BORDER = mapFor(BORDER_DASH_DOT, + "dashed 1pt", BORDER_DASH_DOT_DOT, "dashed 1pt", BORDER_DASHED, + "dashed 1pt", BORDER_DOTTED, "dotted 1pt", BORDER_DOUBLE, + "double 3pt", BORDER_HAIR, "solid 1px", BORDER_MEDIUM, "solid 2pt", + BORDER_MEDIUM_DASH_DOT, "dashed 2pt", BORDER_MEDIUM_DASH_DOT_DOT, + "dashed 2pt", BORDER_MEDIUM_DASHED, "dashed 2pt", BORDER_NONE, + "none", BORDER_SLANTED_DASH_DOT, "dashed 2pt", BORDER_THICK, + "solid 3pt", BORDER_THIN, "dashed 1pt"); + + @SuppressWarnings({"unchecked"}) + private static Map mapFor(Object... mapping) { + Map map = new HashMap(); + for (int i = 0; i < mapping.length; i += 2) { + map.put((K) mapping[i], (V) mapping[i + 1]); + } + return map; + } + + /** + * Creates a new converter to HTML for the given workbook. + * + * @param wb The workbook. + * @param output Where the HTML output will be written. + * + * @return An object for converting the workbook to HTML. + */ + public static ToHtml create(Workbook wb, Appendable output) { + return new ToHtml(wb, output); + } + + /** + * Creates a new converter to HTML for the given workbook. If the path ends + * with ".xlsx" an {@link XSSFWorkbook} will be used; otherwise + * this will use an {@link HSSFWorkbook}. + * + * @param path The file that has the workbook. + * @param output Where the HTML output will be written. + * + * @return An object for converting the workbook to HTML. + */ + public static ToHtml create(String path, Appendable output) + throws IOException { + return create(new FileInputStream(path), output); + } + + /** + * Creates a new converter to HTML for the given workbook. This attempts to + * detect whether the input is XML (so it should create an {@link + * XSSFWorkbook} or not (so it should create an {@link HSSFWorkbook}). + * + * @param in The input stream that has the workbook. + * @param output Where the HTML output will be written. + * + * @return An object for converting the workbook to HTML. + */ + public static ToHtml create(InputStream in, Appendable output) + throws IOException { + try { + Workbook wb = WorkbookFactory.create(in); + return create(wb, output); + } catch (InvalidFormatException e){ + throw new IllegalArgumentException("Cannot create workbook from stream", e); + } + } + + private ToHtml(Workbook wb, Appendable output) { + if (wb == null) + throw new NullPointerException("wb"); + if (output == null) + throw new NullPointerException("output"); + this.wb = wb; + this.output = output; + setupColorMap(); + } + + private void setupColorMap() { + if (wb instanceof HSSFWorkbook) + helper = new HSSFHtmlHelper((HSSFWorkbook) wb); + else if (wb instanceof XSSFWorkbook) + helper = new XSSFHtmlHelper((XSSFWorkbook) wb); + else + throw new IllegalArgumentException( + "unknown workbook type: " + wb.getClass().getSimpleName()); + } + + /** + * Run this class as a program + * + * @param args The command line arguments. + * + * @throws Exception Exception we don't recover from. + */ + public static void main(String[] args) throws Exception { + if(args.length < 2){ + System.err.println("usage: ToHtml inputWorkbook outputHtmlFile"); + return; + } + + ToHtml toHtml = create(args[0], new PrintWriter(new FileWriter(args[1]))); + toHtml.setCompleteHTML(true); + toHtml.printPage(); + } + + public void setCompleteHTML(boolean completeHTML) { + this.completeHTML = completeHTML; + } + + public void printPage() throws IOException { + try { + ensureOut(); + if (completeHTML) { + out.format( + "%n"); + out.format("%n"); + out.format("%n"); + out.format("%n"); + out.format("%n"); + } + + print(); + + if (completeHTML) { + out.format("%n"); + out.format("%n"); + } + } finally { + if (out != null) + out.close(); + if (output instanceof Closeable) { + Closeable closeable = (Closeable) output; + closeable.close(); + } + } + } + + public void print() { + printInlineStyle(); + printSheets(); + } + + private void printInlineStyle() { + //out.format("%n"); + out.format("%n"); + } + + private void ensureOut() { + if (out == null) + out = new Formatter(output); + } + + public void printStyles() { + ensureOut(); + + // First, copy the base css + BufferedReader in = null; + try { + in = new BufferedReader(new InputStreamReader( + getClass().getResourceAsStream("excelStyle.css"))); + String line; + while ((line = in.readLine()) != null) { + out.format("%s%n", line); + } + } catch (IOException e) { + throw new IllegalStateException("Reading standard css", e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + //noinspection ThrowFromFinallyBlock + throw new IllegalStateException("Reading standard css", e); + } + } + } + + // now add css for each used style + Set seen = new HashSet(); + for (int i = 0; i < wb.getNumberOfSheets(); i++) { + Sheet sheet = wb.getSheetAt(i); + Iterator rows = sheet.rowIterator(); + while (rows.hasNext()) { + Row row = rows.next(); + for (Cell cell : row) { + CellStyle style = cell.getCellStyle(); + if (!seen.contains(style)) { + printStyle(style); + seen.add(style); + } + } + } + } + } + + private void printStyle(CellStyle style) { + out.format(".%s .%s {%n", DEFAULTS_CLASS, styleName(style)); + styleContents(style); + out.format("}%n"); + } + + private void styleContents(CellStyle style) { + styleOut("text-align", style.getAlignment(), ALIGN); + styleOut("vertical-align", style.getAlignment(), VERTICAL_ALIGN); + fontStyle(style); + borderStyles(style); + helper.colorStyles(style, out); + } + + private void borderStyles(CellStyle style) { + styleOut("border-left", style.getBorderLeft(), BORDER); + styleOut("border-right", style.getBorderRight(), BORDER); + styleOut("border-top", style.getBorderTop(), BORDER); + styleOut("border-bottom", style.getBorderBottom(), BORDER); + } + + private void fontStyle(CellStyle style) { + Font font = wb.getFontAt(style.getFontIndex()); + + if (font.getBoldweight() >= HSSFFont.BOLDWEIGHT_NORMAL) + out.format(" font-weight: bold;%n"); + if (font.getItalic()) + out.format(" font-style: italic;%n"); + + int fontheight = font.getFontHeightInPoints(); + if (fontheight == 9) { + //fix for stupid ol Windows + fontheight = 10; + } + out.format(" font-size: %dpt;%n", fontheight); + + // Font color is handled with the other colors + } + + private String styleName(CellStyle style) { + if (style == null) + style = wb.getCellStyleAt((short) 0); + StringBuilder sb = new StringBuilder(); + Formatter fmt = new Formatter(sb); + fmt.format("style_%02x", style.getIndex()); + return fmt.toString(); + } + + private void styleOut(String attr, K key, Map mapping) { + String value = mapping.get(key); + if (value != null) { + out.format(" %s: %s;%n", attr, value); + } + } + + private static int ultimateCellType(Cell c) { + int type = c.getCellType(); + if (type == Cell.CELL_TYPE_FORMULA) + type = c.getCachedFormulaResultType(); + return type; + } + + private void printSheets() { + ensureOut(); + Sheet sheet = wb.getSheetAt(0); + printSheet(sheet); + } + + public void printSheet(Sheet sheet) { + ensureOut(); + out.format("%n", DEFAULTS_CLASS); + printCols(sheet); + printSheetContent(sheet); + out.format("
    %n"); + } + + private void printCols(Sheet sheet) { + out.format("%n"); + ensureColumnBounds(sheet); + for (int i = firstColumn; i < endColumn; i++) { + out.format("%n"); + } + } + + private void ensureColumnBounds(Sheet sheet) { + if (gotBounds) + return; + + Iterator iter = sheet.rowIterator(); + firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0); + endColumn = 0; + while (iter.hasNext()) { + Row row = iter.next(); + short firstCell = row.getFirstCellNum(); + if (firstCell >= 0) { + firstColumn = Math.min(firstColumn, firstCell); + endColumn = Math.max(endColumn, row.getLastCellNum()); + } + } + gotBounds = true; + } + + private void printColumnHeads() { + out.format("%n"); + out.format(" %n", COL_HEAD_CLASS); + out.format(" ◊%n", COL_HEAD_CLASS); + //noinspection UnusedDeclaration + StringBuilder colName = new StringBuilder(); + for (int i = firstColumn; i < endColumn; i++) { + colName.setLength(0); + int cnum = i; + do { + colName.insert(0, (char) ('A' + cnum % 26)); + cnum /= 26; + } while (cnum > 0); + out.format(" %s%n", COL_HEAD_CLASS, colName); + } + out.format(" %n"); + out.format("%n"); + } + + private void printSheetContent(Sheet sheet) { + printColumnHeads(); + + out.format("%n"); + Iterator rows = sheet.rowIterator(); + while (rows.hasNext()) { + Row row = rows.next(); + + out.format(" %n"); + out.format(" %d%n", ROW_HEAD_CLASS, + row.getRowNum() + 1); + for (int i = firstColumn; i < endColumn; i++) { + String content = " "; + String attrs = ""; + CellStyle style = null; + if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) { + Cell cell = row.getCell(i); + if (cell != null) { + style = cell.getCellStyle(); + attrs = tagStyle(cell, style); + //Set the value that is rendered for the cell + //also applies the format + CellFormat cf = CellFormat.getInstance( + style.getDataFormatString()); + CellFormatResult result = cf.apply(cell); + content = result.text; + if (content.equals("")) + content = " "; + } + } + out.format(" %s%n", styleName(style), + attrs, content); + } + out.format(" %n"); + } + out.format("%n"); + } + + private String tagStyle(Cell cell, CellStyle style) { + if (style.getAlignment() == ALIGN_GENERAL) { + switch (ultimateCellType(cell)) { + case HSSFCell.CELL_TYPE_STRING: + return "style=\"text-align: left;\""; + case HSSFCell.CELL_TYPE_BOOLEAN: + case HSSFCell.CELL_TYPE_ERROR: + return "style=\"text-align: center;\""; + case HSSFCell.CELL_TYPE_NUMERIC: + default: + // "right" is the default + break; + } + } + return ""; + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/ss/examples/html/XSSFHtmlHelper.java b/poi-examples/src/main/java/poi/ss/examples/html/XSSFHtmlHelper.java new file mode 100644 index 0000000000..0fe76d17be --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/html/XSSFHtmlHelper.java @@ -0,0 +1,68 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.ss.examples.html; + +import java.util.Formatter; +import java.util.Map; + +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFColor; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * Implementation of {@link HtmlHelper} for XSSF files. + * + * @author Ken Arnold, Industrious Media LLC + */ +public class XSSFHtmlHelper implements HtmlHelper { + private final XSSFWorkbook wb; + + private static final Map colors = HSSFColor.getIndexHash(); + + public XSSFHtmlHelper(XSSFWorkbook wb) { + this.wb = wb; + } + + public void colorStyles(CellStyle style, Formatter out) { + XSSFCellStyle cs = (XSSFCellStyle) style; + styleColor(out, "background-color", cs.getFillForegroundXSSFColor()); + styleColor(out, "text-color", cs.getFont().getXSSFColor()); + } + + private void styleColor(Formatter out, String attr, XSSFColor color) { + if (color == null || color.isAuto()) + return; + + byte[] rgb = color.getRgb(); + if (rgb == null) { + return; + } + + // This is done twice -- rgba is new with CSS 3, and browser that don't + // support it will ignore the rgba specification and stick with the + // solid color, which is declared first + out.format(" %s: #%02x%02x%02x;%n", attr, rgb[0], rgb[1], rgb[2]); + byte[] argb = color.getARgb(); + if (argb == null) { + return; + } + out.format(" %s: rgba(0x%02x, 0x%02x, 0x%02x, 0x%02x);%n", attr, + argb[3], argb[0], argb[1], argb[2]); + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/ss/examples/html/excelStyle.css b/poi-examples/src/main/java/poi/ss/examples/html/excelStyle.css new file mode 100644 index 0000000000..1083b637a3 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/html/excelStyle.css @@ -0,0 +1,72 @@ +/* + ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ==================================================================== + */ +/* + * This is the default style sheet for html generated by ToHtml + * + * @author Ken Arnold, Industrious Media LLC + */ +.excelDefaults { + background-color: white; + color: black; + text-decoration: none; + direction: ltr; + text-transform: none; + text-indent: 0; + letter-spacing: 0; + word-spacing: 0; + white-space: normal; + unicode-bidi: normal; + vertical-align: 0; + background-image: none; + text-shadow: none; + list-style-image: none; + list-style-type: none; + padding: 0; + margin: 0; + border-collapse: collapse; + white-space: pre; + vertical-align: bottom; + font-style: normal; + font-family: sans-serif; + font-variant: normal; + font-weight: normal; + font-size: 10pt; + text-align: right; +} + +.excelDefaults td { + padding: 1px 5px; + border: 1px solid silver; +} + +.excelDefaults .colHeader { + background-color: silver; + font-weight: bold; + border: 1px solid black; + text-align: center; + padding: 1px 5px; +} + +.excelDefaults .rowHeader { + background-color: silver; + font-weight: bold; + border: 1px solid black; + text-align: right; + padding: 1px 5px; +} diff --git a/poi-examples/src/main/java/poi/ss/examples/html/package.html b/poi-examples/src/main/java/poi/ss/examples/html/package.html new file mode 100644 index 0000000000..1c8e6af5c4 --- /dev/null +++ b/poi-examples/src/main/java/poi/ss/examples/html/package.html @@ -0,0 +1,27 @@ + + + + + + +This package contains an example that uses POI to convert a workbook into +an HTML representation of the data. It can use both XSSF and HSSF workbooks. + + diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/DataExtraction.java b/poi-examples/src/main/java/poi/xslf/usermodel/DataExtraction.java new file mode 100644 index 0000000000..b7e08fc6f1 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/DataExtraction.java @@ -0,0 +1,94 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import org.apache.poi.openxml4j.opc.PackagePart; + +import java.awt.*; +import java.awt.geom.Rectangle2D; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.List; + +/** + * Demonstrates how you can extract data from a .pptx file + * + * @author Yegor Kozlov + */ +public final class DataExtraction { + + public static void main(String args[]) throws Exception { + + if (args.length == 0) { + System.out.println("Input file is required"); + return; + } + + FileInputStream is = new FileInputStream(args[0]); + XMLSlideShow ppt = new XMLSlideShow(is); + is.close(); + + // Get the document's embedded files. + List embeds = ppt.getAllEmbedds(); + for (PackagePart p : embeds) { + String type = p.getContentType(); + String name = p.getPartName().getName(); //typically file name + + InputStream pIs = p.getInputStream(); + // make sense of the part data + pIs.close(); + + } + + // Get the document's embedded files. + List images = ppt.getAllPictures(); + for (XSLFPictureData data : images) { + PackagePart p = data.getPackagePart(); + + String type = p.getContentType(); + String name = data.getFileName(); + + InputStream pIs = p.getInputStream(); + // make sense of the image data + pIs.close(); + + + + } + + Dimension pageSize = ppt.getPageSize(); // size of the canvas in points + for(XSLFSlide slide : ppt.getSlides()) { + for(XSLFShape shape : slide){ + Rectangle2D anchor = shape.getAnchor(); // position on the canvas + if(shape instanceof XSLFTextShape) { + XSLFTextShape txShape = (XSLFTextShape)shape; + System.out.println(txShape.getText()); + } else if (shape instanceof XSLFPictureShape){ + XSLFPictureShape pShape = (XSLFPictureShape)shape; + XSLFPictureData pData = pShape.getPictureData(); + System.out.println(pData.getFileName()); + } else { + System.out.println("Process me: " + shape.getClass()); + } + } + } + } + +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/MergePresentations.java b/poi-examples/src/main/java/poi/xslf/usermodel/MergePresentations.java new file mode 100644 index 0000000000..994f94c259 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/MergePresentations.java @@ -0,0 +1,50 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import java.io.FileInputStream; +import java.io.FileOutputStream; + +/** + * Merge multiple pptx presentations together + * + * @author Yegor Kozlov + */ +public final class MergePresentations { + + public static void main(String args[]) throws Exception { + XMLSlideShow ppt = new XMLSlideShow(); + + for(String arg : args){ + FileInputStream is = new FileInputStream(arg); + XMLSlideShow src = new XMLSlideShow(is); + is.close(); + + for(XSLFSlide srcSlide : src.getSlides()){ + ppt.createSlide().importContent(srcSlide); + } + } + + FileOutputStream out = new FileOutputStream("merged.pptx"); + ppt.write(out); + out.close(); + } + +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/PPTX2SVG.txt b/poi-examples/src/main/java/poi/xslf/usermodel/PPTX2SVG.txt new file mode 100644 index 0000000000..dbe089ac30 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/PPTX2SVG.txt @@ -0,0 +1,176 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import org.apache.batik.dom.svg.SVGDOMImplementation; +import org.apache.batik.svggen.SVGGraphics2D; +import org.apache.batik.transcoder.wmf.tosvg.WMFPainter; +import org.apache.batik.transcoder.wmf.tosvg.WMFRecordStore; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackagePart; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; + +import javax.imageio.ImageIO; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.io.DataInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; + +/** + * Convert each slide of a .pptx presentation into SVG + * + * @author Yegor Kozlov + */ +public class PPTX2SVG { + + static void usage() { + System.out.println("Usage: PPTX2SVG "); + } + + public static void main(String[] args) throws Exception { + if (args.length == 0) { + usage(); + return; + } + + String file = args[0]; + + System.out.println("Processing " + file); + + // read the .pptx file + XMLSlideShow ppt = new XMLSlideShow(OPCPackage.open(file)); + + Dimension pgsize = ppt.getPageSize(); + + // convert each slide into a .svg file + XSLFSlide[] slide = ppt.getSlides(); + for (int i = 0; i < slide.length; i++) { + // Create initial SVG DOM + DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation(); + Document doc = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null); + //Use Batik SVG Graphics2D driver + SVGGraphics2D graphics = new SVGGraphics2D(doc); + graphics.setRenderingHint(XSLFRenderingHint.IMAGE_RENDERER, new WMFImageRender()); + graphics.setSVGCanvasSize(pgsize); + + String title = slide[i].getTitle(); + System.out.println("Rendering slide " + (i + 1) + (title == null ? "" : ": " + title)); + + // draw stuff. All the heavy-lifting happens here + slide[i].draw(graphics); + + // save the result. + int sep = file.lastIndexOf("."); + String fname = file.substring(0, sep == -1 ? file.length() : sep) + "-" + (i + 1) + ".svg"; + OutputStreamWriter out = + new OutputStreamWriter(new FileOutputStream(fname), "UTF-8"); + DOMSource domSource = new DOMSource(graphics.getRoot()); + StreamResult streamResult = new StreamResult(out); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer serializer = tf.newTransformer(); + serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + serializer.setOutputProperty(OutputKeys.INDENT, "yes"); + serializer.transform(domSource, streamResult); + out.flush(); + out.close(); + } + System.out.println("Done"); + } + + /** + * Image renderer with support for .wmf images + */ + static class WMFImageRender extends XSLFImageRendener { + + /** + * Use Apache Batik to render WMF, + * delegate all other types of images to the javax.imageio framework + */ + @Override + public boolean drawImage(Graphics2D graphics, XSLFPictureData data, + Rectangle2D anchor) { + try { + // see what type of image we are + PackagePart part = data.getPackagePart(); + String contentType = part.getContentType(); + if (contentType.equals("image/x-wmf")) { + WMFRecordStore currentStore = new WMFRecordStore(); + currentStore.read(new DataInputStream(part.getInputStream())); + int wmfwidth = currentStore.getWidthPixels(); + float conv = (float) anchor.getWidth() / wmfwidth; + + // Build a painter for the RecordStore + WMFPainter painter = new WMFPainter(currentStore, + (int) anchor.getX(), (int) anchor.getY(), conv); + painter.paint(graphics); + } else { + BufferedImage img = ImageIO.read(data.getPackagePart().getInputStream()); + graphics.drawImage(img, + (int) anchor.getX(), (int) anchor.getY(), + (int) anchor.getWidth(), (int) anchor.getHeight(), null); + } + } catch (Exception e) { + return false; + } + return true; + } + + /** + * Convert data form the supplied package part into a BufferedImage. + * This method is used to create texture paint. + */ + @Override + public BufferedImage readImage(PackagePart packagePart) throws IOException { + String contentType = packagePart.getContentType(); + if (contentType.equals("image/x-wmf")) { + try { + WMFRecordStore currentStore = new WMFRecordStore(); + currentStore.read(new DataInputStream(packagePart.getInputStream())); + int wmfwidth = currentStore.getWidthPixels(); + int wmfheight = currentStore.getHeightPixels(); + + BufferedImage img = new BufferedImage(wmfwidth, wmfheight, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = img.createGraphics(); + + // Build a painter for the RecordStore + WMFPainter painter = new WMFPainter(currentStore, 0, 0, 1.0f); + painter.paint(graphics); + + return img; + } catch (IOException e) { + return null; + } + } else { + return ImageIO.read(packagePart.getInputStream()); + } + } + + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/PieChartDemo.java b/poi-examples/src/main/java/poi/xslf/usermodel/PieChartDemo.java new file mode 100644 index 0000000000..f6e6a847d6 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/PieChartDemo.java @@ -0,0 +1,152 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import org.apache.poi.POIXMLDocumentPart; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieChart; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieSer; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData; +import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.OutputStream; + +/** + * Build a pie chart from a template pptx + * + * @author Yegor Kozlov + */ +public class PieChartDemo { + private static void usage(){ + System.out.println("Usage: PieChartDemo "); + System.out.println(" pie-chart-template.pptx template with a pie chart"); + System.out.println(" pie-chart-data.txt the model to set. First line is chart title, " + + "then go pairs {axis-label value}"); + } + + public static void main(String[] args) throws Exception { + if(args.length < 2) { + usage(); + return; + } + + BufferedReader modelReader = new BufferedReader(new FileReader(args[1])); + + String chartTitle = modelReader.readLine(); // first line is chart title + + XMLSlideShow pptx = new XMLSlideShow(new FileInputStream(args[0])); + XSLFSlide slide = pptx.getSlides()[0]; + + // find chart in the slide + XSLFChart chart = null; + for(POIXMLDocumentPart part : slide.getRelations()){ + if(part instanceof XSLFChart){ + chart = (XSLFChart) part; + break; + } + } + + if(chart == null) throw new IllegalStateException("chart not found in the template"); + + // embedded Excel workbook that holds the chart data + POIXMLDocumentPart xlsPart = chart.getRelations().get(0); + XSSFWorkbook wb = new XSSFWorkbook(); + XSSFSheet sheet = wb.createSheet(); + + CTChart ctChart = chart.getCTChart(); + CTPlotArea plotArea = ctChart.getPlotArea(); + + CTPieChart pieChart = plotArea.getPieChartArray(0); + //Pie Chart Series + CTPieSer ser = pieChart.getSerArray(0); + + // Series Text + CTSerTx tx = ser.getTx(); + tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle); + sheet.createRow(0).createCell(1).setCellValue(chartTitle); + String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString(); + tx.getStrRef().setF(titleRef); + + + // Category Axis Data + CTAxDataSource cat = ser.getCat(); + CTStrData strData = cat.getStrRef().getStrCache(); + + // Values + CTNumDataSource val = ser.getVal(); + CTNumData numData = val.getNumRef().getNumCache(); + + strData.setPtArray(null); // unset old axis text + numData.setPtArray(null); // unset old values + + + // set model + int idx = 0; + int rownum = 1; + String ln; + while((ln = modelReader.readLine()) != null){ + String[] vals = ln.split("\\s+"); + CTNumVal numVal = numData.addNewPt(); + numVal.setIdx(idx); + numVal.setV(vals[1]); + + CTStrVal sVal = strData.addNewPt(); + sVal.setIdx(idx); + sVal.setV(vals[0]); + + idx++; + XSSFRow row = sheet.createRow(rownum++); + row.createCell(0).setCellValue(vals[0]); + row.createCell(1).setCellValue(Double.valueOf(vals[1])); + } + numData.getPtCount().setVal(idx); + strData.getPtCount().setVal(idx); + + String numDataRange = new CellRangeAddress(1, rownum-1, 1, 1).formatAsString(sheet.getSheetName(), true); + val.getNumRef().setF(numDataRange); + String axisDataRange = new CellRangeAddress(1, rownum-1, 0, 0).formatAsString(sheet.getSheetName(), true); + cat.getStrRef().setF(axisDataRange); + + // updated the embedded workbook with the data + OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream(); + wb.write(xlsOut); + xlsOut.close(); + + // save the result + FileOutputStream out = new FileOutputStream("pie-chart-demo-output.pptx"); + pptx.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial1.java b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial1.java new file mode 100644 index 0000000000..726013d82c --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial1.java @@ -0,0 +1,72 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Demonstrates how to create slides with predefined layout + * and fill the placeholder shapes + * + * @author Yegor Kozlov + */ +public class Tutorial1 { + + public static void main(String[] args) throws IOException{ + XMLSlideShow ppt = new XMLSlideShow(); + + // XSLFSlide#createSlide() with no arguments creates a blank slide + XSLFSlide blankSlide = ppt.createSlide(); + + + XSLFSlideMaster master = ppt.getSlideMasters()[0]; + + XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE); + XSLFSlide slide1 = ppt.createSlide(layout1) ; + XSLFTextShape[] ph1 = slide1.getPlaceholders(); + XSLFTextShape titlePlaceholder1 = ph1[0]; + titlePlaceholder1.setText("This is a title"); + XSLFTextShape subtitlePlaceholder1 = ph1[1]; + subtitlePlaceholder1.setText("this is a subtitle"); + + XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT); + XSLFSlide slide2 = ppt.createSlide(layout2) ; + XSLFTextShape[] ph2 = slide2.getPlaceholders(); + XSLFTextShape titlePlaceholder2 = ph2[0]; + titlePlaceholder2.setText("This is a title"); + XSLFTextShape bodyPlaceholder = ph2[1]; + // we are going to add text by paragraphs. Clear the default placehoder text before that + bodyPlaceholder.clearText(); + XSLFTextParagraph p1 = bodyPlaceholder.addNewTextParagraph(); + p1.setLevel(0); + p1.addNewTextRun().setText("Level1 text"); + XSLFTextParagraph p2 = bodyPlaceholder.addNewTextParagraph(); + p2.setLevel(1); + p2.addNewTextRun().setText("Level2 text"); + XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph(); + p3.setLevel(3); + p3.addNewTextRun().setText("Level3 text"); + + FileOutputStream out = new FileOutputStream("slides.pptx"); + ppt.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial2.java b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial2.java new file mode 100644 index 0000000000..373f01f33f --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial2.java @@ -0,0 +1,82 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import java.awt.*; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Basic paragraph and text formatting + * + * @author Yegor Kozlov + */ +public class Tutorial2 { + + public static void main(String[] args) throws IOException{ + XMLSlideShow ppt = new XMLSlideShow(); + + XSLFSlide slide1 = ppt.createSlide(); + XSLFTextBox shape1 = slide1.createTextBox(); + // initial height of the text box is 100 pt but + Rectangle anchor = new Rectangle(10, 100, 300, 100); + shape1.setAnchor(anchor); + + XSLFTextParagraph p1 = shape1.addNewTextParagraph(); + XSLFTextRun r1 = p1.addNewTextRun(); + r1.setText("Paragraph Formatting"); + r1.setFontSize(24); + r1.setFontColor(new Color(85, 142, 213)); + + XSLFTextParagraph p2 = shape1.addNewTextParagraph(); + // If spaceBefore >= 0, then space is a percentage of normal line height. + // If spaceBefore < 0, the absolute value of linespacing is the spacing in points + p2.setSpaceBefore(-20); // 20 pt from the previous paragraph + p2.setSpaceAfter(300); // 3 lines after the paragraph + XSLFTextRun r2 = p2.addNewTextRun(); + r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph."); + r2.setFontSize(16); + + XSLFTextParagraph p3 = shape1.addNewTextParagraph(); + + XSLFTextRun r3 = p3.addNewTextRun(); + r3.setText("Run Formatting"); + r3.setFontSize(24); + r3.setFontColor(new Color(85, 142, 213)); + + XSLFTextParagraph p4 = shape1.addNewTextParagraph(); + p4.setSpaceBefore(-20); // 20 pt from the previous paragraph + p4.setSpaceAfter(300); // 3 lines after the paragraph + XSLFTextRun r4 = p4.addNewTextRun(); + r4.setFontSize(16); + r4.setText( + "Run level formatting is the most granular property level and allows " + + "for the specifying of all low level text properties. The text run is " + + "what all paragraphs are derived from and thus specifying various " + + "properties per run will allow for a diversely formatted text paragraph."); + + // resize the shape to fit text + shape1.resizeToFitText(); + + FileOutputStream out = new FileOutputStream("text.pptx"); + ppt.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial3.java b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial3.java new file mode 100644 index 0000000000..a5e01387da --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial3.java @@ -0,0 +1,47 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import java.awt.*; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * How to set slide title + * + * @author Yegor Kozlov + */ +public class Tutorial3 { + + public static void main(String[] args) throws IOException{ + XMLSlideShow ppt = new XMLSlideShow(); + + XSLFSlide slide = ppt.createSlide(); + + XSLFTextShape titleShape = slide.createTextBox(); + titleShape.setPlaceholder(Placeholder.TITLE); + titleShape.setText("This is a slide title"); + titleShape.setAnchor(new Rectangle(50, 50, 400, 100)); + + FileOutputStream out = new FileOutputStream("title.pptx"); + ppt.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial4.java b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial4.java new file mode 100644 index 0000000000..ea4fba320c --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial4.java @@ -0,0 +1,89 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import java.awt.*; +import java.awt.geom.Rectangle2D; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * PPTX Tables + * + * @author Yegor Kozlov + */ +public class Tutorial4 { + + public static void main(String[] args) throws IOException{ + XMLSlideShow ppt = new XMLSlideShow(); + + // XSLFSlide#createSlide() with no arguments creates a blank slide + XSLFSlide slide = ppt.createSlide(); + + XSLFTable tbl = slide.createTable(); + tbl.setAnchor(new Rectangle2D.Double(50, 50, 450, 300)); + + int numColumns = 3; + int numRows = 5; + XSLFTableRow headerRow = tbl.addRow(); + headerRow.setHeight(50); + // header + for(int i = 0; i < numColumns; i++) { + XSLFTableCell th = headerRow.addCell(); + XSLFTextParagraph p = th.addNewTextParagraph(); + p.setTextAlign(TextAlign.CENTER); + XSLFTextRun r = p.addNewTextRun(); + r.setText("Header " + (i+1)); + r.setBold(true); + r.setFontColor(Color.white); + th.setFillColor(new Color(79, 129, 189)); + th.setBorderBottom(2); + th.setBorderBottomColor(Color.white); + + tbl.setColumnWidth(i, 150); // all columns are equally sized + } + + // rows + + for(int rownum = 0; rownum < numRows; rownum ++){ + XSLFTableRow tr = tbl.addRow(); + tr.setHeight(50); + // header + for(int i = 0; i < numColumns; i++) { + XSLFTableCell cell = tr.addCell(); + XSLFTextParagraph p = cell.addNewTextParagraph(); + XSLFTextRun r = p.addNewTextRun(); + + r.setText("Cell " + (i+1)); + if(rownum % 2 == 0) + cell.setFillColor(new Color(208, 216, 232)); + else + cell.setFillColor(new Color(233, 247, 244)); + + } + + } + + + FileOutputStream out = new FileOutputStream("table.pptx"); + ppt.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial5.java b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial5.java new file mode 100644 index 0000000000..607248a753 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial5.java @@ -0,0 +1,50 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import org.apache.poi.util.IOUtils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Images + * + * @author Yegor Kozlov + */ +public class Tutorial5 { + + public static void main(String[] args) throws IOException{ + XMLSlideShow ppt = new XMLSlideShow(); + + XSLFSlide slide = ppt.createSlide(); + File img = new File(System.getProperty("POI.testdata.path"), "slideshow/clock.jpg"); + byte[] data = IOUtils.toByteArray(new FileInputStream(img)); + int pictureIndex = ppt.addPicture(data, XSLFPictureData.PICTURE_TYPE_PNG); + + XSLFPictureShape shape = slide.createPicture(pictureIndex); + + FileOutputStream out = new FileOutputStream("images.pptx"); + ppt.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial6.java b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial6.java new file mode 100644 index 0000000000..fc278cbe90 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial6.java @@ -0,0 +1,59 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import java.awt.*; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Hyperlinks + * + * @author Yegor Kozlov + */ +public class Tutorial6 { + + public static void main(String[] args) throws IOException{ + XMLSlideShow ppt = new XMLSlideShow(); + + XSLFSlide slide1 = ppt.createSlide(); + XSLFSlide slide2 = ppt.createSlide(); + + XSLFTextBox shape1 = slide1.createTextBox(); + shape1.setAnchor(new Rectangle(50, 50, 200, 50)); + XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun(); + XSLFHyperlink link1 = r1.createHyperlink(); + r1.setText("http://poi.apache.org"); // visible text + link1.setAddress("http://poi.apache.org"); // link address + + XSLFTextBox shape2 = slide1.createTextBox(); + shape2.setAnchor(new Rectangle(300, 50, 200, 50)); + XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun(); + XSLFHyperlink link2 = r2.createHyperlink(); + r2.setText("Go to the second slide"); // visible text + link2.setAddress(slide2); // link address + + + + FileOutputStream out = new FileOutputStream("hyperlinks.pptx"); + ppt.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial7.java b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial7.java new file mode 100644 index 0000000000..a80f23cad7 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/Tutorial7.java @@ -0,0 +1,85 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel; + +import java.awt.*; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Bullets and numbering + * + * @author Yegor Kozlov + */ +public class Tutorial7 { + + public static void main(String[] args) throws IOException{ + XMLSlideShow ppt = new XMLSlideShow(); + + XSLFSlide slide = ppt.createSlide(); + XSLFTextBox shape = slide.createTextBox(); + shape.setAnchor(new Rectangle(50, 50, 400, 200)); + + XSLFTextParagraph p1 = shape.addNewTextParagraph(); + p1.setLevel(0); + p1.setBullet(true); + XSLFTextRun r1 = p1.addNewTextRun(); + r1.setText("Bullet1"); + + XSLFTextParagraph p2 = shape.addNewTextParagraph(); + // indentation before text + p2.setLeftMargin(60); + // the bullet is set 40 pt before the text + p2.setIndent(-40); + p2.setBullet(true); + // customize bullets + p2.setBulletFontColor(Color.red); + p2.setBulletFont("Wingdings"); + p2.setBulletCharacter("\u0075"); + p2.setLevel(1); + XSLFTextRun r2 = p2.addNewTextRun(); + r2.setText("Bullet2"); + + // the next three paragraphs form an auto-numbered list + XSLFTextParagraph p3 = shape.addNewTextParagraph(); + p3.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 1); + p3.setLevel(2); + XSLFTextRun r3 = p3.addNewTextRun(); + r3.setText("Numbered List Item - 1"); + + XSLFTextParagraph p4 = shape.addNewTextParagraph(); + p4.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 2); + p4.setLevel(2); + XSLFTextRun r4 = p4.addNewTextRun(); + r4.setText("Numbered List Item - 2"); + + XSLFTextParagraph p5 = shape.addNewTextParagraph(); + p5.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 3); + p5.setLevel(2); + XSLFTextRun r5 = p5.addNewTextRun(); + r5.setText("Numbered List Item - 3"); + + shape.resizeToFitText(); + + FileOutputStream out = new FileOutputStream("list.pptx"); + ppt.write(out); + out.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/pie-chart-data.txt b/poi-examples/src/main/java/poi/xslf/usermodel/pie-chart-data.txt new file mode 100644 index 0000000000..40b6959c2c --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/pie-chart-data.txt @@ -0,0 +1,4 @@ +My Chart +First 1.0 +Second 3.0 +Third 4.0 \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/pie-chart-template.pptx b/poi-examples/src/main/java/poi/xslf/usermodel/pie-chart-template.pptx new file mode 100644 index 0000000000..33d28e154c Binary files /dev/null and b/poi-examples/src/main/java/poi/xslf/usermodel/pie-chart-template.pptx differ diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/tutorial/Step1.java b/poi-examples/src/main/java/poi/xslf/usermodel/tutorial/Step1.java new file mode 100644 index 0000000000..a83a17e4b8 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/tutorial/Step1.java @@ -0,0 +1,68 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel.tutorial; + +import org.apache.poi.xslf.usermodel.XMLSlideShow; +import org.apache.poi.xslf.usermodel.XSLFShape; +import org.apache.poi.xslf.usermodel.XSLFSlide; +import org.apache.poi.xslf.usermodel.XSLFTextParagraph; +import org.apache.poi.xslf.usermodel.XSLFTextRun; +import org.apache.poi.xslf.usermodel.XSLFTextShape; + +import java.io.FileInputStream; + +/** + * Reading a .pptx presentation and printing basic shape properties + * + * @author Yegor Kozlov + */ +public class Step1 { + + public static void main(String[] args) throws Exception { + if(args.length == 0) { + System.out.println("Input file is required"); + return; + } + + XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(args[0])); + + for(XSLFSlide slide : ppt.getSlides()){ + System.out.println("Title: " + slide.getTitle()); + + for(XSLFShape shape : slide.getShapes()){ + if(shape instanceof XSLFTextShape) { + XSLFTextShape tsh = (XSLFTextShape)shape; + for(XSLFTextParagraph p : tsh){ + System.out.println("Paragraph level: " + p.getLevel()); + for(XSLFTextRun r : p){ + System.out.println(r.getText()); + System.out.println(" bold: " + r.isBold()); + System.out.println(" italic: " + r.isItalic()); + System.out.println(" underline: " + r.isUnderline()); + System.out.println(" font.family: " + r.getFontFamily()); + System.out.println(" font.size: " + r.getFontSize()); + System.out.println(" font.color: " + r.getFontColor()); + } + } + } + } + } + } +} diff --git a/poi-examples/src/main/java/poi/xslf/usermodel/tutorial/Step2.java b/poi-examples/src/main/java/poi/xslf/usermodel/tutorial/Step2.java new file mode 100644 index 0000000000..16b155d3f2 --- /dev/null +++ b/poi-examples/src/main/java/poi/xslf/usermodel/tutorial/Step2.java @@ -0,0 +1,80 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xslf.usermodel.tutorial; + +import org.apache.poi.xslf.usermodel.SlideLayout; +import org.apache.poi.xslf.usermodel.XMLSlideShow; +import org.apache.poi.xslf.usermodel.XSLFSlide; +import org.apache.poi.xslf.usermodel.XSLFSlideLayout; +import org.apache.poi.xslf.usermodel.XSLFSlideMaster; +import org.apache.poi.xslf.usermodel.XSLFTextShape; + +import java.io.FileOutputStream; + +/** + * Create slides from pre-defined slide layouts + * + * @author Yegor Kozlov + */ +public class Step2 { + public static void main(String[] args) throws Exception{ + XMLSlideShow ppt = new XMLSlideShow(); + + + // first see what slide layouts are available by default + System.out.println("Available slide layouts:"); + for(XSLFSlideMaster master : ppt.getSlideMasters()){ + for(XSLFSlideLayout layout : master.getSlideLayouts()){ + System.out.println(layout.getType()); + } + } + + // blank slide + XSLFSlide blankSlide = ppt.createSlide(); + + XSLFSlideMaster defaultMaster = ppt.getSlideMasters()[0]; + + // title slide + XSLFSlideLayout titleLayout = defaultMaster.getLayout(SlideLayout.TITLE); + XSLFSlide slide1 = ppt.createSlide(titleLayout); + XSLFTextShape title1 = slide1.getPlaceholder(0); + title1.setText("First Title"); + + // title and content + XSLFSlideLayout titleBodyLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); + XSLFSlide slide2 = ppt.createSlide(titleBodyLayout); + + XSLFTextShape title2 = slide2.getPlaceholder(0); + title2.setText("Second Title"); + + XSLFTextShape body2 = slide2.getPlaceholder(1); + body2.clearText(); // unset any existing text + body2.addNewTextParagraph().addNewTextRun().setText("First paragraph"); + body2.addNewTextParagraph().addNewTextRun().setText("Second paragraph"); + body2.addNewTextParagraph().addNewTextRun().setText("Third paragraph"); + + + + FileOutputStream out = new FileOutputStream("step2.pptx"); + ppt.write(out); + out.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/xssf/eventusermodel/XLSX2CSV.java b/poi-examples/src/main/java/poi/xssf/eventusermodel/XLSX2CSV.java new file mode 100644 index 0000000000..892c3bb2bc --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/eventusermodel/XLSX2CSV.java @@ -0,0 +1,424 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.eventusermodel; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.poi.openxml4j.exceptions.OpenXML4JException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackageAccess; +import org.apache.poi.ss.usermodel.BuiltinFormats; +import org.apache.poi.ss.usermodel.DataFormatter; +import org.apache.poi.xssf.model.StylesTable; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFRichTextString; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + +/** + * A rudimentary XLSX -> CSV processor modeled on the + * POI sample program XLS2CSVmra by Nick Burch from the + * package org.apache.poi.hssf.eventusermodel.examples. + * Unlike the HSSF version, this one completely ignores + * missing rows. + *

    + * Data sheets are read using a SAX parser to keep the + * memory footprint relatively small, so this should be + * able to read enormous workbooks. The styles table and + * the shared-string table must be kept in memory. The + * standard POI styles table class is used, but a custom + * (read-only) class is used for the shared string table + * because the standard POI SharedStringsTable grows very + * quickly with the number of unique strings. + *

    + * Thanks to Eric Smith for a patch that fixes a problem + * triggered by cells with multiple "t" elements, which is + * how Excel represents different formats (e.g., one word + * plain and one word bold). + * + * @author Chris Lott + */ +public class XLSX2CSV { + + /** + * The type of the data value is indicated by an attribute on the cell. + * The value is usually in a "v" element within the cell. + */ + enum xssfDataType { + BOOL, + ERROR, + FORMULA, + INLINESTR, + SSTINDEX, + NUMBER, + } + + + /** + * Derived from http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api + *

    + * Also see Standard ECMA-376, 1st edition, part 4, pages 1928ff, at + * http://www.ecma-international.org/publications/standards/Ecma-376.htm + *

    + * A web-friendly version is http://openiso.org/Ecma/376/Part4 + */ + class MyXSSFSheetHandler extends DefaultHandler { + + /** + * Table with styles + */ + private StylesTable stylesTable; + + /** + * Table with unique strings + */ + private ReadOnlySharedStringsTable sharedStringsTable; + + /** + * Destination for data + */ + private final PrintStream output; + + /** + * Number of columns to read starting with leftmost + */ + private final int minColumnCount; + + // Set when V start element is seen + private boolean vIsOpen; + + // Set when cell start element is seen; + // used when cell close element is seen. + private xssfDataType nextDataType; + + // Used to format numeric cell values. + private short formatIndex; + private String formatString; + private final DataFormatter formatter; + + private int thisColumn = -1; + // The last column printed to the output stream + private int lastColumnNumber = -1; + + // Gathers characters as they are seen. + private StringBuffer value; + + /** + * Accepts objects needed while parsing. + * + * @param styles Table of styles + * @param strings Table of shared strings + * @param cols Minimum number of columns to show + * @param target Sink for output + */ + public MyXSSFSheetHandler( + StylesTable styles, + ReadOnlySharedStringsTable strings, + int cols, + PrintStream target) { + this.stylesTable = styles; + this.sharedStringsTable = strings; + this.minColumnCount = cols; + this.output = target; + this.value = new StringBuffer(); + this.nextDataType = xssfDataType.NUMBER; + this.formatter = new DataFormatter(); + } + + /* + * (non-Javadoc) + * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + public void startElement(String uri, String localName, String name, + Attributes attributes) throws SAXException { + + if ("inlineStr".equals(name) || "v".equals(name)) { + vIsOpen = true; + // Clear contents cache + value.setLength(0); + } + // c => cell + else if ("c".equals(name)) { + // Get the cell reference + String r = attributes.getValue("r"); + int firstDigit = -1; + for (int c = 0; c < r.length(); ++c) { + if (Character.isDigit(r.charAt(c))) { + firstDigit = c; + break; + } + } + thisColumn = nameToColumn(r.substring(0, firstDigit)); + + // Set up defaults. + this.nextDataType = xssfDataType.NUMBER; + this.formatIndex = -1; + this.formatString = null; + String cellType = attributes.getValue("t"); + String cellStyleStr = attributes.getValue("s"); + if ("b".equals(cellType)) + nextDataType = xssfDataType.BOOL; + else if ("e".equals(cellType)) + nextDataType = xssfDataType.ERROR; + else if ("inlineStr".equals(cellType)) + nextDataType = xssfDataType.INLINESTR; + else if ("s".equals(cellType)) + nextDataType = xssfDataType.SSTINDEX; + else if ("str".equals(cellType)) + nextDataType = xssfDataType.FORMULA; + else if (cellStyleStr != null) { + // It's a number, but almost certainly one + // with a special style or format + int styleIndex = Integer.parseInt(cellStyleStr); + XSSFCellStyle style = stylesTable.getStyleAt(styleIndex); + this.formatIndex = style.getDataFormat(); + this.formatString = style.getDataFormatString(); + if (this.formatString == null) + this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex); + } + } + + } + + /* + * (non-Javadoc) + * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) + */ + public void endElement(String uri, String localName, String name) + throws SAXException { + + String thisStr = null; + + // v => contents of a cell + if ("v".equals(name)) { + // Process the value contents as required. + // Do now, as characters() may be called more than once + switch (nextDataType) { + + case BOOL: + char first = value.charAt(0); + thisStr = first == '0' ? "FALSE" : "TRUE"; + break; + + case ERROR: + thisStr = "\"ERROR:" + value.toString() + '"'; + break; + + case FORMULA: + // A formula could result in a string value, + // so always add double-quote characters. + thisStr = '"' + value.toString() + '"'; + break; + + case INLINESTR: + // TODO: have seen an example of this, so it's untested. + XSSFRichTextString rtsi = new XSSFRichTextString(value.toString()); + thisStr = '"' + rtsi.toString() + '"'; + break; + + case SSTINDEX: + String sstIndex = value.toString(); + try { + int idx = Integer.parseInt(sstIndex); + XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); + thisStr = '"' + rtss.toString() + '"'; + } + catch (NumberFormatException ex) { + output.println("Failed to parse SST index '" + sstIndex + "': " + ex.toString()); + } + break; + + case NUMBER: + String n = value.toString(); + if (this.formatString != null) + thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString); + else + thisStr = n; + break; + + default: + thisStr = "(TODO: Unexpected type: " + nextDataType + ")"; + break; + } + + // Output after we've seen the string contents + // Emit commas for any fields that were missing on this row + if (lastColumnNumber == -1) { + lastColumnNumber = 0; + } + for (int i = lastColumnNumber; i < thisColumn; ++i) + output.print(','); + + // Might be the empty string. + output.print(thisStr); + + // Update column + if (thisColumn > -1) + lastColumnNumber = thisColumn; + + } else if ("row".equals(name)) { + + // Print out any missing commas if needed + if (minColumns > 0) { + // Columns are 0 based + if (lastColumnNumber == -1) { + lastColumnNumber = 0; + } + for (int i = lastColumnNumber; i < (this.minColumnCount); i++) { + output.print(','); + } + } + + // We're onto a new row + output.println(); + lastColumnNumber = -1; + } + + } + + /** + * Captures characters only if a suitable element is open. + * Originally was just "v"; extended for inlineStr also. + */ + public void characters(char[] ch, int start, int length) + throws SAXException { + if (vIsOpen) + value.append(ch, start, length); + } + + /** + * Converts an Excel column name like "C" to a zero-based index. + * + * @param name + * @return Index corresponding to the specified name + */ + private int nameToColumn(String name) { + int column = -1; + for (int i = 0; i < name.length(); ++i) { + int c = name.charAt(i); + column = (column + 1) * 26 + c - 'A'; + } + return column; + } + + } + + /////////////////////////////////////// + + private OPCPackage xlsxPackage; + private int minColumns; + private PrintStream output; + + /** + * Creates a new XLSX -> CSV converter + * + * @param pkg The XLSX package to process + * @param output The PrintStream to output the CSV to + * @param minColumns The minimum number of columns to output, or -1 for no minimum + */ + public XLSX2CSV(OPCPackage pkg, PrintStream output, int minColumns) { + this.xlsxPackage = pkg; + this.output = output; + this.minColumns = minColumns; + } + + /** + * Parses and shows the content of one sheet + * using the specified styles and shared-strings tables. + * + * @param styles + * @param strings + * @param sheetInputStream + */ + public void processSheet( + StylesTable styles, + ReadOnlySharedStringsTable strings, + InputStream sheetInputStream) + throws IOException, ParserConfigurationException, SAXException { + + InputSource sheetSource = new InputSource(sheetInputStream); + SAXParserFactory saxFactory = SAXParserFactory.newInstance(); + SAXParser saxParser = saxFactory.newSAXParser(); + XMLReader sheetParser = saxParser.getXMLReader(); + ContentHandler handler = new MyXSSFSheetHandler(styles, strings, this.minColumns, this.output); + sheetParser.setContentHandler(handler); + sheetParser.parse(sheetSource); + } + + /** + * Initiates the processing of the XLS workbook file to CSV. + * + * @throws IOException + * @throws OpenXML4JException + * @throws ParserConfigurationException + * @throws SAXException + */ + public void process() + throws IOException, OpenXML4JException, ParserConfigurationException, SAXException { + + ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage); + XSSFReader xssfReader = new XSSFReader(this.xlsxPackage); + StylesTable styles = xssfReader.getStylesTable(); + XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); + int index = 0; + while (iter.hasNext()) { + InputStream stream = iter.next(); + String sheetName = iter.getSheetName(); + this.output.println(); + this.output.println(sheetName + " [index=" + index + "]:"); + processSheet(styles, strings, stream); + stream.close(); + ++index; + } + } + + public static void main(String[] args) throws Exception { + if (args.length < 1) { + System.err.println("Use:"); + System.err.println(" XLSX2CSV [min columns]"); + return; + } + + File xlsxFile = new File(args[0]); + if (!xlsxFile.exists()) { + System.err.println("Not found or not a file: " + xlsxFile.getPath()); + return; + } + + int minColumns = -1; + if (args.length >= 2) + minColumns = Integer.parseInt(args[1]); + + // The package open is instantaneous, as it should be. + OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ); + XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns); + xlsx2csv.process(); + } + +} diff --git a/poi-examples/src/main/java/poi/xssf/eventusermodel/examples/FromHowTo.java b/poi-examples/src/main/java/poi/xssf/eventusermodel/examples/FromHowTo.java new file mode 100644 index 0000000000..fc6604c649 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/eventusermodel/examples/FromHowTo.java @@ -0,0 +1,138 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.eventusermodel.examples; + +import java.io.InputStream; +import java.util.Iterator; + +import org.apache.poi.xssf.eventusermodel.XSSFReader; +import org.apache.poi.xssf.model.SharedStringsTable; +import org.apache.poi.xssf.usermodel.XSSFRichTextString; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; +import org.xml.sax.helpers.XMLReaderFactory; + +/** + * XSSF and SAX (Event API) + */ +public class FromHowTo { + public void processOneSheet(String filename) throws Exception { + OPCPackage pkg = OPCPackage.open(filename); + XSSFReader r = new XSSFReader( pkg ); + SharedStringsTable sst = r.getSharedStringsTable(); + + XMLReader parser = fetchSheetParser(sst); + + // rId2 found by processing the Workbook + // Seems to either be rId# or rSheet# + InputStream sheet2 = r.getSheet("rId2"); + InputSource sheetSource = new InputSource(sheet2); + parser.parse(sheetSource); + sheet2.close(); + } + + public void processAllSheets(String filename) throws Exception { + OPCPackage pkg = OPCPackage.open(filename); + XSSFReader r = new XSSFReader( pkg ); + SharedStringsTable sst = r.getSharedStringsTable(); + + XMLReader parser = fetchSheetParser(sst); + + Iterator sheets = r.getSheetsData(); + while(sheets.hasNext()) { + System.out.println("Processing new sheet:\n"); + InputStream sheet = sheets.next(); + InputSource sheetSource = new InputSource(sheet); + parser.parse(sheetSource); + sheet.close(); + System.out.println(""); + } + } + + public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException { + XMLReader parser = + XMLReaderFactory.createXMLReader( + "org.apache.xerces.parsers.SAXParser" + ); + ContentHandler handler = new SheetHandler(sst); + parser.setContentHandler(handler); + return parser; + } + + /** + * See org.xml.sax.helpers.DefaultHandler javadocs + */ + private static class SheetHandler extends DefaultHandler { + private SharedStringsTable sst; + private String lastContents; + private boolean nextIsString; + + private SheetHandler(SharedStringsTable sst) { + this.sst = sst; + } + + public void startElement(String uri, String localName, String name, + Attributes attributes) throws SAXException { + // c => cell + if(name.equals("c")) { + // Print the cell reference + System.out.print(attributes.getValue("r") + " - "); + // Figure out if the value is an index in the SST + String cellType = attributes.getValue("t"); + if(cellType != null && cellType.equals("s")) { + nextIsString = true; + } else { + nextIsString = false; + } + } + // Clear contents cache + lastContents = ""; + } + + public void endElement(String uri, String localName, String name) + throws SAXException { + // Process the last contents as required. + // Do now, as characters() may be called more than once + if(nextIsString) { + int idx = Integer.parseInt(lastContents); + lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); + } + + // v => contents of a cell + // Output after we've seen the string contents + if(name.equals("v")) { + System.out.println(lastContents); + } + } + + public void characters(char[] ch, int start, int length) + throws SAXException { + lastContents += new String(ch, start, length); + } + } + + public static void main(String[] args) throws Exception { + FromHowTo howto = new FromHowTo(); + howto.processOneSheet(args[0]); + howto.processAllSheets(args[0]); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/streaming/examples/Outlining.java b/poi-examples/src/main/java/poi/xssf/streaming/examples/Outlining.java new file mode 100644 index 0000000000..03af09ddda --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/streaming/examples/Outlining.java @@ -0,0 +1,51 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.streaming.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; + +public class Outlining { + + public static void main(String[] args) throws Exception { + Outlining o = new Outlining(); + o.collapseRow(); + } + + private void collapseRow() throws Exception { + SXSSFWorkbook wb2 = new SXSSFWorkbook(100); + SXSSFSheet sheet2 = (SXSSFSheet) wb2.createSheet("new sheet"); + + int rowCount = 20; + for (int i = 0; i < rowCount; i++) { + sheet2.createRow(i); + } + + sheet2.groupRow(4, 9); + sheet2.groupRow(11, 19); + + sheet2.setRowGroupCollapsed(4, true); + + FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx"); + wb2.write(fileOut); + fileOut.close(); + wb2.dispose(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/AligningCells.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/AligningCells.java new file mode 100644 index 0000000000..6ed76081b1 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/AligningCells.java @@ -0,0 +1,129 @@ +/* ==================================================================== +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.*; +import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl; + +/** + * Shows how various alignment options work. + * + * Modified by Cristian Petrula, Romania on May 26, 2010 + * New method was added centerAcrossSelection to center a column content over + * one selection using ALIGN_CENTER_SELECTION + * To create this method example was change for XSSF only and the previous + * AligningCells.java example has been moved into the SS examples folder. + */ +public class AligningCells { + + public static void main(String[] args) throws IOException { + XSSFWorkbook wb = new XSSFWorkbook(); + + XSSFSheet sheet = wb.createSheet(); + XSSFRow row = sheet.createRow((short) 2); + row.setHeightInPoints(30); + for (int i = 0; i < 8; i++) { + //column width is set in units of 1/256th of a character width + sheet.setColumnWidth(i, 256 * 15); + } + + createCell(wb, row, (short) 0, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_BOTTOM); + createCell(wb, row, (short) 1, XSSFCellStyle.ALIGN_CENTER_SELECTION, XSSFCellStyle.VERTICAL_BOTTOM); + createCell(wb, row, (short) 2, XSSFCellStyle.ALIGN_FILL, XSSFCellStyle.VERTICAL_CENTER); + createCell(wb, row, (short) 3, XSSFCellStyle.ALIGN_GENERAL, XSSFCellStyle.VERTICAL_CENTER); + createCell(wb, row, (short) 4, XSSFCellStyle.ALIGN_JUSTIFY, XSSFCellStyle.VERTICAL_JUSTIFY); + createCell(wb, row, (short) 5, XSSFCellStyle.ALIGN_LEFT, XSSFCellStyle.VERTICAL_TOP); + createCell(wb, row, (short) 6, XSSFCellStyle.ALIGN_RIGHT, XSSFCellStyle.VERTICAL_TOP); + + //center text over B4, C4, D4 + row = sheet.createRow((short) 3); + centerAcrossSelection(wb, row, (short) 1, (short) 3, XSSFCellStyle.VERTICAL_CENTER); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("xssf-align.xlsx"); + wb.write(fileOut); + fileOut.close(); + } + + /** + * Creates a cell and aligns it a certain way. + * + * @param wb the workbook + * @param row the row to create the cell in + * @param column the column number to create the cell in + * @param halign the horizontal alignment for the cell. + */ + private static void createCell(XSSFWorkbook wb, XSSFRow row, short column, + short halign, short valign) { + XSSFCell cell = row.createCell(column); + cell.setCellValue(new XSSFRichTextString("Align It")); + CellStyle cellStyle = wb.createCellStyle(); + cellStyle.setAlignment(halign); + cellStyle.setVerticalAlignment(valign); + cell.setCellStyle(cellStyle); + } + + /** + * Center a text over multiple columns using ALIGN_CENTER_SELECTION + * + * @param wb the workbook + * @param row the row to create the cell in + * @param start_column the column number to create the cell in and where the selection starts + * @param end_column the column number where the selection ends + * @param valign the horizontal alignment for the cell. + * + * @author Cristian Petrula, Romania + */ + private static void centerAcrossSelection(XSSFWorkbook wb, XSSFRow row, + short start_column, short end_column, short valign) { + + // Create cell style with ALIGN_CENTER_SELECTION + XSSFCellStyle cellStyle = wb.createCellStyle(); + cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION); + cellStyle.setVerticalAlignment(valign); + + // Create cells over the selected area + for (int i = start_column; i <= end_column; i++) { + XSSFCell cell = row.createCell(i); + cell.setCellStyle(cellStyle); + } + + // Set value to the first cell + XSSFCell cell = row.getCell(start_column); + cell.setCellValue(new XSSFRichTextString("Align It")); + + // Make the selection + CTRowImpl ctRow = (CTRowImpl) row.getCTRow(); + List spanList = new ArrayList(); + + // Add object with format start_coll:end_coll. For example 1:3 will span from + // cell 1 to cell 3, where the column index starts with 0 + // + // You can add multiple spans for one row + Object span = start_column + ":" + end_column; + spanList.add(span); + + //add spns to the row + ctRow.setSpans(spanList); + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/BigGridDemo.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/BigGridDemo.java new file mode 100644 index 0000000000..00c5342746 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/BigGridDemo.java @@ -0,0 +1,269 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import java.io.*; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.usermodel.*; + +/** + * Demonstrates a workaround you can use to generate large workbooks and avoid OutOfMemory exception. + * + * The trick is as follows: + * 1. create a template workbook, create sheets and global objects such as cell styles, number formats, etc. + * 2. create an application that streams data in a text file + * 3. Substitute the sheet in the template with the generated data + * + *

    + * Since 3.8-beta3 POI provides a low-memory footprint SXSSF API which implementing the "BigGridDemo" strategy. + * XSSF is an API-compatible streaming extension of XSSF to be used when + * very large spreadsheets have to be produced, and heap space is limited. + * SXSSF achieves its low memory footprint by limiting access to the rows that + * are within a sliding window, while XSSF gives access to all rows in the + * document. Older rows that are no longer in the window become inaccessible, + * as they are written to the disk. + *

    + * See + * http://poi.apache.org/spreadsheet/how-to.html#sxssf. + + * + * @author Yegor Kozlov + */ +public class BigGridDemo { + private static final String XML_ENCODING = "UTF-8"; + + public static void main(String[] args) throws Exception { + + // Step 1. Create a template file. Setup sheets and workbook-level objects such as + // cell styles, number formats, etc. + + XSSFWorkbook wb = new XSSFWorkbook(); + XSSFSheet sheet = wb.createSheet("Big Grid"); + + Map styles = createStyles(wb); + //name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml + String sheetRef = sheet.getPackagePart().getPartName().getName(); + + //save the template + FileOutputStream os = new FileOutputStream("template.xlsx"); + wb.write(os); + os.close(); + + //Step 2. Generate XML file. + File tmp = File.createTempFile("sheet", ".xml"); + Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING); + generate(fw, styles); + fw.close(); + + //Step 3. Substitute the template entry with the generated data + FileOutputStream out = new FileOutputStream("big-grid.xlsx"); + substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out); + out.close(); + } + + /** + * Create a library of cell styles. + */ + private static Map createStyles(XSSFWorkbook wb){ + Map styles = new HashMap(); + XSSFDataFormat fmt = wb.createDataFormat(); + + XSSFCellStyle style1 = wb.createCellStyle(); + style1.setAlignment(XSSFCellStyle.ALIGN_RIGHT); + style1.setDataFormat(fmt.getFormat("0.0%")); + styles.put("percent", style1); + + XSSFCellStyle style2 = wb.createCellStyle(); + style2.setAlignment(XSSFCellStyle.ALIGN_CENTER); + style2.setDataFormat(fmt.getFormat("0.0X")); + styles.put("coeff", style2); + + XSSFCellStyle style3 = wb.createCellStyle(); + style3.setAlignment(XSSFCellStyle.ALIGN_RIGHT); + style3.setDataFormat(fmt.getFormat("$#,##0.00")); + styles.put("currency", style3); + + XSSFCellStyle style4 = wb.createCellStyle(); + style4.setAlignment(XSSFCellStyle.ALIGN_RIGHT); + style4.setDataFormat(fmt.getFormat("mmm dd")); + styles.put("date", style4); + + XSSFCellStyle style5 = wb.createCellStyle(); + XSSFFont headerFont = wb.createFont(); + headerFont.setBold(true); + style5.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + style5.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); + style5.setFont(headerFont); + styles.put("header", style5); + + return styles; + } + + private static void generate(Writer out, Map styles) throws Exception { + + Random rnd = new Random(); + Calendar calendar = Calendar.getInstance(); + + SpreadsheetWriter sw = new SpreadsheetWriter(out); + sw.beginSheet(); + + //insert header row + sw.insertRow(0); + int styleIndex = styles.get("header").getIndex(); + sw.createCell(0, "Title", styleIndex); + sw.createCell(1, "% Change", styleIndex); + sw.createCell(2, "Ratio", styleIndex); + sw.createCell(3, "Expenses", styleIndex); + sw.createCell(4, "Date", styleIndex); + + sw.endRow(); + + //write data rows + for (int rownum = 1; rownum < 100000; rownum++) { + sw.insertRow(rownum); + + sw.createCell(0, "Hello, " + rownum + "!"); + sw.createCell(1, (double)rnd.nextInt(100)/100, styles.get("percent").getIndex()); + sw.createCell(2, (double)rnd.nextInt(10)/10, styles.get("coeff").getIndex()); + sw.createCell(3, rnd.nextInt(10000), styles.get("currency").getIndex()); + sw.createCell(4, calendar, styles.get("date").getIndex()); + + sw.endRow(); + + calendar.roll(Calendar.DAY_OF_YEAR, 1); + } + sw.endSheet(); + } + + /** + * + * @param zipfile the template file + * @param tmpfile the XML file with the sheet data + * @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml + * @param out the stream to write the result to + */ + private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException { + ZipFile zip = new ZipFile(zipfile); + + ZipOutputStream zos = new ZipOutputStream(out); + + @SuppressWarnings("unchecked") + Enumeration en = (Enumeration) zip.entries(); + while (en.hasMoreElements()) { + ZipEntry ze = en.nextElement(); + if(!ze.getName().equals(entry)){ + zos.putNextEntry(new ZipEntry(ze.getName())); + InputStream is = zip.getInputStream(ze); + copyStream(is, zos); + is.close(); + } + } + zos.putNextEntry(new ZipEntry(entry)); + InputStream is = new FileInputStream(tmpfile); + copyStream(is, zos); + is.close(); + + zos.close(); + } + + private static void copyStream(InputStream in, OutputStream out) throws IOException { + byte[] chunk = new byte[1024]; + int count; + while ((count = in.read(chunk)) >=0 ) { + out.write(chunk,0,count); + } + } + + /** + * Writes spreadsheet data in a Writer. + * (YK: in future it may evolve in a full-featured API for streaming data in Excel) + */ + public static class SpreadsheetWriter { + private final Writer _out; + private int _rownum; + + public SpreadsheetWriter(Writer out){ + _out = out; + } + + public void beginSheet() throws IOException { + _out.write("" + + "" ); + _out.write("\n"); + } + + public void endSheet() throws IOException { + _out.write(""); + _out.write(""); + } + + /** + * Insert a new row + * + * @param rownum 0-based row number + */ + public void insertRow(int rownum) throws IOException { + _out.write("\n"); + this._rownum = rownum; + } + + /** + * Insert row end marker + */ + public void endRow() throws IOException { + _out.write("\n"); + } + + public void createCell(int columnIndex, String value, int styleIndex) throws IOException { + String ref = new CellReference(_rownum, columnIndex).formatAsString(); + _out.write(""); + _out.write(""+value+""); + _out.write(""); + } + + public void createCell(int columnIndex, String value) throws IOException { + createCell(columnIndex, value, -1); + } + + public void createCell(int columnIndex, double value, int styleIndex) throws IOException { + String ref = new CellReference(_rownum, columnIndex).formatAsString(); + _out.write(""); + _out.write(""+value+""); + _out.write(""); + } + + public void createCell(int columnIndex, double value) throws IOException { + createCell(columnIndex, value, -1); + } + + public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException { + createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex); + } + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/CalendarDemo.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CalendarDemo.java new file mode 100644 index 0000000000..d8baaceda5 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CalendarDemo.java @@ -0,0 +1,228 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.xssf.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.usermodel.*; + +import java.io.FileOutputStream; +import java.util.Calendar; +import java.util.Map; +import java.util.HashMap; + +/** + * A monthly calendar created using Apache POI. Each month is on a separate sheet. + * This is a version of org.apache.poi.ss.examples.CalendarDemo that demonstrates + * some XSSF features not avaiable when using common HSSF-XSSF interfaces. + * + *
    + * Usage:
    + * CalendarDemo 
    + * 
    + * + * @author Yegor Kozlov + */ +public class CalendarDemo { + + private static final String[] days = { + "Sunday", "Monday", "Tuesday", + "Wednesday", "Thursday", "Friday", "Saturday"}; + + private static final String[] months = { + "January", "February", "March","April", "May", "June","July", "August", + "September","October", "November", "December"}; + + public static void main(String[] args) throws Exception { + + Calendar calendar = Calendar.getInstance(); + if(args.length > 0) calendar.set(Calendar.YEAR, Integer.parseInt(args[0])); + + int year = calendar.get(Calendar.YEAR); + + XSSFWorkbook wb = new XSSFWorkbook(); + Map styles = createStyles(wb); + + for (int month = 0; month < 12; month++) { + calendar.set(Calendar.MONTH, month); + calendar.set(Calendar.DAY_OF_MONTH, 1); + //create a sheet for each month + XSSFSheet sheet = wb.createSheet(months[month]); + + //turn off gridlines + sheet.setDisplayGridlines(false); + sheet.setPrintGridlines(false); + XSSFPrintSetup printSetup = sheet.getPrintSetup(); + printSetup.setOrientation(PrintOrientation.LANDSCAPE); + sheet.setFitToPage(true); + sheet.setHorizontallyCenter(true); + + //the header row: centered text in 48pt font + XSSFRow headerRow = sheet.createRow(0); + headerRow.setHeightInPoints(80); + XSSFCell titleCell = headerRow.createCell(0); + titleCell.setCellValue(months[month] + " " + year); + titleCell.setCellStyle(styles.get("title")); + sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1")); + + //header with month titles + XSSFRow monthRow = sheet.createRow(1); + for (int i = 0; i < days.length; i++) { + //for compatibility with HSSF we have to set column width in units of 1/256th of a character width + sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide + sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide + sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1)); + XSSFCell monthCell = monthRow.createCell(i*2); + monthCell.setCellValue(days[i]); + monthCell.setCellStyle(styles.get("month")); + } + + int cnt = 1, day=1; + int rownum = 2; + for (int j = 0; j < 6; j++) { + XSSFRow row = sheet.createRow(rownum++); + row.setHeightInPoints(100); + for (int i = 0; i < days.length; i++) { + XSSFCell dayCell_1 = row.createCell(i*2); + XSSFCell dayCell_2 = row.createCell(i*2 + 1); + + int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); + if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) { + dayCell_1.setCellValue(day); + calendar.set(Calendar.DAY_OF_MONTH, ++day); + + if(i == 0 || i == days.length-1) { + dayCell_1.setCellStyle(styles.get("weekend_left")); + dayCell_2.setCellStyle(styles.get("weekend_right")); + } else { + dayCell_1.setCellStyle(styles.get("workday_left")); + dayCell_2.setCellStyle(styles.get("workday_right")); + } + } else { + dayCell_1.setCellStyle(styles.get("grey_left")); + dayCell_2.setCellStyle(styles.get("grey_right")); + } + cnt++; + } + if(calendar.get(Calendar.MONTH) > month) break; + } + } + + // Write the output to a file + FileOutputStream out = new FileOutputStream("calendar-"+year+".xlsx"); + wb.write(out); + out.close(); + } + + /** + * cell styles used for formatting calendar sheets + */ + private static Map createStyles(XSSFWorkbook wb){ + Map styles = new HashMap(); + + XSSFCellStyle style; + XSSFFont titleFont = wb.createFont(); + titleFont.setFontHeightInPoints((short)48); + titleFont.setColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setFont(titleFont); + styles.put("title", style); + + XSSFFont monthFont = wb.createFont(); + monthFont.setFontHeightInPoints((short)12); + monthFont.setColor(new XSSFColor(new java.awt.Color(255, 255, 255))); + monthFont.setBold(true); + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setFillForegroundColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setFont(monthFont); + styles.put("month", style); + + XSSFFont dayFont = wb.createFont(); + dayFont.setFontHeightInPoints((short)14); + dayFont.setBold(true); + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.LEFT); + style.setVerticalAlignment(VerticalAlignment.TOP); + style.setFillForegroundColor(new XSSFColor(new java.awt.Color(228, 232, 243))); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setBorderLeft(BorderStyle.THIN); + style.setLeftBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style.setFont(dayFont); + styles.put("weekend_left", style); + + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.TOP); + style.setFillForegroundColor(new XSSFColor(new java.awt.Color(228, 232, 243))); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setBorderRight(BorderStyle.THIN); + style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + styles.put("weekend_right", style); + + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.LEFT); + style.setVerticalAlignment(VerticalAlignment.TOP); + style.setBorderLeft(BorderStyle.THIN); + style.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255))); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setLeftBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style.setFont(dayFont); + styles.put("workday_left", style); + + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.TOP); + style.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255))); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setBorderRight(BorderStyle.THIN); + style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + styles.put("workday_right", style); + + style = wb.createCellStyle(); + style.setBorderLeft(BorderStyle.THIN); + style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234))); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + styles.put("grey_left", style); + + style = wb.createCellStyle(); + style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234))); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setBorderRight(BorderStyle.THIN); + style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); + styles.put("grey_right", style); + + return styles; + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/CellComments.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CellComments.java new file mode 100644 index 0000000000..4eaa33d92d --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CellComments.java @@ -0,0 +1,80 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import java.io.IOException; +import java.io.FileOutputStream; + +/** + * Demonstrates how to work with excel cell comments. + * + *

    + * Excel comment is a kind of a text shape, + * so inserting a comment is very similar to placing a text box in a worksheet + *

    + * + * @author Yegor Kozlov + */ +public class CellComments { + public static void main(String[] args) throws IOException { + Workbook wb = new XSSFWorkbook(); + + CreationHelper factory = wb.getCreationHelper(); + + Sheet sheet = wb.createSheet(); + + Cell cell1 = sheet.createRow(3).createCell(5); + cell1.setCellValue("F4"); + + Drawing drawing = sheet.createDrawingPatriarch(); + + ClientAnchor anchor = factory.createClientAnchor(); + + Comment comment1 = drawing.createCellComment(anchor); + RichTextString str1 = factory.createRichTextString("Hello, World!"); + comment1.setString(str1); + comment1.setAuthor("Apache POI"); + cell1.setCellComment(comment1); + + Cell cell2 = sheet.createRow(2).createCell(2); + cell2.setCellValue("C3"); + + Comment comment2 = drawing.createCellComment(anchor); + RichTextString str2 = factory.createRichTextString("XSSF can set cell comments"); + //apply custom font to the text in the comment + Font font = wb.createFont(); + font.setFontName("Arial"); + font.setFontHeightInPoints((short)14); + font.setBoldweight(Font.BOLDWEIGHT_BOLD); + font.setColor(IndexedColors.RED.getIndex()); + str2.applyFont(font); + + comment2.setString(str2); + comment2.setAuthor("Apache POI"); + comment2.setColumn(2); + comment2.setRow(2); + + String fname = "comments.xlsx"; + FileOutputStream out = new FileOutputStream(fname); + wb.write(out); + out.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/CreateCell.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CreateCell.java new file mode 100644 index 0000000000..9a2c46033a --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CreateCell.java @@ -0,0 +1,80 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; +import java.util.Date; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * Illustrates how to create cell and set values of different types. + */ +public class CreateCell { + + + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + CreationHelper creationHelper = wb.getCreationHelper(); + Sheet sheet = wb.createSheet("new sheet"); + + // Create a row and put some cells in it. Rows are 0 based. + Row row = sheet.createRow((short)0); + // Create a cell and put a value in it. + Cell cell = row.createCell((short)0); + cell.setCellValue(1); + + //numeric value + row.createCell(1).setCellValue(1.2); + + //plain string value + row.createCell(2).setCellValue("This is a string cell"); + + //rich text string + RichTextString str = creationHelper.createRichTextString("Apache"); + Font font = wb.createFont(); + font.setItalic(true); + font.setUnderline(Font.U_SINGLE); + str.applyFont(font); + row.createCell(3).setCellValue(str); + + //boolean value + row.createCell(4).setCellValue(true); + + //formula + row.createCell(5).setCellFormula("SUM(A1:B1)"); + + //date + CellStyle style = wb.createCellStyle(); + style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm")); + cell = row.createCell(6); + cell.setCellValue(new Date()); + cell.setCellStyle(style); + + //hyperlink + row.createCell(7).setCellFormula("SUM(A1:B1)"); + cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")"); + + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java new file mode 100644 index 0000000000..2c37ea08d2 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java @@ -0,0 +1,65 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.DataFormat; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * How to set user-defined date formats + */ +public class CreateUserDefinedDataFormats { + + + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet("format sheet"); + CellStyle style; + DataFormat format = wb.createDataFormat(); + Row row; + Cell cell; + short rowNum = 0; + short colNum = 0; + + row = sheet.createRow(rowNum++); + cell = row.createCell(colNum); + cell.setCellValue(11111.25); + style = wb.createCellStyle(); + style.setDataFormat(format.getFormat("0.0")); + cell.setCellStyle(style); + + row = sheet.createRow(rowNum++); + cell = row.createCell(colNum); + cell.setCellValue(11111.25); + style = wb.createCellStyle(); + style.setDataFormat(format.getFormat("#,##0.0000")); + cell.setCellStyle(style); + + FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx"); + wb.write(fileOut); + fileOut.close(); + } + +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/CustomXMLMapping.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CustomXMLMapping.java new file mode 100644 index 0000000000..1add0d2fb3 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/CustomXMLMapping.java @@ -0,0 +1,45 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.xssf.extractor.XSSFExportToXml; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFMap; + +import java.io.ByteArrayOutputStream; + +/** + * Print all custom XML mappings registered in the given workbook + */ +public class CustomXMLMapping { + + public static void main(String[] args) throws Exception { + OPCPackage pkg = OPCPackage.open(args[0]); + XSSFWorkbook wb = new XSSFWorkbook(pkg); + + for (XSSFMap map : wb.getCustomXMLMappings()) { + XSSFExportToXml exporter = new XSSFExportToXml(map); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + exporter.exportToXML(os, true); + String xml = os.toString("UTF-8"); + System.out.println(xml); + } + pkg.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/EmbeddedObjects.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/EmbeddedObjects.java new file mode 100644 index 0000000000..b50e959460 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/EmbeddedObjects.java @@ -0,0 +1,72 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackagePart; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.hslf.HSLFSlideShow; +import org.apache.poi.hwpf.HWPFDocument; +import org.apache.poi.xslf.XSLFSlideShow; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; + +import java.io.InputStream; + +/** + * Demonstrates how you can extract embedded data from a .xlsx file + */ +public class EmbeddedObjects { + public static void main(String[] args) throws Exception { + OPCPackage pkg = OPCPackage.open(args[0]); + XSSFWorkbook workbook = new XSSFWorkbook(pkg); + for (PackagePart pPart : workbook.getAllEmbedds()) { + String contentType = pPart.getContentType(); + // Excel Workbook - either binary or OpenXML + if (contentType.equals("application/vnd.ms-excel")) { + HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream()); + } + // Excel Workbook - OpenXML file format + else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { + XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream()); + } + // Word Document - binary (OLE2CDF) file format + else if (contentType.equals("application/msword")) { + HWPFDocument document = new HWPFDocument(pPart.getInputStream()); + } + // Word Document - OpenXML file format + else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) { + XWPFDocument document = new XWPFDocument(pPart.getInputStream()); + } + // PowerPoint Document - binary file format + else if (contentType.equals("application/vnd.ms-powerpoint")) { + HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream()); + } + // PowerPoint Document - OpenXML file format + else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) { + OPCPackage docPackage = OPCPackage.open(pPart.getInputStream()); + XSLFSlideShow slideShow = new XSLFSlideShow(docPackage); + } + // Any other type of embedded object. + else { + System.out.println("Unknown Embedded Document: " + contentType); + InputStream inputStream = pPart.getInputStream(); + } + } + pkg.close(); + } +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/FillsAndColors.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/FillsAndColors.java new file mode 100644 index 0000000000..019e14d1ce --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/FillsAndColors.java @@ -0,0 +1,59 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.xssf.usermodel.XSSFRichTextString; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * Fills and Colors + */ +public class FillsAndColors { + public static void main(String[] args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet("new sheet"); + + // Create a row and put some cells in it. Rows are 0 based. + Row row = sheet.createRow((short) 1); + + // Aqua background + CellStyle style = wb.createCellStyle(); + style.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); + style.setFillPattern(CellStyle.BIG_SPOTS); + Cell cell = row.createCell((short) 1); + cell.setCellValue(new XSSFRichTextString("X")); + cell.setCellStyle(style); + + // Orange "foreground", foreground being the fill foreground not the font color. + style = wb.createCellStyle(); + style.setFillForegroundColor(IndexedColors.ORANGE.getIndex()); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + cell = row.createCell((short) 2); + cell.setCellValue(new XSSFRichTextString("X")); + cell.setCellStyle(style); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx"); + wb.write(fileOut); + fileOut.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/FitSheetToOnePage.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/FitSheetToOnePage.java new file mode 100644 index 0000000000..a781688c39 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/FitSheetToOnePage.java @@ -0,0 +1,46 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.PrintSetup; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +public class FitSheetToOnePage { + + + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet("format sheet"); + PrintSetup ps = sheet.getPrintSetup(); + + sheet.setAutobreaks(true); + + ps.setFitHeight((short) 1); + ps.setFitWidth((short) 1); + + // Create various cells and rows for spreadsheet. + + FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx"); + wb.write(fileOut); + fileOut.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/HeadersAndFooters.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/HeadersAndFooters.java new file mode 100644 index 0000000000..8b95fe63c2 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/HeadersAndFooters.java @@ -0,0 +1,84 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.Footer; +import org.apache.poi.ss.usermodel.Header; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +public class HeadersAndFooters { + + + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet("first-header - format sheet"); + sheet.createRow(0).createCell(0).setCellValue(123); + + //set page numbers in the footer + Footer footer = sheet.getFooter(); + //&P == current page number + //&N == page numbers + footer.setRight("Page &P of &N"); + + + Header firstHeader=((XSSFSheet)sheet).getFirstHeader(); + //&F == workbook file name + firstHeader.setLeft("&F ......... first header"); + + for(int i=0;i<100;i=i+10){ + sheet.createRow(i).createCell(0).setCellValue(123); + } + + + XSSFSheet sheet2 = (XSSFSheet)wb.createSheet("odd header-even footer"); + Header oddHeader=sheet2.getOddHeader(); + //&B == bold + //&E == double underline + //&D == date + oddHeader.setCenter("&B &E oddHeader &D "); + + Footer evenFooter=sheet2.getEvenFooter(); + evenFooter.setRight("even footer &P"); + sheet2.createRow(10).createCell(0).setCellValue("Second sheet with an oddHeader and an evenFooter"); + + for(int i=0;i<200;i=i+10){ + sheet2.createRow(i).createCell(0).setCellValue(123); + } + + XSSFSheet sheet3 = (XSSFSheet)wb.createSheet("odd header- odd footer"); + sheet3.createRow(10).createCell(0).setCellValue("Third sheet with oddHeader and oddFooter"); + Header oddH=sheet3.getOddHeader(); + //&C == centered + oddH.setCenter("centered oddHeader"); + oddH.setLeft("left "); + oddH.setRight("right "); + + Footer oddF=sheet3.getOddFooter(); + oddF.setLeft("Page &P"); + oddF.setRight("Pages &N "); + + FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx"); + wb.write(fileOut); + fileOut.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/HyperlinkExample.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/HyperlinkExample.java new file mode 100644 index 0000000000..005bdc756d --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/HyperlinkExample.java @@ -0,0 +1,89 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.ss.usermodel.IndexedColors; + +/** + * Demonstrates how to create hyperlinks. + */ +public class HyperlinkExample { + + + public static void main(String[]args) throws Exception{ + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + CreationHelper createHelper = wb.getCreationHelper(); + + //cell style for hyperlinks + //by default hyperlinks are blue and underlined + CellStyle hlink_style = wb.createCellStyle(); + Font hlink_font = wb.createFont(); + hlink_font.setUnderline(Font.U_SINGLE); + hlink_font.setColor(IndexedColors.BLUE.getIndex()); + hlink_style.setFont(hlink_font); + + Cell cell; + Sheet sheet = wb.createSheet("Hyperlinks"); + //URL + cell = sheet.createRow(0).createCell((short)0); + cell.setCellValue("URL Link"); + + Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL); + link.setAddress("http://poi.apache.org/"); + cell.setHyperlink(link); + cell.setCellStyle(hlink_style); + + //link to a file in the current directory + cell = sheet.createRow(1).createCell((short)0); + cell.setCellValue("File Link"); + link = createHelper.createHyperlink(Hyperlink.LINK_FILE); + link.setAddress("link1.xls"); + cell.setHyperlink(link); + cell.setCellStyle(hlink_style); + + //e-mail link + cell = sheet.createRow(2).createCell((short)0); + cell.setCellValue("Email Link"); + link = createHelper.createHyperlink(Hyperlink.LINK_EMAIL); + //note, if subject contains white spaces, make sure they are url-encoded + link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); + cell.setHyperlink(link); + cell.setCellStyle(hlink_style); + + //link to a place in this workbook + + //create a target sheet and cell + Sheet sheet2 = wb.createSheet("Target Sheet"); + sheet2.createRow(0).createCell((short)0).setCellValue("Target Cell"); + + cell = sheet.createRow(3).createCell((short)0); + cell.setCellValue("Worksheet Link"); + Hyperlink link2 = createHelper.createHyperlink(Hyperlink.LINK_DOCUMENT); + link2.setAddress("'Target Sheet'!A1"); + cell.setHyperlink(link2); + cell.setCellStyle(hlink_style); + + FileOutputStream out = new FileOutputStream("hyperinks.xlsx"); + wb.write(out); + out.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/IterateCells.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/IterateCells.java new file mode 100644 index 0000000000..99d1cacf61 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/IterateCells.java @@ -0,0 +1,46 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; + +import java.io.FileInputStream; + +/** + * Iterate over rows and cells + */ +public class IterateCells { + + public static void main(String[] args) throws Exception { + Workbook wb = new XSSFWorkbook(new FileInputStream(args[0])); + for (int i = 0; i < wb.getNumberOfSheets(); i++) { + Sheet sheet = wb.getSheetAt(i); + System.out.println(wb.getSheetName(i)); + for (Row row : sheet) { + System.out.println("rownum: " + row.getRowNum()); + for (Cell cell : row) { + System.out.println(cell.toString()); + } + } + } + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/LineChart.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/LineChart.java new file mode 100644 index 0000000000..9fc24ac0d7 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/LineChart.java @@ -0,0 +1,79 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.usermodel.charts.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import java.io.FileOutputStream; + +/** + * Line chart example. + * + * @author Martin Andersson + */ +public class LineChart { + + public static void main(String[] args) throws Exception { + Workbook wb = new XSSFWorkbook(); + Sheet sheet = wb.createSheet("linechart"); + final int NUM_OF_ROWS = 3; + final int NUM_OF_COLUMNS = 10; + + // Create a row and put some cells in it. Rows are 0 based. + Row row; + Cell cell; + for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { + row = sheet.createRow((short) rowIndex); + for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { + cell = row.createCell((short) colIndex); + cell.setCellValue(colIndex * (rowIndex + 1)); + } + } + + Drawing drawing = sheet.createDrawingPatriarch(); + ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); + + Chart chart = drawing.createChart(anchor); + ChartLegend legend = chart.getOrCreateLegend(); + legend.setPosition(LegendPosition.TOP_RIGHT); + + LineChartData data = chart.getChartDataFactory().createLineChartData(); + + // Use a category axis for the bottom axis. + ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); + ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); + leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); + + ChartDataSource xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); + ChartDataSource ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); + ChartDataSource ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); + + + data.addSerie(xs, ys1); + data.addSerie(xs, ys2); + + chart.plot(data, bottomAxis, leftAxis); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/MergingCells.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/MergingCells.java new file mode 100644 index 0000000000..9d63268fc3 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/MergingCells.java @@ -0,0 +1,49 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFRichTextString; + +import java.io.FileOutputStream; + +/** + * An example of how to merge regions of cells. + */ +public class MergingCells { + public static void main(String[] args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet("new sheet"); + + Row row = sheet.createRow((short) 1); + Cell cell = row.createCell((short) 1); + cell.setCellValue(new XSSFRichTextString("This is a test of merging")); + + sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2)); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/NewLinesInCells.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/NewLinesInCells.java new file mode 100644 index 0000000000..eb179357d5 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/NewLinesInCells.java @@ -0,0 +1,57 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * How to use newlines in cells + */ +public class NewLinesInCells { + + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet(); + + Row row = sheet.createRow(2); + Cell cell = row.createCell(2); + cell.setCellValue("Use \n with word wrap on to create a new line"); + + //to enable newlines you need set a cell styles with wrap=true + CellStyle cs = wb.createCellStyle(); + cs.setWrapText(true); + cell.setCellStyle(cs); + + //increase row height to accomodate two lines of text + row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints())); + + //adjust column width to fit the content + sheet.autoSizeColumn(2); + + FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx"); + wb.write(fileOut); + fileOut.close(); + } + +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/Outlining.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/Outlining.java new file mode 100644 index 0000000000..71d63b1f55 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/Outlining.java @@ -0,0 +1,75 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +public class Outlining { + + public static void main(String[]args) throws Exception{ + Outlining o=new Outlining(); + o.groupRowColumn(); + o.collapseExpandRowColumn(); + } + + + private void groupRowColumn() throws Exception{ + Workbook wb = new XSSFWorkbook(); + Sheet sheet1 = wb.createSheet("new sheet"); + + sheet1.groupRow( 5, 14 ); + sheet1.groupRow( 7, 14 ); + sheet1.groupRow( 16, 19 ); + + sheet1.groupColumn( (short)4, (short)7 ); + sheet1.groupColumn( (short)9, (short)12 ); + sheet1.groupColumn( (short)10, (short)11 ); + + FileOutputStream fileOut = new FileOutputStream("outlining.xlsx"); + wb.write(fileOut); + fileOut.close(); + + } + + private void collapseExpandRowColumn()throws Exception{ + Workbook wb2 = new XSSFWorkbook(); + Sheet sheet2 = wb2.createSheet("new sheet"); + sheet2.groupRow( 5, 14 ); + sheet2.groupRow( 7, 14 ); + sheet2.groupRow( 16, 19 ); + + sheet2.groupColumn( (short)4, (short)7 ); + sheet2.groupColumn( (short)9, (short)12 ); + sheet2.groupColumn( (short)10, (short)11 ); + + + sheet2.setRowGroupCollapsed( 7, true ); + //sheet1.setRowGroupCollapsed(7,false); + + sheet2.setColumnGroupCollapsed( (short)4, true ); + sheet2.setColumnGroupCollapsed( (short)4, false ); + + FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx"); + wb2.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/ScatterChart.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/ScatterChart.java new file mode 100644 index 0000000000..f0a94777f0 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/ScatterChart.java @@ -0,0 +1,80 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.*; +import org.apache.poi.ss.usermodel.charts.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * Illustrates how to create a simple scatter chart. + * + * @author Roman Kashitsyn + */ +public class ScatterChart { + + public static void main(String[] args) throws Exception { + Workbook wb = new XSSFWorkbook(); + Sheet sheet = wb.createSheet("Sheet 1"); + final int NUM_OF_ROWS = 3; + final int NUM_OF_COLUMNS = 10; + + // Create a row and put some cells in it. Rows are 0 based. + Row row; + Cell cell; + for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { + row = sheet.createRow((short) rowIndex); + for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { + cell = row.createCell((short) colIndex); + cell.setCellValue(colIndex * (rowIndex + 1)); + } + } + + Drawing drawing = sheet.createDrawingPatriarch(); + ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); + + Chart chart = drawing.createChart(anchor); + ChartLegend legend = chart.getOrCreateLegend(); + legend.setPosition(LegendPosition.TOP_RIGHT); + + ScatterChartData data = chart.getChartDataFactory().createScatterChartData(); + + ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM); + ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); + leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); + + ChartDataSource xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); + ChartDataSource ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); + ChartDataSource ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); + + + data.addSerie(xs, ys1); + data.addSerie(xs, ys2); + + chart.plot(data, bottomAxis, leftAxis); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/SelectedSheet.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/SelectedSheet.java new file mode 100644 index 0000000000..45bee91d6f --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/SelectedSheet.java @@ -0,0 +1,43 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +public class SelectedSheet { + + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + + Sheet sheet = wb.createSheet("row sheet"); + Sheet sheet2 = wb.createSheet("another sheet"); + Sheet sheet3 = wb.createSheet(" sheet 3 "); + sheet3.setSelected(true); + wb.setActiveSheet(2); + + // Create various cells and rows for spreadsheet. + + FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx"); + wb.write(fileOut); + fileOut.close(); + } + +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/ShiftRows.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/ShiftRows.java new file mode 100644 index 0000000000..ec4bb21398 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/ShiftRows.java @@ -0,0 +1,61 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * How to shift rows up or down + */ +public class ShiftRows { + + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet("Sheet1"); + + Row row1 = sheet.createRow(1); + row1.createCell(0).setCellValue(1); + + Row row2 = sheet.createRow(4); + row2.createCell(1).setCellValue(2); + + Row row3 = sheet.createRow(5); + row3.createCell(2).setCellValue(3); + + Row row4 = sheet.createRow(6); + row4.createCell(3).setCellValue(4); + + Row row5 = sheet.createRow(9); + row5.createCell(4).setCellValue(5); + + // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5) + sheet.shiftRows(5, 10, -4); + + FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx"); + wb.write(fileOut); + fileOut.close(); + + } + + +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/SplitAndFreezePanes.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/SplitAndFreezePanes.java new file mode 100644 index 0000000000..937086b85d --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/SplitAndFreezePanes.java @@ -0,0 +1,50 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import java.io.FileOutputStream; + +/** + * How to set spklit and freeze panes + */ +public class SplitAndFreezePanes { + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); + Sheet sheet1 = wb.createSheet("new sheet"); + Sheet sheet2 = wb.createSheet("second sheet"); + Sheet sheet3 = wb.createSheet("third sheet"); + Sheet sheet4 = wb.createSheet("fourth sheet"); + + // Freeze just one row + sheet1.createFreezePane(0, 1, 0, 1); + // Freeze just one column + sheet2.createFreezePane(1, 0, 1, 0); + // Freeze the columns and rows (forget about scrolling position of the lower right quadrant). + sheet3.createFreezePane(2, 2); + // Create a split with the lower left side being the active quadrant + sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT); + + FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkbookProperties.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkbookProperties.java new file mode 100644 index 0000000000..3a8fd56d00 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkbookProperties.java @@ -0,0 +1,66 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.POIXMLProperties; + +/** + * How to set extended and custom properties + * + * @author Yegor Kozlov + */ +public class WorkbookProperties { + + public static void main(String[]args) throws Exception { + + XSSFWorkbook workbook = new XSSFWorkbook(); + workbook.createSheet("Workbook Properties"); + + POIXMLProperties props = workbook.getProperties(); + + /** + * Extended properties are a predefined set of metadata properties + * that are specifically applicable to Office Open XML documents. + * Extended properties consist of 24 simple properties and 3 complex properties stored in the + * part targeted by the relationship of type + */ + POIXMLProperties.ExtendedProperties ext = props.getExtendedProperties(); + ext.getUnderlyingProperties().setCompany("Apache Software Foundation"); + ext.getUnderlyingProperties().setTemplate("XSSF"); + + /** + * Custom properties enable users to define custom metadata properties. + */ + + POIXMLProperties.CustomProperties cust = props.getCustomProperties(); + cust.addProperty("Author", "John Smith"); + cust.addProperty("Year", 2009); + cust.addProperty("Price", 45.50); + cust.addProperty("Available", true); + + FileOutputStream out = new FileOutputStream("workbook.xlsx"); + workbook.write(out); + out.close(); + + } + + +} \ No newline at end of file diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithBorders.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithBorders.java new file mode 100644 index 0000000000..6e12fffe74 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithBorders.java @@ -0,0 +1,58 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.usermodel.*; + +import java.io.FileOutputStream; + +/** + * Working with borders + */ +public class WorkingWithBorders { + public static void main(String[] args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet("borders"); + + // Create a row and put some cells in it. Rows are 0 based. + Row row = sheet.createRow((short) 1); + + // Create a cell and put a value in it. + Cell cell = row.createCell((short) 1); + cell.setCellValue(4); + + // Style the cell with borders all around. + CellStyle style = wb.createCellStyle(); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setLeftBorderColor(IndexedColors.GREEN.getIndex()); + style.setBorderRight(CellStyle.BORDER_THIN); + style.setRightBorderColor(IndexedColors.BLUE.getIndex()); + style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED); + style.setTopBorderColor(IndexedColors.BLACK.getIndex()); + cell.setCellStyle(style); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithFonts.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithFonts.java new file mode 100644 index 0000000000..3d4393ba1f --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithFonts.java @@ -0,0 +1,101 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.ss.usermodel.IndexedColors; + +import java.io.FileOutputStream; + +/** + * Working with Fonts + */ +public class WorkingWithFonts { + public static void main(String[] args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + Sheet sheet = wb.createSheet("Fonts"); + + Font font0 = wb.createFont(); + font0.setColor(IndexedColors.BROWN.getIndex()); + CellStyle style0 = wb.createCellStyle(); + style0.setFont(font0); + + Font font1 = wb.createFont(); + font1.setFontHeightInPoints((short)14); + font1.setFontName("Courier New"); + font1.setColor(IndexedColors.RED.getIndex()); + CellStyle style1 = wb.createCellStyle(); + style1.setFont(font1); + + Font font2 = wb.createFont(); + font2.setFontHeightInPoints((short)16); + font2.setFontName("Arial"); + font2.setColor(IndexedColors.GREEN.getIndex()); + CellStyle style2 = wb.createCellStyle(); + style2.setFont(font2); + + Font font3 = wb.createFont(); + font3.setFontHeightInPoints((short)18); + font3.setFontName("Times New Roman"); + font3.setColor(IndexedColors.LAVENDER.getIndex()); + CellStyle style3 = wb.createCellStyle(); + style3.setFont(font3); + + Font font4 = wb.createFont(); + font4.setFontHeightInPoints((short)18); + font4.setFontName("Wingdings"); + font4.setColor(IndexedColors.GOLD.getIndex()); + CellStyle style4 = wb.createCellStyle(); + style4.setFont(font4); + + Font font5 = wb.createFont(); + font5.setFontName("Symbol"); + CellStyle style5 = wb.createCellStyle(); + style5.setFont(font5); + + Cell cell0 = sheet.createRow(0).createCell(1); + cell0.setCellValue("Default"); + cell0.setCellStyle(style0); + + Cell cell1 = sheet.createRow(1).createCell(1); + cell1.setCellValue("Courier"); + cell1.setCellStyle(style1); + + Cell cell2 = sheet.createRow(2).createCell(1); + cell2.setCellValue("Arial"); + cell2.setCellStyle(style2); + + Cell cell3 = sheet.createRow(3).createCell(1); + cell3.setCellValue("Times New Roman"); + cell3.setCellStyle(style3); + + Cell cell4 = sheet.createRow(4).createCell(1); + cell4.setCellValue("Wingdings"); + cell4.setCellStyle(style4); + + Cell cell5 = sheet.createRow(5).createCell(1); + cell5.setCellValue("Symbol"); + cell5.setCellStyle(style5); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithPageSetup.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithPageSetup.java new file mode 100644 index 0000000000..d1be7af174 --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithPageSetup.java @@ -0,0 +1,78 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xssf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * Demonstrates various settings avaiable in the Page Setup dialog + */ +public class WorkingWithPageSetup { + + public static void main(String[]args) throws Exception { + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + + /** + * It's possible to set up repeating rows and columns in your printouts by using the setRepeatingRowsAndColumns() function in the Workbook object. + * + * This function Contains 5 parameters: + * The first parameter is the index to the sheet (0 = first sheet). + * The second and third parameters specify the range for the columns to repreat. + * To stop the columns from repeating pass in -1 as the start and end column. + * The fourth and fifth parameters specify the range for the rows to repeat. + * To stop the columns from repeating pass in -1 as the start and end rows. + */ + Sheet sheet1 = wb.createSheet("new sheet"); + Sheet sheet2 = wb.createSheet("second sheet"); + + // Set the columns to repeat from column 0 to 2 on the first sheet + Row row1 = sheet1.createRow(0); + row1.createCell(0).setCellValue(1); + row1.createCell(1).setCellValue(2); + row1.createCell(2).setCellValue(3); + Row row2 = sheet1.createRow(1); + row2.createCell(1).setCellValue(4); + row2.createCell(2).setCellValue(5); + + + Row row3 = sheet2.createRow(1); + row3.createCell(0).setCellValue(2.1); + row3.createCell(4).setCellValue(2.2); + row3.createCell(5).setCellValue(2.3); + Row row4 = sheet2.createRow(2); + row4.createCell(4).setCellValue(2.4); + row4.createCell(5).setCellValue(2.5); + + // Set the columns to repeat from column 0 to 2 on the first sheet + wb.setRepeatingRowsAndColumns(0,0,2,-1,-1); + // Set the the repeating rows and columns on the second sheet. + wb.setRepeatingRowsAndColumns(1,4,5,1,2); + + //set the print area for the first sheet + wb.setPrintArea(0, 1, 2, 0, 3); + + + FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithPictures.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithPictures.java new file mode 100644 index 0000000000..a2a914335e --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithPictures.java @@ -0,0 +1,69 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.xssf.usermodel.*; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.util.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; + +/** + * Demonstrates how to insert pictures in a SpreadsheetML document + * + * @author Yegor Kozlov + */ +public class WorkingWithPictures { + public static void main(String[] args) throws IOException { + + //create a new workbook + Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + CreationHelper helper = wb.getCreationHelper(); + + //add a picture in this workbook. + InputStream is = new FileInputStream(args[0]); + byte[] bytes = IOUtils.toByteArray(is); + is.close(); + int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG); + + //create sheet + Sheet sheet = wb.createSheet(); + + //create drawing + Drawing drawing = sheet.createDrawingPatriarch(); + + //add a picture shape + ClientAnchor anchor = helper.createClientAnchor(); + anchor.setCol1(1); + anchor.setRow1(1); + Picture pict = drawing.createPicture(anchor, pictureIdx); + + //auto-size picture + pict.resize(2); + + //save workbook + String file = "picture.xls"; + if(wb instanceof XSSFWorkbook) file += "x"; + FileOutputStream fileOut = new FileOutputStream(file); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithRichText.java b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithRichText.java new file mode 100644 index 0000000000..d019ab8d8b --- /dev/null +++ b/poi-examples/src/main/java/poi/xssf/usermodel/examples/WorkingWithRichText.java @@ -0,0 +1,61 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.xssf.usermodel.examples; + +import org.apache.poi.xssf.usermodel.*; + +import java.io.FileOutputStream; + +/** + * Demonstrates how to work with rich text + */ +public class WorkingWithRichText { + + public static void main(String[] args) throws Exception { + + XSSFWorkbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); + + XSSFSheet sheet = wb.createSheet(); + XSSFRow row = sheet.createRow((short) 2); + + XSSFCell cell = row.createCell(1); + XSSFRichTextString rt = new XSSFRichTextString("The quick brown fox"); + + XSSFFont font1 = wb.createFont(); + font1.setBold(true); + font1.setColor(new XSSFColor(new java.awt.Color(255, 0, 0))); + rt.applyFont(0, 10, font1); + + XSSFFont font2 = wb.createFont(); + font2.setItalic(true); + font2.setUnderline(XSSFFont.U_DOUBLE); + font2.setColor(new XSSFColor(new java.awt.Color(0, 255, 0))); + rt.applyFont(10, 19, font2); + + XSSFFont font3 = wb.createFont(); + font3.setColor(new XSSFColor(new java.awt.Color(0, 0, 255))); + rt.append(" Jumped over the lazy dog", font3); + + cell.setCellValue(rt); + + // Write the output to a file + FileOutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx"); + wb.write(fileOut); + fileOut.close(); + } +} diff --git a/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleDocument.java b/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleDocument.java new file mode 100644 index 0000000000..b7e4da2d4e --- /dev/null +++ b/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleDocument.java @@ -0,0 +1,120 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xwpf.usermodel; + +import java.io.FileOutputStream; + +/** + * A simple WOrdprocessingML document created by POI XWPF API + * + * @author Yegor Kozlov + */ +public class SimpleDocument { + + public static void main(String[] args) throws Exception { + XWPFDocument doc = new XWPFDocument(); + + XWPFParagraph p1 = doc.createParagraph(); + p1.setAlignment(ParagraphAlignment.CENTER); + p1.setBorderBottom(Borders.DOUBLE); + p1.setBorderTop(Borders.DOUBLE); + + p1.setBorderRight(Borders.DOUBLE); + p1.setBorderLeft(Borders.DOUBLE); + p1.setBorderBetween(Borders.SINGLE); + + p1.setVerticalAlignment(TextAlignment.TOP); + + XWPFRun r1 = p1.createRun(); + r1.setBold(true); + r1.setText("The quick brown fox"); + r1.setBold(true); + r1.setFontFamily("Courier"); + r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); + r1.setTextPosition(100); + + XWPFParagraph p2 = doc.createParagraph(); + p2.setAlignment(ParagraphAlignment.RIGHT); + + //BORDERS + p2.setBorderBottom(Borders.DOUBLE); + p2.setBorderTop(Borders.DOUBLE); + p2.setBorderRight(Borders.DOUBLE); + p2.setBorderLeft(Borders.DOUBLE); + p2.setBorderBetween(Borders.SINGLE); + + XWPFRun r2 = p2.createRun(); + r2.setText("jumped over the lazy dog"); + r2.setStrike(true); + r2.setFontSize(20); + + XWPFRun r3 = p2.createRun(); + r3.setText("and went away"); + r3.setStrike(true); + r3.setFontSize(20); + r3.setSubscript(VerticalAlign.SUPERSCRIPT); + + + XWPFParagraph p3 = doc.createParagraph(); + p3.setWordWrap(true); + p3.setPageBreak(true); + + //p3.setAlignment(ParagraphAlignment.DISTRIBUTE); + p3.setAlignment(ParagraphAlignment.BOTH); + p3.setSpacingLineRule(LineSpacingRule.EXACT); + + p3.setIndentationFirstLine(600); + + + XWPFRun r4 = p3.createRun(); + r4.setTextPosition(20); + r4.setText("To be, or not to be: that is the question: " + + "Whether 'tis nobler in the mind to suffer " + + "The slings and arrows of outrageous fortune, " + + "Or to take arms against a sea of troubles, " + + "And by opposing end them? To die: to sleep; "); + r4.addBreak(BreakType.PAGE); + r4.setText("No more; and by a sleep to say we end " + + "The heart-ache and the thousand natural shocks " + + "That flesh is heir to, 'tis a consummation " + + "Devoutly to be wish'd. To die, to sleep; " + + "To sleep: perchance to dream: ay, there's the rub; " + + "......."); + r4.setItalic(true); +//This would imply that this break shall be treated as a simple line break, and break the line after that word: + + XWPFRun r5 = p3.createRun(); + r5.setTextPosition(-10); + r5.setText("For in that sleep of death what dreams may come"); + r5.addCarriageReturn(); + r5.setText("When we have shuffled off this mortal coil," + + "Must give us pause: there's the respect" + + "That makes calamity of so long life;"); + r5.addBreak(); + r5.setText("For who would bear the whips and scorns of time," + + "The oppressor's wrong, the proud man's contumely,"); + + r5.addBreak(BreakClear.ALL); + r5.setText("The pangs of despised love, the law's delay," + + "The insolence of office and the spurns" + "......."); + + FileOutputStream out = new FileOutputStream("simple.docx"); + doc.write(out); + out.close(); + + } +} diff --git a/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleImages.java b/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleImages.java new file mode 100644 index 0000000000..10e48d1aed --- /dev/null +++ b/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleImages.java @@ -0,0 +1,71 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.apache.poi.xwpf.usermodel; + +import org.apache.poi.util.Units; + +import java.io.FileInputStream; +import java.io.FileOutputStream; + +/** + * Demonstrates how to add pictures in a .docx document + * + * @author Yegor Kozlov + */ +public class SimpleImages { + + public static void main(String[] args) throws Exception { + XWPFDocument doc = new XWPFDocument(); + XWPFParagraph p = doc.createParagraph(); + + XWPFRun r = p.createRun(); + + for(String imgFile : args) { + int format; + + if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF; + else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF; + else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT; + else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG; + else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG; + else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB; + else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF; + else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF; + else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS; + else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP; + else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG; + else { + System.err.println("Unsupported picture: " + imgFile + + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg"); + continue; + } + + r.setText(imgFile); + r.addBreak(); + r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels + r.addBreak(BreakType.PAGE); + } + + FileOutputStream out = new FileOutputStream("images.docx"); + doc.write(out); + out.close(); + } + + +} diff --git a/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleTable.java b/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleTable.java new file mode 100644 index 0000000000..5f049ba0ac --- /dev/null +++ b/poi-examples/src/main/java/poi/xwpf/usermodel/SimpleTable.java @@ -0,0 +1,199 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xwpf.usermodel; + +import java.io.FileOutputStream; +import java.math.BigInteger; +import java.util.List; + +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc; + +/** + * This program creates a simple WordprocessingML table using POI XWPF API, and + * a more complex, styled table using both XWPF and ooxml-schema. It's possible + * that not all referenced wordprocessingml classes are defined in + * poi-ooxml-schemas-3.8-beta4. If this is the case, you'll need to use the full + * ooxml-schemas.jar library. + * + * @author gisella bronzetti (original) + * @author Gregg Morris (styled table) + */ +public class SimpleTable { + + public static void main(String[] args) throws Exception { + try { + createSimpleTable(); + } + catch(Exception e) { + System.out.println("Error trying to create simple table."); + throw(e); + } + try { + createStyledTable(); + } + catch(Exception e) { + System.out.println("Error trying to create styled table."); + throw(e); + } + } + + public static void createSimpleTable() throws Exception { + XWPFDocument doc = new XWPFDocument(); + + XWPFTable table = doc.createTable(3, 3); + + table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE"); + + // table cells have a list of paragraphs; there is an initial + // paragraph created when the cell is created. If you create a + // paragraph in the document to put in the cell, it will also + // appear in the document following the table, which is probably + // not the desired result. + XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0); + + XWPFRun r1 = p1.createRun(); + r1.setBold(true); + r1.setText("The quick brown fox"); + r1.setItalic(true); + r1.setFontFamily("Courier"); + r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); + r1.setTextPosition(100); + + table.getRow(2).getCell(2).setText("only text"); + + FileOutputStream out = new FileOutputStream("simpleTable.docx"); + doc.write(out); + out.close(); + } + + /** + * Create a table with some row and column styling. I "manually" add the + * style name to the table, but don't check to see if the style actually + * exists in the document. Since I'm creating it from scratch, it obviously + * won't exist. When opened in MS Word, the table style becomes "Normal". + * I manually set alternating row colors. This could be done using Themes, + * but that's left as an exercise for the reader. The cells in the last + * column of the table have 10pt. "Courier" font. + * I make no claims that this is the "right" way to do it, but it worked + * for me. Given the scarcity of XWPF examples, I thought this may prove + * instructive and give you ideas for your own solutions. + + * @throws Exception + */ + public static void createStyledTable() throws Exception { + // Create a new document from scratch + XWPFDocument doc = new XWPFDocument(); + // -- OR -- + // open an existing empty document with styles already defined + //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx")); + + // Create a new table with 6 rows and 3 columns + int nRows = 6; + int nCols = 3; + XWPFTable table = doc.createTable(nRows, nCols); + + // Set the table style. If the style is not defined, the table style + // will become "Normal". + CTTblPr tblPr = table.getCTTbl().getTblPr(); + CTString styleStr = tblPr.addNewTblStyle(); + styleStr.setVal("StyledTable"); + + // Get a list of the rows in the table + List rows = table.getRows(); + int rowCt = 0; + int colCt = 0; + for (XWPFTableRow row : rows) { + // get table row properties (trPr) + CTTrPr trPr = row.getCtRow().addNewTrPr(); + // set row height; units = twentieth of a point, 360 = 0.25" + CTHeight ht = trPr.addNewTrHeight(); + ht.setVal(BigInteger.valueOf(360)); + + // get the cells in this row + List cells = row.getTableCells(); + // add content to each cell + for (XWPFTableCell cell : cells) { + // get a table cell properties element (tcPr) + CTTcPr tcpr = cell.getCTTc().addNewTcPr(); + // set vertical alignment to "center" + CTVerticalJc va = tcpr.addNewVAlign(); + va.setVal(STVerticalJc.CENTER); + + // create cell color element + CTShd ctshd = tcpr.addNewShd(); + ctshd.setColor("auto"); + ctshd.setVal(STShd.CLEAR); + if (rowCt == 0) { + // header row + ctshd.setFill("A7BFDE"); + } + else if (rowCt % 2 == 0) { + // even row + ctshd.setFill("D3DFEE"); + } + else { + // odd row + ctshd.setFill("EDF2F8"); + } + + // get 1st paragraph in cell's paragraph list + XWPFParagraph para = cell.getParagraphs().get(0); + // create a run to contain the content + XWPFRun rh = para.createRun(); + // style cell as desired + if (colCt == nCols - 1) { + // last column is 10pt Courier + rh.setFontSize(10); + rh.setFontFamily("Courier"); + } + if (rowCt == 0) { + // header row + rh.setText("header row, col " + colCt); + rh.setBold(true); + para.setAlignment(ParagraphAlignment.CENTER); + } + else if (rowCt % 2 == 0) { + // even row + rh.setText("row " + rowCt + ", col " + colCt); + para.setAlignment(ParagraphAlignment.LEFT); + } + else { + // odd row + rh.setText("row " + rowCt + ", col " + colCt); + para.setAlignment(ParagraphAlignment.LEFT); + } + colCt++; + } // for cell + colCt = 0; + rowCt++; + } // for row + + // write the file + FileOutputStream out = new FileOutputStream("styledTable.docx"); + doc.write(out); + out.close(); + } + +} diff --git a/poi-examples/src/main/java/poi/xwpf/usermodel/UpdateEmbeddedDoc.java b/poi-examples/src/main/java/poi/xwpf/usermodel/UpdateEmbeddedDoc.java new file mode 100644 index 0000000000..ffdb7e2049 --- /dev/null +++ b/poi-examples/src/main/java/poi/xwpf/usermodel/UpdateEmbeddedDoc.java @@ -0,0 +1,219 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xwpf.usermodel; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.List; +import java.util.Iterator; + +import junit.framework.Assert; +import org.apache.poi.openxml4j.opc.PackagePart; +import org.apache.poi.openxml4j.exceptions.OpenXML4JException; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Cell; + +/** + * Tests whether it is possible to successfully update an Excel workbook that is + * embedded into a WordprocessingML document. Note that the test has currently + * only been conducted with a binary Excel workbook and NOT yet with a + * SpreadsheetML workbook embedded into the document. + * + *

    + * This code was successfully tested with the following file from the POI test collection: + * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx + *

    + * + * @author Mark B + */ +public class UpdateEmbeddedDoc { + + private XWPFDocument doc = null; + private File docFile = null; + + private static final int SHEET_NUM = 0; + private static final int ROW_NUM = 0; + private static final int CELL_NUM = 0; + private static final double NEW_VALUE = 100.98D; + private static final String BINARY_EXTENSION = "xls"; + private static final String OPENXML_EXTENSION = "xlsx"; + + /** + * Create a new instance of the UpdateEmbeddedDoc class using the following + * parameters; + * + * @param filename An instance of the String class that encapsulates the name + * of and path to a WordprocessingML Word document that contains an + * embedded binary Excel workbook. + * @throws java.io.FileNotFoundException Thrown if the file cannot be found + * on the underlying file system. + * @throws java.io.IOException Thrown if a problem occurs in the underlying + * file system. + */ + public UpdateEmbeddedDoc(String filename) throws FileNotFoundException, IOException { + this.docFile = new File(filename); + FileInputStream fis = null; + if (!this.docFile.exists()) { + throw new FileNotFoundException("The Word dcoument " + + filename + + " does not exist."); + } + try { + + // Open the Word document file and instantiate the XWPFDocument + // class. + fis = new FileInputStream(this.docFile); + this.doc = new XWPFDocument(fis); + } finally { + if (fis != null) { + try { + fis.close(); + fis = null; + } catch (IOException ioEx) { + System.out.println("IOException caught trying to close " + + "FileInputStream in the constructor of " + + "UpdateEmbeddedDoc."); + } + } + } + } + + /** + * Called to update the embedded Excel workbook. As the format and structire + * of the workbook are known in advance, all this code attempts to do is + * write a new value into the first cell on the first row of the first + * worksheet. Prior to executing this method, that cell will contain the + * value 1. + * + * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException + * Rather + * than use the specific classes (HSSF/XSSF) to handle the embedded + * workbook this method uses those defeined in the SS stream. As + * a result, it might be the case that a SpreadsheetML file is + * opened for processing, throwing this exception if that file is + * invalid. + * @throws java.io.IOException Thrown if a problem occurs in the underlying + * file system. + */ + public void updateEmbeddedDoc() throws OpenXML4JException, IOException { + Workbook workbook = null; + Sheet sheet = null; + Row row = null; + Cell cell = null; + PackagePart pPart = null; + Iterator pIter = null; + List embeddedDocs = this.doc.getAllEmbedds(); + if (embeddedDocs != null && !embeddedDocs.isEmpty()) { + pIter = embeddedDocs.iterator(); + while (pIter.hasNext()) { + pPart = pIter.next(); + if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || + pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { + + // Get an InputStream from the pacage part and pass that + // to the create method of the WorkbookFactory class. Update + // the resulting Workbook and then stream that out again + // using an OutputStream obtained from the same PackagePart. + workbook = WorkbookFactory.create(pPart.getInputStream()); + sheet = workbook.getSheetAt(SHEET_NUM); + row = sheet.getRow(ROW_NUM); + cell = row.getCell(CELL_NUM); + cell.setCellValue(NEW_VALUE); + workbook.write(pPart.getOutputStream()); + } + } + + // Finally, write the newly modified Word document out to file. + this.doc.write(new FileOutputStream(this.docFile)); + } + } + + /** + * Called to test whether or not the embedded workbook was correctly + * updated. This method simply recovers the first cell from the first row + * of the first workbook and tests the value it contains. + *

    + * Note that execution will not continue up to the assertion as the + * embedded workbook is now corrupted and causes an IllegalArgumentException + * with the following message + *

    + * java.lang.IllegalArgumentException: Your InputStream was neither an + * OLE2 stream, nor an OOXML stream + *

    + * to be thrown when the WorkbookFactory.createWorkbook(InputStream) method + * is executed. + * + * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException + * Rather + * than use the specific classes (HSSF/XSSF) to handle the embedded + * workbook this method uses those defeined in the SS stream. As + * a result, it might be the case that a SpreadsheetML file is + * opened for processing, throwing this exception if that file is + * invalid. + * @throws java.io.IOException Thrown if a problem occurs in the underlying + * file system. + */ + public void checkUpdatedDoc() throws OpenXML4JException, IOException { + Workbook workbook = null; + Sheet sheet = null; + Row row = null; + Cell cell = null; + PackagePart pPart = null; + Iterator pIter = null; + List embeddedDocs = this.doc.getAllEmbedds(); + if (embeddedDocs != null && !embeddedDocs.isEmpty()) { + pIter = embeddedDocs.iterator(); + while (pIter.hasNext()) { + pPart = pIter.next(); + if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || + pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { + workbook = WorkbookFactory.create(pPart.getInputStream()); + sheet = workbook.getSheetAt(SHEET_NUM); + row = sheet.getRow(ROW_NUM); + cell = row.getCell(CELL_NUM); + Assert.assertEquals(cell.getNumericCellValue(), NEW_VALUE); + } + } + } + } + + /** + * Code to test updating of the embedded Excel workbook. + * + * @param args + */ + public static void main(String[] args) { + try { + UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]); + ued.updateEmbeddedDoc(); + ued.checkUpdatedDoc(); + } catch (Exception ex) { + System.out.println(ex.getClass().getName()); + System.out.println(ex.getMessage()); + ex.printStackTrace(System.out); + } + } +} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java b/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java deleted file mode 100644 index 1fb9d48ef2..0000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java +++ /dev/null @@ -1,542 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.apache.poi.hpsf.HPSFRuntimeException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Util; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.TempFile; - -/** - *

    This class copies a POI file system to a new file and compares the copy - * with the original.

    - * - *

    Property set streams are copied logically, i.e. the application - * establishes a {@link org.apache.poi.hpsf.PropertySet} of an original property - * set, creates a {@link org.apache.poi.hpsf.MutablePropertySet} from the - * {@link org.apache.poi.hpsf.PropertySet} and writes the - * {@link org.apache.poi.hpsf.MutablePropertySet} to the destination POI file - * system. - Streams which are no property set streams are copied bit by - * bit.

    - * - *

    The comparison of the POI file systems is done logically. That means that - * the two disk files containing the POI file systems do not need to be - * exactly identical. However, both POI file systems must contain the same - * files, and most of these files must be bitwise identical. Property set - * streams, however, are compared logically: they must have the same sections - * with the same attributs, and the sections must contain the same properties. - * Details like the ordering of the properties do not matter.

    - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class CopyCompare -{ - /** - *

    Runs the example program. The application expects one or two - * arguments:

    - * - *
      - * - *
    1. The first argument is the disk file name of the POI filesystem to - * copy.

    2. - * - *
    3. The second argument is optional. If it is given, it is the name of - * a disk file the copy of the POI filesystem will be written to. If it is - * not given, the copy will be written to a temporary file which will be - * deleted at the end of the program.

    4. - * - *
    - * - * @param args Command-line arguments. - * @exception MarkUnsupportedException if a POI document stream does not - * support the mark() operation. - * @exception NoPropertySetStreamException if the application tries to - * create a property set from a POI document stream that is not a property - * set stream. - * @exception IOException if any I/O exception occurs. - * @exception UnsupportedEncodingException if a character encoding is not - * supported. - */ - public static void main(final String[] args) - throws NoPropertySetStreamException, MarkUnsupportedException, - UnsupportedEncodingException, IOException - { - String originalFileName = null; - String copyFileName = null; - - /* Check the command-line arguments. */ - if (args.length == 1) - { - originalFileName = args[0]; - File f = TempFile.createTempFile("CopyOfPOIFileSystem-", ".ole2"); - f.deleteOnExit(); - copyFileName = f.getAbsolutePath(); - } - else if (args.length == 2) - { - originalFileName = args[0]; - copyFileName = args[1]; - } - else - { - System.err.println("Usage: " + CopyCompare.class.getName() + - "originPOIFS [copyPOIFS]"); - System.exit(1); - } - - /* Read the origin POIFS using the eventing API. The real work is done - * in the class CopyFile which is registered here as a POIFSReader. */ - final POIFSReader r = new POIFSReader(); - final CopyFile cf = new CopyFile(copyFileName); - r.registerListener(cf); - r.read(new FileInputStream(originalFileName)); - - /* Write the new POIFS to disk. */ - cf.close(); - - /* Read all documents from the original POI file system and compare them - * with the equivalent document from the copy. */ - final POIFSFileSystem opfs = - new POIFSFileSystem(new FileInputStream(originalFileName)); - final POIFSFileSystem cpfs = - new POIFSFileSystem(new FileInputStream(copyFileName)); - - final DirectoryEntry oRoot = opfs.getRoot(); - final DirectoryEntry cRoot = cpfs.getRoot(); - final StringBuffer messages = new StringBuffer(); - if (equal(oRoot, cRoot, messages)) - System.out.println("Equal"); - else - System.out.println("Not equal: " + messages.toString()); - } - - - - /** - *

    Compares two {@link DirectoryEntry} instances of a POI file system. - * The directories must contain the same streams with the same names and - * contents.

    - * - * @param d1 The first directory. - * @param d2 The second directory. - * @param msg The method may append human-readable comparison messages to - * this string buffer. - * @return true if the directories are equal, else - * false. - * @exception MarkUnsupportedException if a POI document stream does not - * support the mark() operation. - * @exception NoPropertySetStreamException if the application tries to - * create a property set from a POI document stream that is not a property - * set stream. - * @throws UnsupportedEncodingException - * @exception IOException if any I/O exception occurs. - */ - private static boolean equal(final DirectoryEntry d1, - final DirectoryEntry d2, - final StringBuffer msg) - throws NoPropertySetStreamException, MarkUnsupportedException, - UnsupportedEncodingException, IOException - { - boolean equal = true; - /* Iterate over d1 and compare each entry with its counterpart in d2. */ - for (final Iterator i = d1.getEntries(); equal && i.hasNext();) - { - final Entry e1 = (Entry) i.next(); - final String n1 = e1.getName(); - Entry e2 = null; - try - { - e2 = d2.getEntry(n1); - } - catch (FileNotFoundException ex) - { - msg.append("Document \"" + e1 + "\" exists, document \"" + - e2 + "\" does not.\n"); - equal = false; - break; - } - - if (e1.isDirectoryEntry() && e2.isDirectoryEntry()) - equal = equal((DirectoryEntry) e1, (DirectoryEntry) e2, msg); - else if (e1.isDocumentEntry() && e2.isDocumentEntry()) - equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg); - else - { - msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " + - "document while the other one is a directory.\n"); - equal = false; - } - } - - /* Iterate over d2 just to make sure that there are no entries in d2 - * that are not in d1. */ - for (final Iterator i = d2.getEntries(); equal && i.hasNext();) - { - final Entry e2 = (Entry) i.next(); - final String n2 = e2.getName(); - Entry e1 = null; - try - { - e1 = d1.getEntry(n2); - } - catch (FileNotFoundException ex) - { - msg.append("Document \"" + e2 + "\" exitsts, document \"" + - e1 + "\" does not.\n"); - equal = false; - break; - } - } - return equal; - } - - - - /** - *

    Compares two {@link DocumentEntry} instances of a POI file system. - * Documents that are not property set streams must be bitwise identical. - * Property set streams must be logically equal.

    - * - * @param d1 The first document. - * @param d2 The second document. - * @param msg The method may append human-readable comparison messages to - * this string buffer. - * @return true if the documents are equal, else - * false. - * @exception MarkUnsupportedException if a POI document stream does not - * support the mark() operation. - * @exception NoPropertySetStreamException if the application tries to - * create a property set from a POI document stream that is not a property - * set stream. - * @throws UnsupportedEncodingException - * @exception IOException if any I/O exception occurs. - */ - private static boolean equal(final DocumentEntry d1, final DocumentEntry d2, - final StringBuffer msg) - throws NoPropertySetStreamException, MarkUnsupportedException, - UnsupportedEncodingException, IOException - { - boolean equal = true; - final DocumentInputStream dis1 = new DocumentInputStream(d1); - final DocumentInputStream dis2 = new DocumentInputStream(d2); - if (PropertySet.isPropertySetStream(dis1) && - PropertySet.isPropertySetStream(dis2)) - { - final PropertySet ps1 = PropertySetFactory.create(dis1); - final PropertySet ps2 = PropertySetFactory.create(dis2); - equal = ps1.equals(ps2); - if (!equal) - { - msg.append("Property sets are not equal.\n"); - return equal; - } - } - else - { - int i1; - int i2; - do - { - i1 = dis1.read(); - i2 = dis2.read(); - if (i1 != i2) - { - equal = false; - msg.append("Documents are not equal.\n"); - break; - } - } - while (equal && i1 == -1); - } - return true; - } - - - - /** - *

    This class does all the work. Its method {@link - * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each file in - * the original POI file system. Except for property set streams it copies - * everything unmodified to the destination POI filesystem. Property set - * streams are copied by creating a new {@link PropertySet} from the - * original property set by using the {@link - * MutablePropertySet#MutablePropertySet(PropertySet)} constructor.

    - */ - static class CopyFile implements POIFSReaderListener - { - String dstName; - OutputStream out; - POIFSFileSystem poiFs; - - - /** - *

    The constructor of a {@link CopyFile} instance creates the target - * POIFS. It also stores the name of the file the POIFS will be written - * to once it is complete.

    - * - * @param dstName The name of the disk file the destination POIFS is to - * be written to. - */ - public CopyFile(final String dstName) - { - this.dstName = dstName; - poiFs = new POIFSFileSystem(); - } - - - /** - *

    The method is called by POI's eventing API for each file in the - * origin POIFS.

    - */ - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - /* The following declarations are shortcuts for accessing the - * "event" object. */ - final POIFSDocumentPath path = event.getPath(); - final String name = event.getName(); - final DocumentInputStream stream = event.getStream(); - - Throwable t = null; - - try - { - /* Find out whether the current document is a property set - * stream or not. */ - if (PropertySet.isPropertySetStream(stream)) - { - /* Yes, the current document is a property set stream. - * Let's create a PropertySet instance from it. */ - PropertySet ps = null; - try - { - ps = PropertySetFactory.create(stream); - } - catch (NoPropertySetStreamException ex) - { - /* This exception will not be thrown because we already - * checked above. */ - } - - /* Copy the property set to the destination POI file - * system. */ - copy(poiFs, path, name, ps); - } - else - /* No, the current document is not a property set stream. We - * copy it unmodified to the destination POIFS. */ - copy(poiFs, event.getPath(), event.getName(), stream); - } - catch (MarkUnsupportedException ex) - { - t = ex; - } - catch (IOException ex) - { - t = ex; - } - catch (WritingNotSupportedException ex) - { - t = ex; - } - - /* According to the definition of the processPOIFSReaderEvent method - * we cannot pass checked exceptions to the caller. The following - * lines check whether a checked exception occured and throws an - * unchecked exception. The message of that exception is that of - * the underlying checked exception. */ - if (t != null) - { - throw new HPSFRuntimeException - ("Could not read file \"" + path + "/" + name + - "\". Reason: " + Util.toString(t)); - } - } - - - - /** - *

    Writes a {@link PropertySet} to a POI filesystem.

    - * - * @param poiFs The POI filesystem to write to. - * @param path The file's path in the POI filesystem. - * @param name The file's name in the POI filesystem. - * @param ps The property set to write. - * @throws WritingNotSupportedException - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet ps) - throws WritingNotSupportedException, IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final MutablePropertySet mps = new MutablePropertySet(ps); - de.createDocument(name, mps.toInputStream()); - } - - - - /** - *

    Copies the bytes from a {@link DocumentInputStream} to a new - * stream in a POI filesystem.

    - * - * @param poiFs The POI filesystem to write to. - * @param path The source document's path. - * @param name The source document's name. - * @param stream The stream containing the source document. - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final DocumentInputStream stream) throws IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - int c; - while ((c = stream.read()) != -1) - out.write(c); - stream.close(); - out.close(); - final InputStream in = - new ByteArrayInputStream(out.toByteArray()); - de.createDocument(name, in); - } - - - /** - *

    Writes the POI file system to a disk file.

    - * - * @throws FileNotFoundException - * @throws IOException - */ - public void close() throws FileNotFoundException, IOException - { - out = new FileOutputStream(dstName); - poiFs.writeFilesystem(out); - out.close(); - } - - - - /** Contains the directory paths that have already been created in the - * output POI filesystem and maps them to their corresponding - * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ - private final Map paths = new HashMap(); - - - - /** - *

    Ensures that the directory hierarchy for a document in a POI - * fileystem is in place. When a document is to be created somewhere in - * a POI filesystem its directory must be created first. This method - * creates all directories between the POI filesystem root and the - * directory the document should belong to which do not yet exist.

    - * - *

    Unfortunately POI does not offer a simple method to interrogate - * the POIFS whether a certain child node (file or directory) exists in - * a directory. However, since we always start with an empty POIFS which - * contains the root directory only and since each directory in the - * POIFS is created by this method we can maintain the POIFS's directory - * hierarchy ourselves: The {@link DirectoryEntry} of each directory - * created is stored in a {@link Map}. The directories' path names map - * to the corresponding {@link DirectoryEntry} instances.

    - * - * @param poiFs The POI filesystem the directory hierarchy is created - * in, if needed. - * @param path The document's path. This method creates those directory - * components of this hierarchy which do not yet exist. - * @return The directory entry of the document path's parent. The caller - * should use this {@link DirectoryEntry} to create documents in it. - */ - public DirectoryEntry getPath(final POIFSFileSystem poiFs, - final POIFSDocumentPath path) - { - try - { - /* Check whether this directory has already been created. */ - final String s = path.toString(); - DirectoryEntry de = (DirectoryEntry) paths.get(s); - if (de != null) - /* Yes: return the corresponding DirectoryEntry. */ - return de; - - /* No: We have to create the directory - or return the root's - * DirectoryEntry. */ - int l = path.length(); - if (l == 0) - /* Get the root directory. It does not have to be created - * since it always exists in a POIFS. */ - de = poiFs.getRoot(); - else - { - /* Create a subordinate directory. The first step is to - * ensure that the parent directory exists: */ - de = getPath(poiFs, path.getParent()); - /* Now create the target directory: */ - de = de.createDirectory(path.getComponent - (path.length() - 1)); - } - paths.put(s, de); - return de; - } - catch (IOException ex) - { - /* This exception will be thrown if the directory already - * exists. However, since we have full control about directory - * creation we can ensure that this will never happen. */ - ex.printStackTrace(System.err); - throw new RuntimeException(ex.toString()); - /* FIXME (2): Replace the previous line by the following once we - * no longer need JDK 1.3 compatibility. */ - // throw new RuntimeException(ex); - } - } - } - -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java b/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java deleted file mode 100644 index 66c1cbdb0e..0000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java +++ /dev/null @@ -1,194 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Date; - -import org.apache.poi.hpsf.CustomProperties; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - *

    This is a sample application showing how to easily modify properties in - * the summary information and in the document summary information. The - * application reads the name of a POI filesystem from the command line and - * performs the following actions:

    - * - *
      - * - *
    • Open the POI filesystem.

    • - * - *
    • Read the summary information.

    • - * - *
    • Read and print the "author" property.

    • - * - *
    • Change the author to "Rainer Klute".

    • - * - *
    • Read the document summary information.

    • - * - *
    • Read and print the "category" property.

    • - * - *
    • Change the category to "POI example".

    • - * - *
    • Read the custom properties (if available).

    • - * - *
    • Insert a new custom property.

    • - * - *
    • Write the custom properties back to the document summary - * information.

    • - * - *
    • Write the summary information to the POI filesystem.

    • - * - *
    • Write the document summary information to the POI filesystem.

    • - * - *
    • Write the POI filesystem back to the original file.

    • - * - * - * - * @author Rainer Klute klute@rainer-klute.de - */ -public class ModifyDocumentSummaryInformation { - - /** - *

      Main method - see class description.

      - * - * @param args The command-line parameters. - * @throws IOException - * @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(); - } -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java b/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java deleted file mode 100644 index bf6bcd1f8f..0000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.util.HexDump; - -/** - *

      Sample application showing how to read a document's custom property set. - * Call it with the document's file name as command-line parameter.

      - * - *

      Explanations can be found in the HPSF HOW-TO.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class ReadCustomPropertySets -{ - - /** - *

      Runs the example program.

      - * - * @param args Command-line arguments (unused). - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) - throws IOException - { - final String filename = args[0]; - POIFSReader r = new POIFSReader(); - - /* Register a listener for *all* documents. */ - r.registerListener(new MyPOIFSReaderListener()); - r.read(new FileInputStream(filename)); - } - - - static class MyPOIFSReaderListener implements POIFSReaderListener - { - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - PropertySet ps = null; - try - { - ps = PropertySetFactory.create(event.getStream()); - } - catch (NoPropertySetStreamException ex) - { - out("No property set stream: \"" + event.getPath() + - event.getName() + "\""); - return; - } - catch (Exception ex) - { - throw new RuntimeException - ("Property set stream \"" + - event.getPath() + event.getName() + "\": " + ex); - } - - /* Print the name of the property set stream: */ - out("Property set stream \"" + event.getPath() + - event.getName() + "\":"); - - /* Print the number of sections: */ - final long sectionCount = ps.getSectionCount(); - out(" No. of sections: " + sectionCount); - - /* Print the list of sections: */ - List sections = ps.getSections(); - int nr = 0; - for (Iterator i = sections.iterator(); i.hasNext();) - { - /* Print a single section: */ - Section sec = (Section) i.next(); - out(" Section " + nr++ + ":"); - String s = hex(sec.getFormatID().getBytes()); - s = s.substring(0, s.length() - 1); - out(" Format ID: " + s); - - /* Print the number of properties in this section. */ - int propertyCount = sec.getPropertyCount(); - out(" No. of properties: " + propertyCount); - - /* Print the properties: */ - Property[] properties = sec.getProperties(); - for (int i2 = 0; i2 < properties.length; i2++) - { - /* Print a single property: */ - Property p = properties[i2]; - long id = p.getID(); - long type = p.getType(); - Object value = p.getValue(); - out(" Property ID: " + id + ", type: " + type + - ", value: " + value); - } - } - } - } - - static void out(final String msg) - { - System.out.println(msg); - } - - static String hex(final byte[] bytes) - { - return HexDump.dump(bytes, 0L, 0); - } - -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java b/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java deleted file mode 100644 index c036d222b6..0000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.FileInputStream; -import java.io.IOException; - -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; - -/** - *

      Sample application showing how to read a OLE 2 document's - * title. Call it with the document's file name as command line - * parameter.

      - * - *

      Explanations can be found in the HPSF HOW-TO.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class ReadTitle -{ - /** - *

      Runs the example program.

      - * - * @param args Command-line arguments. The first command-line argument must - * be the name of a POI filesystem to read. - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) throws IOException - { - final String filename = args[0]; - POIFSReader r = new POIFSReader(); - r.registerListener(new MyPOIFSReaderListener(), - "\005SummaryInformation"); - r.read(new FileInputStream(filename)); - } - - - static class MyPOIFSReaderListener implements POIFSReaderListener - { - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - SummaryInformation si = null; - try - { - si = (SummaryInformation) - PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { - throw new RuntimeException - ("Property set stream \"" + - event.getPath() + event.getName() + "\": " + ex); - } - final String title = si.getTitle(); - if (title != null) - System.out.println("Title: \"" + title + "\""); - else - System.out.println("Document has no title."); - } - } - -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java b/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java deleted file mode 100644 index 00749ab4d2..0000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java +++ /dev/null @@ -1,423 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.hpsf.HPSFRuntimeException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.MutableSection; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.Util; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - *

      This class is a sample application which shows how to write or modify the - * author and title property of an OLE 2 document. This could be done in two - * different ways:

      - * - *
        - * - *
      • The first approach is to open the OLE 2 file as a POI filesystem - * (see class {@link POIFSFileSystem}), read the summary information property - * set (see classes {@link SummaryInformation} and {@link PropertySet}), write - * the author and title properties into it and write the property set back into - * the POI filesystem.

      • - * - *
      • The second approach does not modify the original POI filesystem, but - * instead creates a new one. All documents from the original POIFS are copied - * to the destination POIFS, except for the summary information stream. The - * latter is modified by setting the author and title property before writing - * it to the destination POIFS. It there are several summary information streams - * in the original POIFS - e.g. in subordinate directories - they are modified - * just the same.

      • - * - *
      - * - *

      This sample application takes the second approach. It expects the name of - * the existing POI filesystem's name as its first command-line parameter and - * the name of the output POIFS as the second command-line argument. The - * program then works as described above: It copies nearly all documents - * unmodified from the input POI filesystem to the output POI filesystem. If it - * encounters a summary information stream it reads its properties. Then it sets - * the "author" and "title" properties to new values and writes the modified - * summary information stream into the output file.

      - * - *

      Further explanations can be found in the HPSF HOW-TO.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class WriteAuthorAndTitle -{ - /** - *

      Runs the example program.

      - * - * @param args Command-line arguments. The first command-line argument must - * be the name of a POI filesystem to read. - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) throws IOException - { - /* Check whether we have exactly two command-line arguments. */ - if (args.length != 2) - { - System.err.println("Usage: " + WriteAuthorAndTitle.class.getName() + - " originPOIFS destinationPOIFS"); - System.exit(1); - } - - /* Read the names of the origin and destination POI filesystems. */ - final String srcName = args[0]; - final String dstName = args[1]; - - /* Read the origin POIFS using the eventing API. The real work is done - * in the class ModifySICopyTheRest which is registered here as a - * POIFSReader. */ - final POIFSReader r = new POIFSReader(); - final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName); - r.registerListener(msrl); - r.read(new FileInputStream(srcName)); - - /* Write the new POIFS to disk. */ - msrl.close(); - } - - - - /** - *

      This class does all the work. As its name implies it modifies a - * summary information property set and copies everything else unmodified - * to the destination POI filesystem. Since an instance of it is registered - * as a {@link POIFSReader} its method {@link - * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each document - * in the origin POIFS.

      - */ - static class ModifySICopyTheRest implements POIFSReaderListener - { - String dstName; - OutputStream out; - POIFSFileSystem poiFs; - - - /** - *

      The constructor of a {@link ModifySICopyTheRest} instance creates - * the target POIFS. It also stores the name of the file the POIFS will - * be written to once it is complete.

      - * - * @param dstName The name of the disk file the destination POIFS is to - * be written to. - */ - public ModifySICopyTheRest(final String dstName) - { - this.dstName = dstName; - poiFs = new POIFSFileSystem(); - } - - - /** - *

      The method is called by POI's eventing API for each file in the - * origin POIFS.

      - */ - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - /* The following declarations are shortcuts for accessing the - * "event" object. */ - final POIFSDocumentPath path = event.getPath(); - final String name = event.getName(); - final DocumentInputStream stream = event.getStream(); - - Throwable t = null; - - try - { - /* Find out whether the current document is a property set - * stream or not. */ - if (PropertySet.isPropertySetStream(stream)) - { - /* Yes, the current document is a property set stream. - * Let's create a PropertySet instance from it. */ - PropertySet ps = null; - try - { - ps = PropertySetFactory.create(stream); - } - catch (NoPropertySetStreamException ex) - { - /* This exception will not be thrown because we already - * checked above. */ - } - - /* Now we know that we really have a property set. The next - * step is to find out whether it is a summary information - * or not. */ - if (ps.isSummaryInformation()) - /* Yes, it is a summary information. We will modify it - * and write the result to the destination POIFS. */ - editSI(poiFs, path, name, ps); - else - /* No, it is not a summary information. We don't care - * about its internals and copy it unmodified to the - * destination POIFS. */ - copy(poiFs, path, name, ps); - } - else - /* No, the current document is not a property set stream. We - * copy it unmodified to the destination POIFS. */ - copy(poiFs, event.getPath(), event.getName(), stream); - } - catch (MarkUnsupportedException ex) - { - t = ex; - } - catch (IOException ex) - { - t = ex; - } - catch (WritingNotSupportedException ex) - { - t = ex; - } - - /* According to the definition of the processPOIFSReaderEvent method - * we cannot pass checked exceptions to the caller. The following - * lines check whether a checked exception occured and throws an - * unchecked exception. The message of that exception is that of - * the underlying checked exception. */ - if (t != null) - { - throw new HPSFRuntimeException - ("Could not read file \"" + path + "/" + name + - "\". Reason: " + Util.toString(t)); - } - } - - - /** - *

      Receives a summary information property set modifies (or creates) - * its "author" and "title" properties and writes the result under the - * same path and name as the origin to a destination POI filesystem.

      - * - * @param poiFs The POI filesystem to write to. - * @param path The original (and destination) stream's path. - * @param name The original (and destination) stream's name. - * @param si The property set. It should be a summary information - * property set. - * @throws IOException - * @throws WritingNotSupportedException - */ - public void editSI(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet si) - throws WritingNotSupportedException, IOException - - { - /* Get the directory entry for the target stream. */ - final DirectoryEntry de = getPath(poiFs, path); - - /* Create a mutable property set as a copy of the original read-only - * property set. */ - final MutablePropertySet mps = new MutablePropertySet(si); - - /* Retrieve the section containing the properties to modify. A - * summary information property set contains exactly one section. */ - final MutableSection s = - (MutableSection) mps.getSections().get(0); - - /* Set the properties. */ - s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR, - "Rainer Klute"); - s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR, - "Test"); - - /* Create an input stream containing the bytes the property set - * stream consists of. */ - final InputStream pss = mps.toInputStream(); - - /* Write the property set stream to the POIFS. */ - de.createDocument(name, pss); - } - - - /** - *

      Writes a {@link PropertySet} to a POI filesystem. This method is - * simpler than {@link #editSI} because the origin property set has just - * to be copied.

      - * - * @param poiFs The POI filesystem to write to. - * @param path The file's path in the POI filesystem. - * @param name The file's name in the POI filesystem. - * @param ps The property set to write. - * @throws WritingNotSupportedException - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet ps) - throws WritingNotSupportedException, IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final MutablePropertySet mps = new MutablePropertySet(ps); - de.createDocument(name, mps.toInputStream()); - } - - - - /** - *

      Copies the bytes from a {@link DocumentInputStream} to a new - * stream in a POI filesystem.

      - * - * @param poiFs The POI filesystem to write to. - * @param path The source document's path. - * @param name The source document's name. - * @param stream The stream containing the source document. - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final DocumentInputStream stream) throws IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - int c; - while ((c = stream.read()) != -1) - out.write(c); - stream.close(); - out.close(); - final InputStream in = - new ByteArrayInputStream(out.toByteArray()); - de.createDocument(name, in); - } - - - /** - *

      Writes the POI file system to a disk file.

      - * - * @throws FileNotFoundException - * @throws IOException - */ - public void close() throws FileNotFoundException, IOException - { - out = new FileOutputStream(dstName); - poiFs.writeFilesystem(out); - out.close(); - } - - - - /** Contains the directory paths that have already been created in the - * output POI filesystem and maps them to their corresponding - * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ - private final Map paths = new HashMap(); - - - - /** - *

      Ensures that the directory hierarchy for a document in a POI - * fileystem is in place. When a document is to be created somewhere in - * a POI filesystem its directory must be created first. This method - * creates all directories between the POI filesystem root and the - * directory the document should belong to which do not yet exist.

      - * - *

      Unfortunately POI does not offer a simple method to interrogate - * the POIFS whether a certain child node (file or directory) exists in - * a directory. However, since we always start with an empty POIFS which - * contains the root directory only and since each directory in the - * POIFS is created by this method we can maintain the POIFS's directory - * hierarchy ourselves: The {@link DirectoryEntry} of each directory - * created is stored in a {@link Map}. The directories' path names map - * to the corresponding {@link DirectoryEntry} instances.

      - * - * @param poiFs The POI filesystem the directory hierarchy is created - * in, if needed. - * @param path The document's path. This method creates those directory - * components of this hierarchy which do not yet exist. - * @return The directory entry of the document path's parent. The caller - * should use this {@link DirectoryEntry} to create documents in it. - */ - public DirectoryEntry getPath(final POIFSFileSystem poiFs, - final POIFSDocumentPath path) - { - try - { - /* Check whether this directory has already been created. */ - final String s = path.toString(); - DirectoryEntry de = (DirectoryEntry) paths.get(s); - if (de != null) - /* Yes: return the corresponding DirectoryEntry. */ - return de; - - /* No: We have to create the directory - or return the root's - * DirectoryEntry. */ - int l = path.length(); - if (l == 0) - /* Get the root directory. It does not have to be created - * since it always exists in a POIFS. */ - de = poiFs.getRoot(); - else - { - /* Create a subordinate directory. The first step is to - * ensure that the parent directory exists: */ - de = getPath(poiFs, path.getParent()); - /* Now create the target directory: */ - de = de.createDirectory(path.getComponent - (path.length() - 1)); - } - paths.put(s, de); - return de; - } - catch (IOException ex) - { - /* This exception will be thrown if the directory already - * exists. However, since we have full control about directory - * creation we can ensure that this will never happen. */ - ex.printStackTrace(System.err); - throw new RuntimeException(ex.toString()); - /* FIXME (2): Replace the previous line by the following once we - * no longer need JDK 1.3 compatibility. */ - // throw new RuntimeException(ex); - } - } - } - -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java b/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java deleted file mode 100644 index 22e1f69cdd..0000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hpsf.MutableProperty; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.MutableSection; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.apache.poi.hpsf.wellknown.SectionIDMap; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - *

      This class is a simple sample application showing how to create a property - * set and write it to disk.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class WriteTitle -{ - /** - *

      Runs the example program.

      - * - * @param args Command-line arguments. The first and only command-line - * argument is the name of the POI file system to create. - * @throws IOException if any I/O exception occurs. - * @throws WritingNotSupportedException if HPSF does not (yet) support - * writing a certain property type. - */ - 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)); - } - -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java b/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java deleted file mode 100644 index 25f1eab9c5..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java +++ /dev/null @@ -1,515 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.*; -import org.apache.poi.hslf.model.*; -import org.apache.poi.hslf.record.TextHeaderAtom; - -import java.io.IOException; -import java.io.FileOutputStream; -import java.awt.*; - -/** - * Presentation for Fast Feather Track on ApacheconEU 2008 - * - * @author Yegor Kozlov - */ -public final class ApacheconEU08 { - - public static void main(String[] args) throws IOException { - SlideShow ppt = new SlideShow(); - ppt.setPageSize(new Dimension(720, 540)); - - slide1(ppt); - slide2(ppt); - slide3(ppt); - slide4(ppt); - slide5(ppt); - slide6(ppt); - slide7(ppt); - slide8(ppt); - slide9(ppt); - slide10(ppt); - slide11(ppt); - slide12(ppt); - - FileOutputStream out = new FileOutputStream("apachecon_eu_08.ppt"); - ppt.write(out); - out.close(); - - } - - public static void slide1(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.CENTER_TITLE_TYPE); - tr1.setText("POI-HSLF"); - box1.setAnchor(new Rectangle(54, 78, 612, 115)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.setRunType(TextHeaderAtom.CENTRE_BODY_TYPE); - tr2.setText("Java API To Access Microsoft PowerPoint Format Files"); - box2.setAnchor(new Rectangle(108, 204, 504, 138)); - slide.addShape(box2); - - TextBox box3 = new TextBox(); - TextRun tr3 = box3.getTextRun(); - tr3.getRichTextRuns()[0].setFontSize(32); - box3.setHorizontalAlignment(TextBox.AlignCenter); - tr3.setText( - "Yegor Kozlov\r" + - "yegor - apache - org"); - box3.setAnchor(new Rectangle(206, 348, 310, 84)); - slide.addShape(box3); - } - - public static void slide2(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.TITLE_TYPE); - tr1.setText("What is HSLF?"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.setRunType(TextHeaderAtom.BODY_TYPE); - tr2.setText("HorribleSLideshowFormat is the POI Project's pure Java implementation " + - "of the Powerpoint binary file format. \r" + - "POI sub-project since 2005\r" + - "Started by Nick Birch, Yegor Kozlov joined soon after"); - box2.setAnchor(new Rectangle(36, 126, 648, 356)); - slide.addShape(box2); - - - } - - public static void slide3(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.TITLE_TYPE); - tr1.setText("HSLF in a Nutshell"); - box1.setAnchor(new Rectangle(36, 15, 648, 65)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.setRunType(TextHeaderAtom.BODY_TYPE); - tr2.setText( - "HSLF provides a way to read, create and modify MS PowerPoint presentations\r" + - "Pure Java API - you don't need PowerPoint to read and write *.ppt files\r" + - "Comprehensive support of PowerPoint objects"); - tr2.getRichTextRuns()[0].setFontSize(28); - box2.setAnchor(new Rectangle(36, 80, 648, 200)); - slide.addShape(box2); - - TextBox box3 = new TextBox(); - TextRun tr3 = box3.getTextRun(); - tr3.setRunType(TextHeaderAtom.BODY_TYPE); - tr3.setText( - "Rich text\r" + - "Tables\r" + - "Shapes\r" + - "Pictures\r" + - "Master slides"); - tr3.getRichTextRuns()[0].setFontSize(24); - tr3.getRichTextRuns()[0].setIndentLevel(1); - box3.setAnchor(new Rectangle(36, 265, 648, 150)); - slide.addShape(box3); - - TextBox box4 = new TextBox(); - TextRun tr4 = box4.getTextRun(); - tr4.setRunType(TextHeaderAtom.BODY_TYPE); - tr4.setText("Access to low level data structures"); - box4.setAnchor(new Rectangle(36, 430, 648, 50)); - slide.addShape(box4); - } - - public static void slide4(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - String[][] txt1 = { - {"Note"}, - {"This presentation was created programmatically using POI HSLF"} - }; - Table table1 = new Table(2, 1); - for (int i = 0; i < txt1.length; i++) { - for (int j = 0; j < txt1[i].length; j++) { - TableCell cell = table1.getCell(i, j); - cell.setText(txt1[i][j]); - cell.getTextRun().getRichTextRuns()[0].setFontSize(10); - RichTextRun rt = cell.getTextRun().getRichTextRuns()[0]; - rt.setFontName("Arial"); - rt.setBold(true); - if(i == 0){ - rt.setFontSize(32); - rt.setFontColor(Color.white); - cell.getFill().setForegroundColor(new Color(0, 153, 204)); - } else { - rt.setFontSize(28); - cell.getFill().setForegroundColor(new Color(235, 239, 241)); - } - cell.setVerticalAlignment(TextBox.AnchorMiddle); - } - } - - Line border1 = table1.createBorder(); - border1.setLineColor(Color.black); - border1.setLineWidth(1.0); - table1.setAllBorders(border1); - - Line border2 = table1.createBorder(); - border2.setLineColor(Color.black); - border2.setLineWidth(2.0); - table1.setOutsideBorders(border2); - - table1.setColumnWidth(0, 510); - table1.setRowHeight(0, 60); - table1.setRowHeight(1, 100); - slide.addShape(table1); - - table1.moveTo(100, 100); - - TextBox box1 = new TextBox(); - box1.setHorizontalAlignment(TextBox.AlignCenter); - TextRun tr1 = box1.getTextRun(); - tr1.setText("The source code is available at\r" + - "http://people.apache.org/~yegor/apachecon_eu08/"); - RichTextRun rt = tr1.getRichTextRuns()[0]; - rt.setFontSize(24); - box1.setAnchor(new Rectangle(80, 356, 553, 65)); - slide.addShape(box1); - - } - - public static void slide5(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.TITLE_TYPE); - tr1.setText("HSLF in Action - 1\rData Extraction"); - box1.setAnchor(new Rectangle(36, 21, 648, 100)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.setRunType(TextHeaderAtom.BODY_TYPE); - tr2.setText( - "Text from slides and notes\r" + - "Images\r" + - "Shapes and their properties (type, position in the slide, color, font, etc.)"); - box2.setAnchor(new Rectangle(36, 150, 648, 300)); - slide.addShape(box2); - - - } - - public static void slide6(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.TITLE_TYPE); - tr1.setText("HSLF in Action - 2"); - box1.setAnchor(new Rectangle(36, 20, 648, 90)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.getRichTextRuns()[0].setFontSize(18); - tr2.setText("Creating a simple presentation from scratch"); - box2.setAnchor(new Rectangle(170, 100, 364, 30)); - slide.addShape(box2); - - TextBox box3 = new TextBox(); - TextRun tr3 = box3.getTextRun(); - RichTextRun rt3 = tr3.getRichTextRuns()[0]; - rt3.setFontName("Courier New"); - rt3.setFontSize(8); - tr3.setText( - " SlideShow ppt = new SlideShow();\r" + - " Slide slide = ppt.createSlide();\r" + - "\r" + - " TextBox box2 = new TextBox();\r" + - " box2.setHorizontalAlignment(TextBox.AlignCenter);\r" + - " box2.setVerticalAlignment(TextBox.AnchorMiddle);\r" + - " box2.getTextRun().setText(\"Java Code\");\r" + - " box2.getFill().setForegroundColor(new Color(187, 224, 227));\r" + - " box2.setLineColor(Color.black);\r" + - " box2.setLineWidth(0.75);\r" + - " box2.setAnchor(new Rectangle(66, 243, 170, 170));\r" + - " slide.addShape(box2);\r" + - "\r" + - " TextBox box3 = new TextBox();\r" + - " box3.setHorizontalAlignment(TextBox.AlignCenter);\r" + - " box3.setVerticalAlignment(TextBox.AnchorMiddle);\r" + - " box3.getTextRun().setText(\"*.ppt file\");\r" + - " box3.setLineWidth(0.75);\r" + - " box3.setLineColor(Color.black);\r" + - " box3.getFill().setForegroundColor(new Color(187, 224, 227));\r" + - " box3.setAnchor(new Rectangle(473, 243, 170, 170));\r" + - " slide.addShape(box3);\r" + - "\r" + - " AutoShape box4 = new AutoShape(ShapeTypes.Arrow);\r" + - " box4.getFill().setForegroundColor(new Color(187, 224, 227));\r" + - " box4.setLineWidth(0.75);\r" + - " box4.setLineColor(Color.black);\r" + - " box4.setAnchor(new Rectangle(253, 288, 198, 85));\r" + - " slide.addShape(box4);\r" + - "\r" + - " FileOutputStream out = new FileOutputStream(\"hslf-demo.ppt\");\r" + - " ppt.write(out);\r" + - " out.close();"); - box3.setAnchor(new Rectangle(30, 150, 618, 411)); - slide.addShape(box3); - } - - public static void slide7(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box2 = new TextBox(); - box2.setHorizontalAlignment(TextBox.AlignCenter); - box2.setVerticalAlignment(TextBox.AnchorMiddle); - box2.getTextRun().setText("Java Code"); - box2.getFill().setForegroundColor(new Color(187, 224, 227)); - box2.setLineColor(Color.black); - box2.setLineWidth(0.75); - box2.setAnchor(new Rectangle(66, 243, 170, 170)); - slide.addShape(box2); - - TextBox box3 = new TextBox(); - box3.setHorizontalAlignment(TextBox.AlignCenter); - box3.setVerticalAlignment(TextBox.AnchorMiddle); - box3.getTextRun().setText("*.ppt file"); - box3.setLineWidth(0.75); - box3.setLineColor(Color.black); - box3.getFill().setForegroundColor(new Color(187, 224, 227)); - box3.setAnchor(new Rectangle(473, 243, 170, 170)); - slide.addShape(box3); - - AutoShape box4 = new AutoShape(ShapeTypes.Arrow); - box4.getFill().setForegroundColor(new Color(187, 224, 227)); - box4.setLineWidth(0.75); - box4.setLineColor(Color.black); - box4.setAnchor(new Rectangle(253, 288, 198, 85)); - slide.addShape(box4); - } - - public static void slide8(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.TITLE_TYPE); - tr1.setText("Wait, there is more!"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.setRunType(TextHeaderAtom.BODY_TYPE); - tr2.setText( - "Rich text\r" + - "Tables\r" + - "Pictures (JPEG, PNG, BMP, WMF, PICT)\r" + - "Comprehensive formatting features"); - box2.setAnchor(new Rectangle(36, 126, 648, 356)); - slide.addShape(box2); - } - - public static void slide9(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.TITLE_TYPE); - tr1.setText("HSLF in Action - 3"); - box1.setAnchor(new Rectangle(36, 20, 648, 50)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.getRichTextRuns()[0].setFontSize(18); - tr2.setText("PPGraphics2D: PowerPoint Graphics2D driver"); - box2.setAnchor(new Rectangle(178, 70, 387, 30)); - slide.addShape(box2); - - TextBox box3 = new TextBox(); - TextRun tr3 = box3.getTextRun(); - RichTextRun rt3 = tr3.getRichTextRuns()[0]; - rt3.setFontName("Courier New"); - rt3.setFontSize(8); - tr3.setText( - " //bar chart data. The first value is the bar color, the second is the width\r" + - " Object[] def = new Object[]{\r" + - " Color.yellow, new Integer(100),\r" + - " Color.green, new Integer(150),\r" + - " Color.gray, new Integer(75),\r" + - " Color.red, new Integer(200),\r" + - " };\r" + - "\r" + - " SlideShow ppt = new SlideShow();\r" + - " Slide slide = ppt.createSlide();\r" + - "\r" + - " ShapeGroup group = new ShapeGroup();\r" + - " //define position of the drawing in the slide\r" + - " Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300);\r" + - " group.setAnchor(bounds);\r" + - " slide.addShape(group);\r" + - " Graphics2D graphics = new PPGraphics2D(group);\r" + - "\r" + - " //draw a simple bar graph\r" + - " int x = bounds.x + 50, y = bounds.y + 50;\r" + - " graphics.setFont(new Font(\"Arial\", Font.BOLD, 10));\r" + - " for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {\r" + - " graphics.setColor(Color.black);\r" + - " int width = ((Integer)def[i+1]).intValue();\r" + - " graphics.drawString(\"Q\" + idx, x-20, y+20);\r" + - " graphics.drawString(width + \"%\", x + width + 10, y + 20);\r" + - " graphics.setColor((Color)def[i]);\r" + - " graphics.fill(new Rectangle(x, y, width, 30));\r" + - " y += 40;\r" + - " }\r" + - " graphics.setColor(Color.black);\r" + - " graphics.setFont(new Font(\"Arial\", Font.BOLD, 14));\r" + - " graphics.draw(bounds);\r" + - " graphics.drawString(\"Performance\", x + 70, y + 40);\r" + - "\r" + - " FileOutputStream out = new FileOutputStream(\"hslf-demo.ppt\");\r" + - " ppt.write(out);\r" + - " out.close();"); - box3.setAnchor(new Rectangle(96, 110, 499, 378)); - slide.addShape(box3); - } - - public static void slide10(SlideShow ppt) throws IOException { - //bar chart data. The first value is the bar color, the second is the width - Object[] def = new Object[]{ - Color.yellow, new Integer(100), - Color.green, new Integer(150), - Color.gray, new Integer(75), - Color.red, new Integer(200), - }; - - Slide slide = ppt.createSlide(); - - ShapeGroup group = new ShapeGroup(); - //define position of the drawing in the slide - Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); - group.setAnchor(bounds); - slide.addShape(group); - Graphics2D graphics = new PPGraphics2D(group); - - //draw a simple bar graph - int x = bounds.x + 50, y = bounds.y + 50; - graphics.setFont(new Font("Arial", Font.BOLD, 10)); - for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { - graphics.setColor(Color.black); - int width = ((Integer)def[i+1]).intValue(); - graphics.drawString("Q" + idx, x-20, y+20); - graphics.drawString(width + "%", x + width + 10, y + 20); - graphics.setColor((Color)def[i]); - graphics.fill(new Rectangle(x, y, width, 30)); - y += 40; - } - graphics.setColor(Color.black); - graphics.setFont(new Font("Arial", Font.BOLD, 14)); - graphics.draw(bounds); - graphics.drawString("Performance", x + 70, y + 40); - - } - - public static void slide11(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.TITLE_TYPE); - tr1.setText("HSLF Development Plans"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.setRunType(TextHeaderAtom.BODY_TYPE); - tr2.getRichTextRuns()[0].setFontSize(32); - tr2.setText( - "Support for more PowerPoint functionality\r" + - "Rendering slides into java.awt.Graphics2D"); - box2.setAnchor(new Rectangle(36, 126, 648, 100)); - slide.addShape(box2); - - TextBox box3 = new TextBox(); - TextRun tr3 = box3.getTextRun(); - tr3.setRunType(TextHeaderAtom.BODY_TYPE); - tr3.getRichTextRuns()[0].setIndentLevel(1); - tr3.setText( - "A way to export slides into images or other formats"); - box3.setAnchor(new Rectangle(36, 220, 648, 70)); - slide.addShape(box3); - - TextBox box4 = new TextBox(); - TextRun tr4 = box4.getTextRun(); - tr4.setRunType(TextHeaderAtom.BODY_TYPE); - tr4.getRichTextRuns()[0].setFontSize(32); - tr4.setText( - "Integration with Apache FOP - Formatting Objects Processor"); - box4.setAnchor(new Rectangle(36, 290, 648, 90)); - slide.addShape(box4); - - TextBox box5 = new TextBox(); - TextRun tr5 = box5.getTextRun(); - tr5.setRunType(TextHeaderAtom.BODY_TYPE); - tr5.getRichTextRuns()[0].setIndentLevel(1); - tr5.setText( - "Transformation of XSL-FO into PPT\r" + - "PPT2PDF transcoder"); - box5.setAnchor(new Rectangle(36, 380, 648, 100)); - slide.addShape(box5); - } - - public static void slide12(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = new TextBox(); - TextRun tr1 = box1.getTextRun(); - tr1.setRunType(TextHeaderAtom.CENTER_TITLE_TYPE); - tr1.setText("Questions?"); - box1.setAnchor(new Rectangle(54, 167, 612, 115)); - slide.addShape(box1); - - TextBox box2 = new TextBox(); - TextRun tr2 = box2.getTextRun(); - tr2.setRunType(TextHeaderAtom.CENTRE_BODY_TYPE); - tr2.setText( - "http://poi.apache.org/hslf/\r" + - "http://people.apache.org/~yegor"); - box2.setAnchor(new Rectangle(108, 306, 504, 138)); - slide.addShape(box2); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java b/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java deleted file mode 100644 index 3a97b61aa0..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.SlideShow; -import org.apache.poi.hslf.usermodel.RichTextRun; -import org.apache.poi.hslf.model.Slide; -import org.apache.poi.hslf.model.TextBox; - -import java.io.FileOutputStream; - -/** - * How to create a single-level bulleted list - * and change some of the bullet attributes - * - * @author Yegor Kozlov - */ -public final class BulletsDemo { - - public static void main(String[] args) throws Exception { - - SlideShow ppt = new SlideShow(); - - Slide slide = ppt.createSlide(); - - TextBox shape = new TextBox(); - RichTextRun rt = shape.getTextRun().getRichTextRuns()[0]; - shape.setText( - "January\r" + - "February\r" + - "March\r" + - "April"); - rt.setFontSize(42); - rt.setBullet(true); - rt.setBulletOffset(0); //bullet offset - rt.setTextOffset(50); //text offset (should be greater than bullet offset) - rt.setBulletChar('\u263A'); //bullet character - slide.addShape(shape); - - shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide - slide.addShape(shape); - - FileOutputStream out = new FileOutputStream("bullets.ppt"); - ppt.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java b/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java deleted file mode 100644 index 0aa8db32de..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.SlideShow; -import org.apache.poi.hslf.model.*; - -import java.io.FileOutputStream; -import java.awt.*; - -/** - * Demonstrates how to create hyperlinks in PowerPoint presentations - * - * @author Yegor Kozlov - */ -public final class CreateHyperlink { - - public static void main(String[] args) throws Exception { - SlideShow ppt = new SlideShow(); - - Slide slideA = ppt.createSlide(); - Slide slideB = ppt.createSlide(); - Slide slideC = ppt.createSlide(); - - // link to a URL - TextBox textBox1 = new TextBox(); - textBox1.setText("Apache POI"); - textBox1.setAnchor(new Rectangle(100, 100, 200, 50)); - - String text = textBox1.getText(); - Hyperlink link = new Hyperlink(); - link.setAddress("http://www.apache.org"); - link.setTitle(textBox1.getText()); - int linkId = ppt.addHyperlink(link); - - // apply link to the text - textBox1.setHyperlink(linkId, 0, text.length()); - - slideA.addShape(textBox1); - - // link to another slide - TextBox textBox2 = new TextBox(); - textBox2.setText("Go to slide #3"); - textBox2.setAnchor(new Rectangle(100, 300, 200, 50)); - - Hyperlink link2 = new Hyperlink(); - link2.setAddress(slideC); - ppt.addHyperlink(link2); - - // apply link to the whole shape - textBox2.setHyperlink(link2); - - slideA.addShape(textBox2); - - FileOutputStream out = new FileOutputStream("hyperlink.ppt"); - ppt.write(out); - out.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java b/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java deleted file mode 100644 index a278e894b6..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java +++ /dev/null @@ -1,148 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.*; -import org.apache.poi.hslf.model.*; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.usermodel.Range; -import org.apache.poi.hwpf.usermodel.Paragraph; - -import java.io.*; - -/** - * Demonstrates how you can extract misc embedded data from a ppt file - * - * @author Yegor Kozlov - */ -public final class DataExtraction { - - public static void main(String args[]) throws Exception { - - if (args.length == 0) { - usage(); - return; - } - - FileInputStream is = new FileInputStream(args[0]); - SlideShow ppt = new SlideShow(is); - is.close(); - - //extract all sound files embedded in this presentation - SoundData[] sound = ppt.getSoundData(); - for (int i = 0; i < sound.length; i++) { - String type = sound[i].getSoundType(); //*.wav - String name = sound[i].getSoundName(); //typically file name - byte[] data = sound[i].getData(); //raw bytes - - //save the sound on disk - FileOutputStream out = new FileOutputStream(name + type); - out.write(data); - out.close(); - } - - //extract embedded OLE documents - Slide[] slide = ppt.getSlides(); - for (int i = 0; i < slide.length; i++) { - Shape[] shape = slide[i].getShapes(); - for (int j = 0; j < shape.length; j++) { - if (shape[j] instanceof OLEShape) { - OLEShape ole = (OLEShape) shape[j]; - ObjectData data = ole.getObjectData(); - String name = ole.getInstanceName(); - if ("Worksheet".equals(name)) { - - //read xls - HSSFWorkbook wb = new HSSFWorkbook(data.getData()); - - } else if ("Document".equals(name)) { - HWPFDocument doc = new HWPFDocument(data.getData()); - //read the word document - Range r = doc.getRange(); - for(int k = 0; k < r.numParagraphs(); k++) { - Paragraph p = r.getParagraph(k); - System.out.println(p.text()); - } - - //save on disk - FileOutputStream out = new FileOutputStream(name + "-("+(j)+").doc"); - doc.write(out); - out.close(); - } else { - FileOutputStream out = new FileOutputStream(ole.getProgID() + "-"+(j+1)+".dat"); - InputStream dis = data.getData(); - byte[] chunk = new byte[2048]; - int count; - while ((count = dis.read(chunk)) >= 0) { - out.write(chunk,0,count); - } - is.close(); - out.close(); - } - } - - } - } - - //Pictures - for (int i = 0; i < slide.length; i++) { - Shape[] shape = slide[i].getShapes(); - for (int j = 0; j < shape.length; j++) { - if (shape[j] instanceof Picture) { - Picture p = (Picture) shape[j]; - PictureData data = p.getPictureData(); - String name = p.getPictureName(); - int type = data.getType(); - String ext; - switch (type) { - case Picture.JPEG: - ext = ".jpg"; - break; - case Picture.PNG: - ext = ".png"; - break; - case Picture.WMF: - ext = ".wmf"; - break; - case Picture.EMF: - ext = ".emf"; - break; - case Picture.PICT: - ext = ".pict"; - break; - case Picture.DIB: - ext = ".dib"; - break; - default: - continue; - } - FileOutputStream out = new FileOutputStream("pict-" + j + ext); - out.write(data.getData()); - out.close(); - } - - } - } - - } - - private static void usage(){ - System.out.println("Usage: DataExtraction ppt"); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java b/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java deleted file mode 100644 index 8d7921146a..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.SlideShow; -import org.apache.poi.hslf.model.*; - -import java.awt.*; -import java.io.FileOutputStream; - -/** - * Demonstrates how to draw into a slide using the HSLF Graphics2D driver. - * - * @author Yegor Kozlov - */ -public final class Graphics2DDemo { - - /** - * A simple bar chart demo - */ - public static void main(String[] args) throws Exception { - SlideShow ppt = new SlideShow(); - - //bar chart data. The first value is the bar color, the second is the width - Object[] def = new Object[]{ - Color.yellow, new Integer(40), - Color.green, new Integer(60), - Color.gray, new Integer(30), - Color.red, new Integer(80), - }; - - Slide slide = ppt.createSlide(); - - ShapeGroup group = new ShapeGroup(); - //define position of the drawing in the slide - Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); - group.setAnchor(bounds); - group.setCoordinates(new java.awt.Rectangle(0, 0, 100, 100)); - slide.addShape(group); - Graphics2D graphics = new PPGraphics2D(group); - - //draw a simple bar graph - int x = 10, y = 10; - graphics.setFont(new Font("Arial", Font.BOLD, 10)); - for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { - graphics.setColor(Color.black); - int width = ((Integer)def[i+1]).intValue(); - graphics.drawString("Q" + idx, x-5, y+10); - graphics.drawString(width + "%", x + width+3, y + 10); - graphics.setColor((Color)def[i]); - graphics.fill(new Rectangle(x, y, width, 10)); - y += 15; - } - graphics.setColor(Color.black); - graphics.setFont(new Font("Arial", Font.BOLD, 14)); - graphics.draw(group.getCoordinates()); - graphics.drawString("Performance", x + 30, y + 10); - - FileOutputStream out = new FileOutputStream("hslf-graphics.ppt"); - ppt.write(out); - out.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java b/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java deleted file mode 100644 index 3ebcecc90f..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.SlideShow; -import org.apache.poi.hslf.model.HeadersFooters; -import org.apache.poi.hslf.model.Slide; - -import java.io.FileOutputStream; - -/** - * Demonstrates how to set headers / footers - * - * @author Yegor Kozlov - */ -public class HeadersFootersDemo { - public static void main(String[] args) throws Exception { - SlideShow ppt = new SlideShow(); - - HeadersFooters slideHeaders = ppt.getSlideHeadersFooters(); - slideHeaders.setFootersText("Created by POI-HSLF"); - slideHeaders.setSlideNumberVisible(true); - slideHeaders.setDateTimeText("custom date time"); - - HeadersFooters notesHeaders = ppt.getNotesHeadersFooters(); - notesHeaders.setFootersText("My notes footers"); - notesHeaders.setHeaderText("My notes header"); - - Slide slide = ppt.createSlide(); - - FileOutputStream out = new FileOutputStream("headers_footers.ppt"); - ppt.write(out); - out.close(); - - } - -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java b/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java deleted file mode 100644 index 968426c513..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.SlideShow; -import org.apache.poi.hslf.model.Slide; -import org.apache.poi.hslf.model.TextRun; -import org.apache.poi.hslf.model.Hyperlink; -import org.apache.poi.hslf.model.Shape; - -import java.io.FileInputStream; - -/** - * Demonstrates how to read hyperlinks from a presentation - * - * @author Yegor Kozlov - */ -public final class Hyperlinks { - - public static void main(String[] args) throws Exception { - for (int i = 0; i < args.length; i++) { - FileInputStream is = new FileInputStream(args[i]); - SlideShow ppt = new SlideShow(is); - is.close(); - - Slide[] slide = ppt.getSlides(); - for (int j = 0; j < slide.length; j++) { - System.out.println("slide " + slide[j].getSlideNumber()); - - //read hyperlinks from the slide's text runs - System.out.println("reading hyperlinks from the text runs"); - TextRun[] txt = slide[j].getTextRuns(); - for (int k = 0; k < txt.length; k++) { - String text = txt[k].getText(); - Hyperlink[] links = txt[k].getHyperlinks(); - if(links != null) for (int l = 0; l < links.length; l++) { - Hyperlink link = links[l]; - String title = link.getTitle(); - String address = link.getAddress(); - System.out.println(" " + title); - System.out.println(" " + address); - String substring = text.substring(link.getStartIndex(), link.getEndIndex()-1);//in ppt end index is inclusive - System.out.println(" " + substring); - } - } - - //in PowerPoint you can assign a hyperlink to a shape without text, - //for example to a Line object. The code below demonstrates how to - //read such hyperlinks - System.out.println(" reading hyperlinks from the slide's shapes"); - Shape[] sh = slide[j].getShapes(); - for (int k = 0; k < sh.length; k++) { - Hyperlink link = sh[k].getHyperlink(); - if(link != null) { - String title = link.getTitle(); - String address = link.getAddress(); - System.out.println(" " + title); - System.out.println(" " + address); - } - } - } - - } - - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/PPT2PNG.java b/src/examples/src/org/apache/poi/hslf/examples/PPT2PNG.java deleted file mode 100644 index 99037d3264..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/PPT2PNG.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.*; -import org.apache.poi.hslf.model.*; - -import javax.imageio.ImageIO; -import java.io.FileOutputStream; -import java.io.FileInputStream; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.awt.geom.Rectangle2D; - -/** - * Demonstrates how you can use HSLF to convert each slide into a PNG image - * - * @author Yegor Kozlov - */ -public final class PPT2PNG { - - public static void main(String args[]) throws Exception { - - if (args.length == 0) { - usage(); - return; - } - - int slidenum = -1; - float scale = 1; - String file = null; - - for (int i = 0; i < args.length; i++) { - if (args[i].startsWith("-")) { - if ("-scale".equals(args[i])){ - scale = Float.parseFloat(args[++i]); - } else if ("-slide".equals(args[i])) { - slidenum = Integer.parseInt(args[++i]); - } - } else { - file = args[i]; - } - } - if(file == null){ - usage(); - return; - } - - FileInputStream is = new FileInputStream(file); - SlideShow ppt = new SlideShow(is); - is.close(); - - Dimension pgsize = ppt.getPageSize(); - int width = (int)(pgsize.width*scale); - int height = (int)(pgsize.height*scale); - - Slide[] slide = ppt.getSlides(); - for (int i = 0; i < slide.length; i++) { - if (slidenum != -1 && slidenum != (i+1)) continue; - - String title = slide[i].getTitle(); - System.out.println("Rendering slide "+slide[i].getSlideNumber() + (title == null ? "" : ": " + title)); - - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = img.createGraphics(); - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - graphics.setPaint(Color.white); - graphics.fill(new Rectangle2D.Float(0, 0, width, height)); - - graphics.scale((double)width/pgsize.width, (double)height/pgsize.height); - - slide[i].draw(graphics); - - String fname = file.replaceAll("\\.ppt", "-" + (i+1) + ".png"); - FileOutputStream out = new FileOutputStream(fname); - ImageIO.write(img, "png", out); - out.close(); - } - } - - private static void usage(){ - System.out.println("Usage: PPT2PNG [-scale -slide ] ppt"); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java b/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java deleted file mode 100644 index b31019db94..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hslf.examples; -import org.apache.poi.ddf.*; -import org.apache.poi.hslf.model.*; -import org.apache.poi.hslf.record.InteractiveInfo; -import org.apache.poi.hslf.record.InteractiveInfoAtom; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.usermodel.*; -import java.io.FileInputStream; -import java.util.Iterator; -import java.util.List; - -/** - * For each slide iterate over shapes and found associated sound data. - * - * @author Yegor Kozlov - */ -public class SoundFinder { - public static void main(String[] args) throws Exception { - SlideShow ppt = new SlideShow(new FileInputStream(args[0])); - SoundData[] sounds = ppt.getSoundData(); - - Slide[] slide = ppt.getSlides(); - for (int i = 0; i < slide.length; i++) { - Shape[] shape = slide[i].getShapes(); - for (int j = 0; j < shape.length; j++) { - int soundRef = getSoundReference(shape[j]); - if(soundRef != -1) { - System.out.println("Slide["+i+"], shape["+j+"], soundRef: "+soundRef); - System.out.println(" " + sounds[soundRef].getSoundName()); - System.out.println(" " + sounds[soundRef].getSoundType()); - } - } - } - } - - /** - * Check if a given shape is associated with a sound. - * @return 0-based reference to a sound in the sound collection - * or -1 if the shape is not associated with a sound - */ - protected static int getSoundReference(Shape shape){ - int soundRef = -1; - //dive into the shape container and search for InteractiveInfoAtom - EscherContainerRecord spContainer = shape.getSpContainer(); - List spchild = spContainer.getChildRecords(); - for (Iterator it = spchild.iterator(); it.hasNext();) { - EscherRecord obj = (EscherRecord) it.next(); - if (obj.getRecordId() == EscherClientDataRecord.RECORD_ID) { - byte[] data = obj.serialize(); - Record[] records = Record.findChildRecords(data, 8, -data.length - 8); - for (int j = 0; j < records.length; j++) { - if (records[j] instanceof InteractiveInfo) { - InteractiveInfoAtom info = ((InteractiveInfo)records[j]).getInteractiveInfoAtom(); - if (info.getAction() == InteractiveInfoAtom.ACTION_MEDIA) { - soundRef = info.getSoundRef(); - } - } - } - } - } - return soundRef; - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/TableDemo.java b/src/examples/src/org/apache/poi/hslf/examples/TableDemo.java deleted file mode 100644 index 44935c05ac..0000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/TableDemo.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import org.apache.poi.hslf.usermodel.SlideShow; -import org.apache.poi.hslf.usermodel.RichTextRun; -import org.apache.poi.hslf.model.*; - -import java.awt.*; -import java.io.FileOutputStream; - -/** - * Demonstrates how to create tables - * - * @author Yegor Kozlov - */ -public final class TableDemo { - - public static void main(String[] args) throws Exception { - - //test data for the first taable - String[][] txt1 = { - {"INPUT FILE", "NUMBER OF RECORDS"}, - {"Item File", "11,559"}, - {"Vendor File", "502"}, - {"Purchase History File - # of PO\u2019s\r(12/01/04 - 05/31/06)", "12,852"}, - {"Purchase History File - # of PO Lines\r(12/01/04 - 05/31/06)", "53,523" }, - {"Total PO History Spend", "$10,172,038"} - }; - - SlideShow ppt = new SlideShow(); - - Slide slide = ppt.createSlide(); - - //six rows, two columns - Table table1 = new Table(6, 2); - for (int i = 0; i < txt1.length; i++) { - for (int j = 0; j < txt1[i].length; j++) { - TableCell cell = table1.getCell(i, j); - cell.setText(txt1[i][j]); - RichTextRun rt = cell.getTextRun().getRichTextRuns()[0]; - rt.setFontName("Arial"); - rt.setFontSize(10); - if(i == 0){ - cell.getFill().setForegroundColor(new Color(227, 227, 227)); - } else { - rt.setBold(true); - } - cell.setVerticalAlignment(TextBox.AnchorMiddle); - cell.setHorizontalAlignment(TextBox.AlignCenter); - } - } - - Line border1 = table1.createBorder(); - border1.setLineColor(Color.black); - border1.setLineWidth(1.0); - table1.setAllBorders(border1); - - table1.setColumnWidth(0, 300); - table1.setColumnWidth(1, 150); - - slide.addShape(table1); - int pgWidth = ppt.getPageSize().width; - table1.moveTo((pgWidth - table1.getAnchor().width)/2, 100); - - //test data for the second taable - String[][] txt2 = { - {"Data Source"}, - {"CAS Internal Metrics - Item Master Summary\r" + - "CAS Internal Metrics - Vendor Summary\r" + - "CAS Internal Metrics - PO History Summary"} - }; - - //two rows, one column - Table table2 = new Table(2, 1); - for (int i = 0; i < txt2.length; i++) { - for (int j = 0; j < txt2[i].length; j++) { - TableCell cell = table2.getCell(i, j); - cell.setText(txt2[i][j]); - RichTextRun rt = cell.getTextRun().getRichTextRuns()[0]; - rt.setFontSize(10); - rt.setFontName("Arial"); - if(i == 0){ - cell.getFill().setForegroundColor(new Color(0, 51, 102)); - rt.setFontColor(Color.white); - rt.setBold(true); - rt.setFontSize(14); - cell.setHorizontalAlignment(TextBox.AlignCenter); - } else { - rt.setBullet(true); - rt.setFontSize(12); - cell.setHorizontalAlignment(TextBox.AlignLeft); - } - cell.setVerticalAlignment(TextBox.AnchorMiddle); - } - } - table2.setColumnWidth(0, 300); - table2.setRowHeight(0, 30); - table2.setRowHeight(1, 70); - - Line border2 = table2.createBorder(); - table2.setOutsideBorders(border2); - - slide.addShape(table2); - table2.moveTo(200, 400); - - FileOutputStream out = new FileOutputStream("hslf-table.ppt"); - ppt.write(out); - out.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java b/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java deleted file mode 100644 index bf018a3e41..0000000000 --- a/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.examples; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; - -/** - * Reads one or several Outlook MSG files and for each of them creates - * a text file from available chunks and a directory that contains - * attachments. - * - * @author Bruno Girin - */ -public class Msg2txt { - - /** - * The stem used to create file names for the text file and the directory - * that contains the attachments. - */ - private String fileNameStem; - - /** - * The Outlook MSG file being processed. - */ - private MAPIMessage msg; - - public Msg2txt(String fileName) throws IOException { - fileNameStem = fileName; - if(fileNameStem.endsWith(".msg") || fileNameStem.endsWith(".MSG")) { - fileNameStem = fileNameStem.substring(0, fileNameStem.length() - 4); - } - msg = new MAPIMessage(fileName); - } - - /** - * Processes the message. - * - * @throws IOException if an exception occurs while writing the message out - */ - public void processMessage() throws IOException { - String txtFileName = fileNameStem + ".txt"; - String attDirName = fileNameStem + "-att"; - PrintWriter txtOut = null; - try { - txtOut = new PrintWriter(txtFileName); - try { - String displayFrom = msg.getDisplayFrom(); - txtOut.println("From: "+displayFrom); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String displayTo = msg.getDisplayTo(); - txtOut.println("To: "+displayTo); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String displayCC = msg.getDisplayCC(); - txtOut.println("CC: "+displayCC); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String displayBCC = msg.getDisplayBCC(); - txtOut.println("BCC: "+displayBCC); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String subject = msg.getSubject(); - txtOut.println("Subject: "+subject); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String body = msg.getTextBody(); - txtOut.println(body); - } catch (ChunkNotFoundException e) { - System.err.println("No message body"); - } - - AttachmentChunks[] attachments = msg.getAttachmentFiles(); - if(attachments.length > 0) { - File d = new File(attDirName); - if(d.mkdir()) { - for(AttachmentChunks attachment : attachments) { - processAttachment(attachment, d); - } - } else { - System.err.println("Can't create directory "+attDirName); - } - } - } finally { - if(txtOut != null) { - txtOut.close(); - } - } - } - - /** - * Processes a single attachment: reads it from the Outlook MSG file and - * writes it to disk as an individual file. - * - * @param attachment the chunk group describing the attachment - * @param dir the directory in which to write the attachment file - * @throws IOException when any of the file operations fails - */ - public void processAttachment(AttachmentChunks attachment, - File dir) throws IOException { - String fileName = attachment.attachFileName.toString(); - if(attachment.attachLongFileName != null) { - fileName = attachment.attachLongFileName.toString(); - } - - File f = new File(dir, fileName); - OutputStream fileOut = null; - try { - fileOut = new FileOutputStream(f); - fileOut.write(attachment.attachData.getValue()); - } finally { - if(fileOut != null) { - fileOut.close(); - } - } - } - - /** - * Processes the list of arguments as a list of names of Outlook MSG files. - * - * @param args the list of MSG files to process - */ - public static void main(String[] args) { - if(args.length <= 0) { - System.err.println("No files names provided"); - } else { - for(int i = 0; i < args.length; i++) { - try { - Msg2txt processor = new Msg2txt(args[i]); - processor.processMessage(); - } catch (IOException e) { - System.err.println("Could not process "+args[i]+": "+e); - } - } - } - } - -} diff --git a/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java b/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java deleted file mode 100644 index 4c1119137e..0000000000 --- a/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java +++ /dev/null @@ -1,327 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventusermodel.examples; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintStream; -import java.util.ArrayList; - -import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener; -import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener; -import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; -import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.BoolErrRecord; -import org.apache.poi.hssf.record.BoundSheetRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.LabelRecord; -import org.apache.poi.hssf.record.LabelSSTRecord; -import org.apache.poi.hssf.record.NoteRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.RKRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SSTRecord; -import org.apache.poi.hssf.record.StringRecord; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * A XLS -> CSV processor, that uses the MissingRecordAware - * EventModel code to ensure it outputs all columns and rows. - * @author Nick Burch - */ -public class XLS2CSVmra implements HSSFListener { - private int minColumns; - private POIFSFileSystem fs; - private PrintStream output; - - private int lastRowNumber; - private int lastColumnNumber; - - /** Should we output the formula, or the value it has? */ - private boolean outputFormulaValues = true; - - /** For parsing Formulas */ - private SheetRecordCollectingListener workbookBuildingListener; - private HSSFWorkbook stubWorkbook; - - // Records we pick up as we process - private SSTRecord sstRecord; - private FormatTrackingHSSFListener formatListener; - - /** So we known which sheet we're on */ - private int sheetIndex = -1; - private BoundSheetRecord[] orderedBSRs; - private ArrayList boundSheetRecords = new ArrayList(); - - // For handling formulas with string results - private int nextRow; - private int nextColumn; - private boolean outputNextStringRecord; - - /** - * Creates a new XLS -> CSV converter - * @param fs The POIFSFileSystem to process - * @param output The PrintStream to output the CSV to - * @param minColumns The minimum number of columns to output, or -1 for no minimum - */ - public XLS2CSVmra(POIFSFileSystem fs, PrintStream output, int minColumns) { - this.fs = fs; - this.output = output; - this.minColumns = minColumns; - } - - /** - * Creates a new XLS -> CSV converter - * @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 XLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException { - this( - new POIFSFileSystem(new FileInputStream(filename)), - System.out, minColumns - ); - } - - /** - * Initiates the processing of the XLS file to CSV - */ - public void process() throws IOException { - MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this); - formatListener = new FormatTrackingHSSFListener(listener); - - HSSFEventFactory factory = new HSSFEventFactory(); - HSSFRequest request = new HSSFRequest(); - - if(outputFormulaValues) { - request.addListenerForAllRecords(formatListener); - } else { - workbookBuildingListener = new SheetRecordCollectingListener(formatListener); - request.addListenerForAllRecords(workbookBuildingListener); - } - - factory.processWorkbookEvents(request, fs); - } - - /** - * Main HSSFListener method, processes events, and outputs the - * CSV as the file is processed. - */ - public void processRecord(Record record) { - int thisRow = -1; - int thisColumn = -1; - String thisStr = null; - - switch (record.getSid()) - { - case BoundSheetRecord.sid: - boundSheetRecords.add(record); - break; - case BOFRecord.sid: - BOFRecord br = (BOFRecord)record; - if(br.getType() == BOFRecord.TYPE_WORKSHEET) { - // Create sub workbook if required - if(workbookBuildingListener != null && stubWorkbook == null) { - stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook(); - } - - // Output the worksheet name - // Works by ordering the BSRs by the location of - // their BOFRecords, and then knowing that we - // process BOFRecords in byte offset order - sheetIndex++; - if(orderedBSRs == null) { - orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords); - } - output.println(); - output.println( - orderedBSRs[sheetIndex].getSheetname() + - " [" + (sheetIndex+1) + "]:" - ); - } - break; - - case SSTRecord.sid: - sstRecord = (SSTRecord) record; - break; - - case BlankRecord.sid: - BlankRecord brec = (BlankRecord) record; - - thisRow = brec.getRow(); - thisColumn = brec.getColumn(); - thisStr = ""; - break; - case BoolErrRecord.sid: - BoolErrRecord berec = (BoolErrRecord) record; - - thisRow = berec.getRow(); - thisColumn = berec.getColumn(); - thisStr = ""; - break; - - case FormulaRecord.sid: - FormulaRecord frec = (FormulaRecord) record; - - thisRow = frec.getRow(); - thisColumn = frec.getColumn(); - - if(outputFormulaValues) { - if(Double.isNaN( frec.getValue() )) { - // Formula result is a string - // This is stored in the next record - outputNextStringRecord = true; - nextRow = frec.getRow(); - nextColumn = frec.getColumn(); - } else { - thisStr = formatListener.formatNumberDateCell(frec); - } - } else { - thisStr = '"' + - HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"'; - } - break; - case StringRecord.sid: - if(outputNextStringRecord) { - // String for formula - StringRecord srec = (StringRecord)record; - thisStr = srec.getString(); - thisRow = nextRow; - thisColumn = nextColumn; - outputNextStringRecord = false; - } - break; - - case LabelRecord.sid: - LabelRecord lrec = (LabelRecord) record; - - thisRow = lrec.getRow(); - thisColumn = lrec.getColumn(); - thisStr = '"' + lrec.getValue() + '"'; - break; - case LabelSSTRecord.sid: - LabelSSTRecord lsrec = (LabelSSTRecord) record; - - thisRow = lsrec.getRow(); - thisColumn = lsrec.getColumn(); - if(sstRecord == null) { - thisStr = '"' + "(No SST Record, can't identify string)" + '"'; - } else { - thisStr = '"' + sstRecord.getString(lsrec.getSSTIndex()).toString() + '"'; - } - break; - case NoteRecord.sid: - NoteRecord nrec = (NoteRecord) record; - - thisRow = nrec.getRow(); - thisColumn = nrec.getColumn(); - // TODO: Find object to match nrec.getShapeId() - thisStr = '"' + "(TODO)" + '"'; - break; - case NumberRecord.sid: - NumberRecord numrec = (NumberRecord) record; - - thisRow = numrec.getRow(); - thisColumn = numrec.getColumn(); - - // Format - thisStr = formatListener.formatNumberDateCell(numrec); - break; - case RKRecord.sid: - RKRecord rkrec = (RKRecord) record; - - thisRow = rkrec.getRow(); - thisColumn = rkrec.getColumn(); - thisStr = '"' + "(TODO)" + '"'; - break; - default: - break; - } - - // Handle new row - if(thisRow != -1 && thisRow != lastRowNumber) { - lastColumnNumber = -1; - } - - // Handle missing column - if(record instanceof MissingCellDummyRecord) { - MissingCellDummyRecord mc = (MissingCellDummyRecord)record; - thisRow = mc.getRow(); - thisColumn = mc.getColumn(); - thisStr = ""; - } - - // If we got something to print out, do so - if(thisStr != null) { - if(thisColumn > 0) { - output.print(','); - } - output.print(thisStr); - } - - // Update column and row count - if(thisRow > -1) - lastRowNumber = thisRow; - if(thisColumn > -1) - lastColumnNumber = thisColumn; - - // Handle end of row - if(record instanceof LastCellOfRowDummyRecord) { - // Print out any missing commas if needed - if(minColumns > 0) { - // Columns are 0 based - if(lastColumnNumber == -1) { lastColumnNumber = 0; } - for(int i=lastColumnNumber; i<(minColumns); i++) { - output.print(','); - } - } - - // We're onto a new row - lastColumnNumber = -1; - - // End the row - output.println(); - } - } - - public static void main(String[] args) throws Exception { - if(args.length < 1) { - System.err.println("Use:"); - System.err.println(" XLS2CSVmra [min columns]"); - System.exit(1); - } - - int minColumns = -1; - if(args.length >= 2) { - minColumns = Integer.parseInt(args[1]); - } - - XLS2CSVmra xls2csv = new XLS2CSVmra(args[0], minColumns); - xls2csv.process(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java deleted file mode 100644 index 6482f186c0..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java +++ /dev/null @@ -1,946 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFClientAnchor; -import org.apache.poi.hssf.usermodel.HSSFPatriarch; -import org.apache.poi.hssf.util.CellReference; - - -/** - * Demonstrates how to add an image to a worksheet and set that image's size - * to a specific number of milimetres irrespective of the width of the columns - * or height of the rows. Overridden methods are provided so that the location - * of the image - the cells row and column co-ordinates that define the top - * left hand corners of the image - can be identified either in the familiar - * Excel manner - A1 for instance - or using POI's methodolody of a column and - * row index where 0, 0 would indicate cell A1. - * - * The best way to make use of these techniques is to delay adding the image to - * the sheet until all other work has been completed. That way, the sizes of - * all rows and columns will have been adjusted - assuming that step was - * necessary. Even though the anchors type is set to prevent the image moving - * or re-sizing, this setting does not have any effect until the sheet is being - * viewed using the Excel application. - * - * The key to the process is the HSSFClientAnchor class. It accepts eight - * parameters that define, in order; - * - * * How far - in terms of co-ordinate position - the image should be inset - * from the left hand border of a cell. - * * How far - in terms of co-ordinate positions - the image should be inset - * from the from the top of the cell. - * * How far - in terms of co-ordinate positions - the right hand edge of - * the image should protrude into a cell (measured from the cell's left hand - * edge to the image's right hand edge). - * * How far - in terms of co-ordinate positions - the bottm edge of the - * image should protrude into a row (measured from the cell's top edge to - * the image's bottom edge). - * * The index of the column that contains the cell whose top left hand - * corner should be aligned with the top left hand corner of the image. - * * The index of the row that contains the cell whose top left hand corner - * should be aligned with the image's top left hand corner. - * * The index of the column that contains the cell whose top left hand - * corner should be aligned with the image's bottom right hand corner - * * The index number of the row that contains the cell whose top left - * hand corner should be aligned with the images bottom right hand corner. - * - * It can be used to add an image into cell A1, for example, in the following - * manner; - * - * HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, - * (short)0, 0, (short)1, 1); - * - * The final four parameters determine that the top left hand corner should be - * aligned with the top left hand corner of cell A1 and it's bottom right - * hand corner with the top left hand corner of cell B2. Think of the image as - * being stretched so that it's top left hand corner is aligned with the top - * left hand corner of cell A1 and it's bottom right hand corner is aligned with - * the top left hand corner of cell B1. Interestingly, this would also produce - * the same results; - * - * anchor = new HSSFClientAnchor(0, 0, 1023, 255, - * (short)0, 0, (short)0, 0); - * - * Note that the final four parameters all contain the same value and seem to - * indicate that the images top left hand corner is aligned with the top left - * hand corner of cell A1 and that it's bottom right hand corner is also - * aligned with the top left hand corner of cell A1. Yet, running this code - * would see the image fully occupying cell A1. That is the result of the - * values passed to parameters three and four; these I have referred to as - * determing the images co-ordinates within the cell. They indicate that the - * image should occupy - in order - the full width of the column and the full - * height of the row. - * - * The co-ordinate values shown are the maxima; and they are independent of - * row height/column width and of the font used. Passing 255 will always result - * in the image occupying the full height of the row and passing 1023 will - * always result in the image occupying the full width of the column. They help - * in situations where an image is larger than a column/row and must overlap - * into the next column/row. Using them does mean, however, that it is often - * necessary to perform conversions between Excel's characters units, points, - * pixels and millimetres in order to establish how many rows/columns an image - * should occupy and just what the varous insets ought to be. - * - * Note that the first two parameters of the HSSFClientAchor classes constructor - * are not made use of in the code that follows. It would be fairly trivial - * however to extend these example further and provide methods that would centre - * an image within a cell or allow the user to specify that a plain border a - * fixed number of millimetres wide should wrap around the image. Those first - * two parameters would make this sort of functionality perfectly possible. - * - * Owing to the various conversions used, the actual size of the image may vary - * from that required; testing has so far found this to be in the region of - * plus or minus two millimetres. Most likely by modifying the way the - * calculations are performed - possibly using double(s) throughout and - * rounding the values at the correct point - it is likely that these errors - * could be reduced or removed. - * - * A note concerning Excels' image resizing behaviour. The HSSFClientAnchor - * class contains a method called setAnchorType(int) which can be used to - * determine how Excel will resize an image in reponse to the user increasing - * or decreasing the dimensions of the cell containing the image. There are - * three values that can be passed to this method; 0 = To move and size the - * image with the cell, 2 = To move but don't size the image with the cell, - * 3 = To prevent the image from moving or being resized along with the cell. If - * an image is inserted using this class and placed into a single cell then if - * the setAnchorType(int) method is called and a value of either 0 or 2 passed - * to it, the resultant resizing behaviour may be a surprise. The image will not - * grow in size of the column is made wider or the row higher but it will shrink - * if the columns width or rows height are reduced. - * - * @author Mark Beardsley [msb at apache.org] - * @version 1.00 5th August 2009. - */ -public class AddDimensionedImage { - - // Four constants that determine how - and indeed whether - the rows - // and columns an image may overlie should be expanded to accomodate that - // image. - // Passing EXPAND_ROW will result in the height of a row being increased - // to accomodate the image if it is not already larger. The image will - // be layed across one or more columns. - // Passing EXPAND_COLUMN will result in the width of the column being - // increased to accomodate the image if it is not already larger. The image - // will be layed across one or many rows. - // Passing EXPAND_ROW_AND_COLUMN will result in the height of the row - // bing increased along with the width of the column to accomdate the - // image if either is not already larger. - // Passing OVERLAY_ROW_AND_COLUMN will result in the image being layed - // over one or more rows and columns. No row or column will be resized, - // instead, code will determine how many rows and columns the image should - // overlie. - public static final int EXPAND_ROW = 1; - public static final int EXPAND_COLUMN = 2; - public static final int EXPAND_ROW_AND_COLUMN = 3; - public static final int OVERLAY_ROW_AND_COLUMN = 7; - - /** - * Add an image to a worksheet. - * - * @param cellNumber A String that contains the location of the cell whose - * top left hand corner should be aligned with the top - * left hand corner of the image; for example "A1", "A2" - * etc. This is to support the familiar Excel syntax. - * Whilst images are are not actually inserted into cells - * this provides a convenient method of indicating where - * the image should be positioned on the sheet. - * @param sheet A reference to the sheet that contains the cell referenced - * above. - * @param imageFile A String that encapsulates the name of and path to - * the image that is to be 'inserted into' the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres. - * @param resizeBehaviour A primitive int whose value will determine how - * the code should react if the image is larger than - * the cell referenced by the cellNumber parameter. - * Four constants are provided to determine what - * should happen; - * AddDimensionedImage.EXPAND_ROW - * AddDimensionedImage.EXPAND_COLUMN - * AddDimensionedImage.EXPAND_ROW_AND_COLUMN - * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN - * @throws java.io.FileNotFoundException If the file containing the image - * cannot be located. - * @throws java.io.IOException If a problem occurs whilst reading the file - * of image data. - * @throws java.lang.IllegalArgumentException If an invalid value is passed - * to the resizeBehaviour - * parameter. - */ - public void addImageToSheet(String cellNumber, HSSFSheet sheet, - String imageFile, double reqImageWidthMM, double reqImageHeightMM, - int resizeBehaviour) throws IOException, IllegalArgumentException { - // Convert the String into column and row indices then chain the - // call to the overridden addImageToSheet() method. - CellReference cellRef = new CellReference(cellNumber); - this.addImageToSheet(cellRef.getCol(), cellRef.getRow(), sheet, - imageFile, reqImageWidthMM, reqImageHeightMM,resizeBehaviour); - } - - /** - * Add an image to a worksheet. - * - * @param colNumber A primitive int that contains the index number of a - * column on the worksheet; POI column indices are zero - * based. Together with the rowNumber parameter's value, - * this parameter identifies a cell on the worksheet. The - * image's top left hand corner will be aligned with the - * top left hand corner of this cell. - * @param rowNumber A primtive int that contains the index number of a row - * on the worksheet; POI row indices are zero based. - * Together with the rowNumber parameter's value, this - * parameter identifies a cell on the worksheet. The - * image's top left hand corner will be aligned with the - * top left hand corner of this cell. - * @param sheet A reference to the sheet that contains the cell identified - * by the two parameters above. - * @param imageFile A String that encapsulates the name of and path to - * the image that is to be 'inserted into' the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres. - * @param resizeBehaviour A primitive int whose value will determine how - * the code should react if the image is larger than - * the cell referenced by the colNumber and - * rowNumber parameters. Four constants are provided - * to determine what should happen; - * AddDimensionedImage.EXPAND_ROW - * AddDimensionedImage.EXPAND_COLUMN - * AddDimensionedImage.EXPAND_ROW_AND_COLUMN - * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN - * @throws java.io.FileNotFoundException If the file containing the image - * cannot be located. - * @throws java.io.IOException If a problem occurs whilst reading the file - * of image data. - * @throws java.lang.IllegalArgumentException If an invalid value is passed - * to the resizeBehaviour - * parameter. - */ - private void addImageToSheet(int colNumber, int rowNumber, HSSFSheet sheet, - String imageFile, double reqImageWidthMM, double reqImageHeightMM, - int resizeBehaviour) throws FileNotFoundException, IOException, - IllegalArgumentException { - HSSFRow row = null; - HSSFClientAnchor anchor = null; - HSSFPatriarch patriarch = null; - ClientAnchorDetail rowClientAnchorDetail = null; - ClientAnchorDetail colClientAnchorDetail = null; - - // Validate the resizeBehaviour parameter. - if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) && - (resizeBehaviour != AddDimensionedImage.EXPAND_ROW) && - (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN) && - (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) { - throw new IllegalArgumentException("Invalid value passed to the " + - "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()"); - } - - // Call methods to calculate how the image and sheet should be - // manipulated to accomodate the image; columns and then rows. - colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, - reqImageWidthMM, resizeBehaviour); - rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, - reqImageHeightMM, resizeBehaviour); - - // Having determined if and how to resize the rows, columns and/or the - // image, create the HSSFClientAnchor object to position the image on - // the worksheet. Note how the two ClientAnchorDetail records are - // interrogated to recover the row/column co-ordinates and any insets. - // The first two parameters are not used currently but could be if the - // need arose to extend the functionality of this code by adding the - // ability to specify that a clear 'border' be placed around the image. - anchor = new HSSFClientAnchor(0, - 0, - colClientAnchorDetail.getInset(), - rowClientAnchorDetail.getInset(), - (short)colClientAnchorDetail.getFromIndex(), - rowClientAnchorDetail.getFromIndex(), - (short)colClientAnchorDetail.getToIndex(), - rowClientAnchorDetail.getToIndex()); - - // For now, set the anchor type to do not move or resize the - // image as the size of the row/column is adjusted. This could easilly - // become another parameter passed to the method. - //anchor.setAnchorType(HSSFClientAnchor.DONT_MOVE_AND_RESIZE); - anchor.setAnchorType(HSSFClientAnchor.MOVE_AND_RESIZE); - - // Now, add the picture to the workbook. Note that the type is assumed - // to be a JPEG/JPG, this could easily (and should) be parameterised - // however. - //int index = sheet.getWorkbook().addPicture(this.imageToBytes(imageFile), - // HSSFWorkbook.PICTURE_TYPE_JPEG); - int index = sheet.getWorkbook().addPicture(this.imageToBytes(imageFile), HSSFWorkbook.PICTURE_TYPE_PNG); - - // Get the drawing patriarch and create the picture. - patriarch = sheet.createDrawingPatriarch(); - patriarch.createPicture(anchor, index); - } - - /** - * Determines whether the sheets columns should be re-sized to accomodate - * the image, adjusts the columns width if necessary and creates then - * returns a ClientAnchorDetail object that facilitates construction of - * an HSSFClientAnchor that will fix the image on the sheet and establish - * it's size. - * - * @param sheet A reference to the sheet that will 'contain' the image. - * @param colNumber A primtive int that contains the index number of a - * column on the sheet. - * @param reqImageWidthMM A primtive double that contains the required - * width of the image in millimetres - * @param resizeBehaviour A primitve int whose value will indicate how the - * width of the column should be adjusted if the - * required width of the image is greater than the - * width of the column. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the column containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number column containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the right hand - * edge of the image can protrude into the next column - expressed - * as a specific number of co-ordinate positions. - */ - private ClientAnchorDetail fitImageToColumns(HSSFSheet sheet, int colNumber, - double reqImageWidthMM, int resizeBehaviour) { - - double colWidthMM = 0.0D; - double colCoordinatesPerMM = 0.0D; - int pictureWidthCoordinates = 0; - ClientAnchorDetail colClientAnchorDetail = null; - - // Get the colum's width in millimetres - colWidthMM = ConvertImageUnits.widthUnits2Millimetres( - (short)sheet.getColumnWidth(colNumber)); - - // Check that the column's width will accomodate the image at the - // required dimension. If the width of the column is LESS than the - // required width of the image, decide how the application should - // respond - resize the column or overlay the image across one or more - // columns. - if(colWidthMM < reqImageWidthMM) { - - // Should the column's width simply be expanded? - if((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { - // Set the width of the column by converting the required image - // width from millimetres into Excel's column width units. - sheet.setColumnWidth(colNumber, - ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM)); - // To make the image occupy the full width of the column, convert - // the required width of the image into co-ordinates. This value - // will become the inset for the ClientAnchorDetail class that - // is then instantiated. - colWidthMM = reqImageWidthMM; - colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); - colClientAnchorDetail = new ClientAnchorDetail(colNumber, - colNumber, pictureWidthCoordinates); - } - // If the user has chosen to overlay both rows and columns or just - // to expand ONLY the size of the rows, then calculate how to lay - // the image out across one or more columns. - else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) { - colClientAnchorDetail = this.calculateColumnLocation(sheet, - colNumber, reqImageWidthMM); - } - } - // If the column is wider than the image. - else { - // Mow many co-ordinate positions are there per millimetre? - colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - // Given the width of the image, what should be it's co-ordinate? - pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); - colClientAnchorDetail = new ClientAnchorDetail(colNumber, - colNumber, pictureWidthCoordinates); - } - return(colClientAnchorDetail); - } - - /** - * Determines whether the sheet's row should be re-sized to accomodate - * the image, adjusts the rows height if necessary and creates then - * returns a ClientAnchorDetail object that facilitates construction of - * an HSSFClientAnchor that will fix the image on the sheet and establish - * it's size. - * - * @param sheet A reference to the sheet that will 'contain' the image. - * @param rowNumber A primtive int that contains the index number of a - * row on the sheet. - * @param reqImageHeightMM A primtive double that contains the required - * height of the image in millimetres - * @param resizeBehaviour A primitve int whose value will indicate how the - * height of the row should be adjusted if the - * required height of the image is greater than the - * height of the row. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the row containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number of the row containing the cell whose - * top left hand corner also defines the bottom right hand - * corner of the image and an inset that determines how far the - * bottom edge of the image can protrude into the next (lower) - * row - expressed as a specific number of co-ordinate positions. - */ - private ClientAnchorDetail fitImageToRows(HSSFSheet sheet, int rowNumber, - double reqImageHeightMM, int resizeBehaviour) { - HSSFRow row = null; - double rowHeightMM = 0.0D; - double rowCoordinatesPerMM = 0.0D; - int pictureHeightCoordinates = 0; - ClientAnchorDetail rowClientAnchorDetail = null; - - // Get the row and it's height - row = sheet.getRow(rowNumber); - if(row == null) { - // Create row if it does not exist. - row = sheet.createRow(rowNumber); - } - - // Get the row's height in millimetres - rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE; - - // Check that the row's height will accomodate the image at the required - // dimensions. If the height of the row is LESS than the required height - // of the image, decide how the application should respond - resize the - // row or overlay the image across a series of rows. - if(rowHeightMM < reqImageHeightMM) { - if((resizeBehaviour == AddDimensionedImage.EXPAND_ROW) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { - row.setHeightInPoints((float)(reqImageHeightMM * - ConvertImageUnits.POINTS_PER_MILLIMETRE)); - rowHeightMM = reqImageHeightMM; - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); - rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, - rowNumber, pictureHeightCoordinates); - } - // If the user has chosen to overlay both rows and columns or just - // to expand ONLY the size of the columns, then calculate how to lay - // the image out ver one or more rows. - else if((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) { - rowClientAnchorDetail = this.calculateRowLocation(sheet, - rowNumber, reqImageHeightMM); - } - } - // Else, if the image is smaller than the space available - else { - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); - rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, - rowNumber, pictureHeightCoordinates); - } - return(rowClientAnchorDetail); - } - - /** - * If the image is to overlie more than one column, calculations need to be - * performed to determine how many columns and whether the image will - * overlie just a part of one column in order to be presented at the - * required size. - * - * @param sheet The sheet that will 'contain' the image. - * @param startingColumn A primitive int whose value is the index of the - * column that contains the cell whose top left hand - * corner should be aligned with the top left hand - * corner of the image. - * @param reqImageWidthMM A primitive double whose value will indicate the - * required width of the image in millimetres. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the column containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number column containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the right hand - * edge of the image can protrude into the next column - expressed - * as a specific number of co-ordinate positions. - */ - private ClientAnchorDetail calculateColumnLocation(HSSFSheet sheet, - int startingColumn, - double reqImageWidthMM) { - ClientAnchorDetail anchorDetail = null; - double totalWidthMM = 0.0D; - double colWidthMM = 0.0D; - double overlapMM = 0.0D; - double coordinatePositionsPerMM = 0.0D; - int toColumn = startingColumn; - int inset = 0; - - // Calculate how many columns the image will have to - // span in order to be presented at the required size. - while(totalWidthMM < reqImageWidthMM) { - colWidthMM = ConvertImageUnits.widthUnits2Millimetres( - (short)(sheet.getColumnWidth(toColumn))); - // Note use of the cell border width constant. Testing with an image - // declared to fit exactly into one column demonstrated that it's - // width was greater than the width of the column the POI returned. - // Further, this difference was a constant value that I am assuming - // related to the cell's borders. Either way, that difference needs - // to be allowed for in this calculation. - totalWidthMM += (colWidthMM + ConvertImageUnits.CELL_BORDER_WIDTH_MILLIMETRES); - toColumn++; - } - // De-crement by one the last column value. - toColumn--; - // Highly unlikely that this will be true but, if the width of a series - // of columns is exactly equal to the required width of the image, then - // simply build a ClientAnchorDetail object with an inset equal to the - // total number of co-ordinate positions available in a column, a - // from column co-ordinate (top left hand corner) equal to the value - // of the startingColumn parameter and a to column co-ordinate equal - // to the toColumn variable. - // - // Convert both values to ints to perform the test. - if((int)totalWidthMM == (int)reqImageWidthMM) { - // A problem could occur if the image is sized to fit into one or - // more columns. If that occurs, the value in the toColumn variable - // will be in error. To overcome this, there are two options, to - // ibcrement the toColumn variable's value by one or to pass the - // total number of co-ordinate positions to the third paramater - // of the ClientAnchorDetail constructor. For no sepcific reason, - // the latter option is used below. - anchorDetail = new ClientAnchorDetail(startingColumn, - toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS); - } - // In this case, the image will overlap part of another column and it is - // necessary to calculate just how much - this will become the inset - // for the ClientAnchorDetail object. - else { - // Firstly, claculate how much of the image should overlap into - // the next column. - overlapMM = reqImageWidthMM - (totalWidthMM - colWidthMM); - - // When the required size is very close indded to the column size, - // the calcaulation above can produce a negative value. To prevent - // problems occuring in later caculations, this is simply removed - // be setting the overlapMM value to zero. - if(overlapMM < 0) { - overlapMM = 0.0D; - } - - // Next, from the columns width, calculate how many co-ordinate - // positons there are per millimetre - coordinatePositionsPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - // From this figure, determine how many co-ordinat positions to - // inset the left hand or bottom edge of the image. - inset = (int)(coordinatePositionsPerMM * overlapMM); - - // Now create the ClientAnchorDetail object, setting the from and to - // columns and the inset. - anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, inset); - } - return(anchorDetail); - } - - /** - * If the image is to overlie more than one rows, calculations need to be - * performed to determine how many rows and whether the image will - * overlie just a part of one row in order to be presented at the - * required size. - * - * @param sheet The sheet that will 'contain' the image. - * @param startingRow A primitive int whose value is the index of the row - * that contains the cell whose top left hand corner - * should be aligned with the top left hand corner of - * the image. - * @param reqImageHeightMM A primitive double whose value will indicate the - * required height of the image in millimetres. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the row containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number of the row containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the bottom edge - * can protrude into the next (lower) row - expressed as a specific - * number of co-ordinate positions. - */ - private ClientAnchorDetail calculateRowLocation(HSSFSheet sheet, - int startingRow, double reqImageHeightMM) { - ClientAnchorDetail clientAnchorDetail = null; - HSSFRow row = null; - double rowHeightMM = 0.0D; - double totalRowHeightMM = 0.0D; - double overlapMM = 0.0D; - double rowCoordinatesPerMM = 0.0D; - int toRow = startingRow; - int inset = 0; - - // Step through the rows in the sheet and accumulate a total of their - // heights. - while(totalRowHeightMM < reqImageHeightMM) { - row = sheet.getRow(toRow); - // Note, if the row does not already exist on the sheet then create - // it here. - if(row == null) { - row = sheet.createRow(toRow); - } - // Get the row's height in millimetres and add to the running total. - rowHeightMM = row.getHeightInPoints() / - ConvertImageUnits.POINTS_PER_MILLIMETRE; - totalRowHeightMM += rowHeightMM; - toRow++; - } - // Owing to the way the loop above works, the rowNumber will have been - // incremented one row too far. Undo that here. - toRow--; - // Check to see whether the image should occupy an exact number of - // rows. If so, build the ClientAnchorDetail record to point - // to those rows and with an inset of the total number of co-ordinate - // position in the row. - // - // To overcome problems that can occur with comparing double values for - // equality, cast both to int(s) to truncate the value; VERY crude and - // I do not really like it!! - if((int)totalRowHeightMM == (int)reqImageHeightMM) { - clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, - ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS); - } - else { - // Calculate how far the image will project into the next row. Note - // that the height of the last row assessed is subtracted from the - // total height of all rows assessed so far. - overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM); - - // To prevent an exception being thrown when the required width of - // the image is very close indeed to the column size. - if(overlapMM < 0) { - overlapMM = 0.0D; - } - - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - inset = (int)(overlapMM * rowCoordinatesPerMM); - clientAnchorDetail = new ClientAnchorDetail(startingRow, - toRow, inset); - } - return(clientAnchorDetail); - } - - /** - * Loads - reads in and converts into an array of byte(s) - an image from - * a named file. - * - * Note: this method should be modified so that the type of the image may - * also be passed to it. Currently, it assumes that all images are - * JPG/JPEG(s). - * - * @param imageFilename A String that encapsulates the path to and name - * of the file that contains the image which is to be - * 'loaded'. - * @return An array of type byte that contains the raw data of the named - * image. - * @throws java.io.FileNotFoundException Thrown if it was not possible to - * open the specified file. - * @throws java.io.IOException Thrown if reading the file failed or was - * interrupted. - */ - private byte[] imageToBytes(String imageFilename) throws IOException { - File imageFile = null; - FileInputStream fis = null; - ByteArrayOutputStream bos = null; - int read = 0; - try { - imageFile = new File(imageFilename); - fis = new FileInputStream(imageFile); - bos = new ByteArrayOutputStream(); - while((read = fis.read()) != -1) { - bos.write(read); - } - return(bos.toByteArray()); - } - finally { - if(fis != null) { - try { - fis.close(); - fis = null; - } - catch(IOException ioEx) { - // Nothing to do here - } - } - } - } - - /** - * The main entry point to the program. It contains code that demonstrates - * one way to use the program. - * - * Note, the code is not restricted to use on new workbooks only. If an - * image is to be inserted into an existing workbook. just open that - * workbook, gat a reference to a sheet and pass that; - * - * AddDimensionedImage addImage = new AddDimensionedImage(); - * - * File file = new File("....... Existing Workbook ......."); - * FileInputStream fis = new FileInputStream(file); - * HSSFWorkbook workbook = new HSSFWorkbook(fis); - * HSSFSheet sheet = workbook.getSheetAt(0); - * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20, - * AddDimensionedImage.EXPAND.ROW); - * - * @param args the command line arguments - */ - public static void main(String[] args) { - String imageFile = null; - String outputFile = null; - FileInputStream fis = null; - FileOutputStream fos = null; - HSSFWorkbook workbook = null; - HSSFSheet sheet = null; - try { - if(args.length < 2){ - System.err.println("Usage: AddDimensionedImage imageFile outputFile"); - return; - } - imageFile = args[0]; - outputFile = args[1]; - - workbook = new HSSFWorkbook(); - sheet = workbook.createSheet("Picture Test"); - new AddDimensionedImage().addImageToSheet("A1", sheet, - imageFile, 125, 125, - AddDimensionedImage.EXPAND_ROW_AND_COLUMN); - fos = new FileOutputStream(outputFile); - workbook.write(fos); - } - catch(FileNotFoundException fnfEx) { - System.out.println("Caught an: " + fnfEx.getClass().getName()); - System.out.println("Message: " + fnfEx.getMessage()); - System.out.println("Stacktrace follows..........."); - fnfEx.printStackTrace(System.out); - } - catch(IOException ioEx) { - System.out.println("Caught an: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follows..........."); - ioEx.printStackTrace(System.out); - } - finally { - if(fos != null) { - try { - fos.close(); - fos = null; - } - catch(IOException ioEx) { - // I G N O R E - } - } - } - } - - /** - * The HSSFClientAnchor class accepts eight parameters. In order, these are; - * - * * How far the left hand edge of the image is inset from the left hand - * edge of the cell - * * How far the top edge of the image is inset from the top of the cell - * * How far the right hand edge of the image is inset from the left - * hand edge of the cell - * * How far the bottom edge of the image is inset from the top of the - * cell. - * * Together, parameters five and six determine the column and row - * co-ordinates of the cell whose top left hand corner will be aligned - * with the image's top left hand corner. - * * Together, parameter seven and eight determine the column and row - * co-ordinates of the cell whose top left hand corner will be aligned - * with the images bottom right hand corner. - * - * An instance of the ClientAnchorDetail class provides three of the eight - * parameters, one of the co-ordinates for the images top left hand corner, - * one of the co-ordinates for the images bottom right hand corner and - * either how far the image should be inset from the top or the left hand - * edge of the cell. - * - * @author Mark Beardsley [mas at apache.org] - * @version 1.00 5th August 2009. - */ - public class ClientAnchorDetail { - - public int fromIndex = 0; - public int toIndex = 0; - public int inset = 0; - - /** - * Create a new instance of the ClientAnchorDetail class using the - * following parameters. - * - * @param fromIndex A primitive int that contains one of the - * co-ordinates (row or column index) for the top left - * hand corner of the image. - * @param toIndex A primitive int that contains one of the - * co-ordinates (row or column index) for the bottom - * right hand corner of the image. - * @param inset A primitive int that contains a value which indicates - * how far the image should be inset from the top or the - * left hand edge of a cell. - */ - public ClientAnchorDetail(int fromIndex, int toIndex, int inset) { - this.fromIndex = fromIndex; - this.toIndex = toIndex; - this.inset = inset; - } - - /** - * Get one of the number of the column or row that contains the cell - * whose top left hand corner will be aligned with the top left hand - * corner of the image. - * - * @return The value - row or column index - for one of the co-ordinates - * of the top left hand corner of the image. - */ - public int getFromIndex() { - return(this.fromIndex); - } - - /** - * Get one of the number of the column or row that contains the cell - * whose top left hand corner will be aligned with the bottom righ hand - * corner of the image. - * - * @return The value - row or column index - for one of the co-ordinates - * of the bottom right hand corner of the image. - */ - public int getToIndex() { - return(this.toIndex); - } - - /** - * Get the image's offset from the edge of a cell. - * - * @return How far either the right hand or bottom edge of the image is - * inset from the left hand or top edge of a cell. - */ - public int getInset() { - return(this.inset); - } - } - - /** - * Utility methods used to convert Excel's character based column and row - * size measurements into pixels and/or millimetres. The class also contains - * various constants that are required in other calculations. - * - * @author xio[darjino@hotmail.com] - * @version 1.01 30th July 2009. - * Added by Mark Beardsley [msb at apache.org]. - * Additional constants. - * widthUnits2Millimetres() and millimetres2Units() methods. - */ - public static class ConvertImageUnits { - - // Each cell conatins a fixed number of co-ordinate points; this number - // does not vary with row height or column width or with font. These two - // constants are defined below. - public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB - public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB - // The resoultion of an image can be expressed as a specific number - // of pixels per inch. Displays and printers differ but 96 pixels per - // inch is an acceptable standard to beging with. - public static final int PIXELS_PER_INCH = 96; // MB - // Cnstants that defines how many pixels and points there are in a - // millimetre. These values are required for the conversion algorithm. - public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB - public static final double POINTS_PER_MILLIMETRE = 2.83; // MB - // The column width returned by HSSF and the width of a picture when - // positioned to exactly cover one cell are different by almost exactly - // 2mm - give or take rounding errors. This constant allows that - // additional amount to be accounted for when calculating how many - // celles the image ought to overlie. - public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB - public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; - public static final int UNIT_OFFSET_LENGTH = 7; - public static final int[] UNIT_OFFSET_MAP = new int[] - { 0, 36, 73, 109, 146, 182, 219 }; - - /** - * pixel units to excel width units(units of 1/256th of a character width) - * @param pxs - * @return - */ - public static short pixel2WidthUnits(int pxs) { - short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * - (pxs / UNIT_OFFSET_LENGTH)); - widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)]; - return widthUnits; - } - - /** - * excel width units(units of 1/256th of a character width) to pixel - * units. - * - * @param widthUnits - * @return - */ - public static int widthUnits2Pixel(short widthUnits) { - int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) - * UNIT_OFFSET_LENGTH; - int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; - pixels += Math.round((float) offsetWidthUnits / - ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); - return pixels; - } - - /** - * Convert Excel's width units into millimetres. - * - * @param widthUnits The width of the column or the height of the - * row in Excel's units. - * @return A primitive double that contains the columns width or rows - * height in millimetres. - */ - public static double widthUnits2Millimetres(short widthUnits) { - return(ConvertImageUnits.widthUnits2Pixel(widthUnits) / - ConvertImageUnits.PIXELS_PER_MILLIMETRES); - } - - /** - * Convert into millimetres Excel's width units.. - * - * @param millimetres A primitive double that contains the columns - * width or rows height in millimetres. - * @return A primitive int that contains the columns width or rows - * height in Excel's units. - */ - public static int millimetres2WidthUnits(double millimetres) { - return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres * - ConvertImageUnits.PIXELS_PER_MILLIMETRES))); - } - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Alignment.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Alignment.java deleted file mode 100644 index b54640ee73..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Alignment.java +++ /dev/null @@ -1,66 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Shows how various alignment options work. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class Alignment { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - HSSFRow row = sheet.createRow(2); - createCell(wb, row, 0, HSSFCellStyle.ALIGN_CENTER); - createCell(wb, row, 1, HSSFCellStyle.ALIGN_CENTER_SELECTION); - createCell(wb, row, 2, HSSFCellStyle.ALIGN_FILL); - createCell(wb, row, 3, HSSFCellStyle.ALIGN_GENERAL); - createCell(wb, row, 4, HSSFCellStyle.ALIGN_JUSTIFY); - createCell(wb, row, 5, HSSFCellStyle.ALIGN_LEFT); - createCell(wb, row, 6, HSSFCellStyle.ALIGN_RIGHT); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } - - /** - * Creates a cell and aligns it a certain way. - * - * @param wb the workbook - * @param row the row to create the cell in - * @param column the column number to create the cell in - * @param align the alignment for the cell. - */ - private static void createCell(HSSFWorkbook wb, HSSFRow row, int column, int align) { - HSSFCell cell = row.createCell(column); - cell.setCellValue("Align It"); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setAlignment((short)align); - cell.setCellStyle(cellStyle); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/BigExample.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/BigExample.java deleted file mode 100644 index 3981a145da..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/BigExample.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.util.HSSFColor; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Demonstrates many features of the user API at once. Used in the HOW-TO guide. - * - * @author Glen Stampoultzis (glens at apache.org) - * @author Andrew Oliver (acoliver at apache.org) - */ -public class BigExample { - public static void main(String[] args) throws IOException { - int rownum; - - // create a new file - FileOutputStream out = new FileOutputStream("workbook.xls"); - // create a new workbook - HSSFWorkbook wb = new HSSFWorkbook(); - // create a new sheet - HSSFSheet s = wb.createSheet(); - // declare a row object reference - HSSFRow r = null; - // declare a cell object reference - HSSFCell c = null; - // create 3 cell styles - HSSFCellStyle cs = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - HSSFCellStyle cs3 = wb.createCellStyle(); - // create 2 fonts objects - HSSFFont f = wb.createFont(); - HSSFFont f2 = wb.createFont(); - - //set font 1 to 12 point type - f.setFontHeightInPoints((short) 12); - //make it red - f.setColor(HSSFColor.RED.index); - // make it bold - //arial is the default font - f.setBoldweight(f.BOLDWEIGHT_BOLD); - - //set font 2 to 10 point type - f2.setFontHeightInPoints((short) 10); - //make it the color at palette index 0xf (white) - f2.setColor(HSSFColor.WHITE.index); - //make it bold - f2.setBoldweight(f2.BOLDWEIGHT_BOLD); - - //set cell stlye - cs.setFont(f); - //set the cell format see HSSFDataFromat for a full list - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - - //set a thin border - cs2.setBorderBottom(cs2.BORDER_THIN); - //fill w fg fill color - cs2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); - // set foreground fill to red - cs2.setFillForegroundColor(HSSFColor.RED.index); - - // set the font - cs2.setFont(f2); - - // set the sheet name to HSSF Test - wb.setSheetName(0, "HSSF Test"); - // create a sheet with 300 rows (0-299) - for (rownum = 0; rownum < 300; rownum++) - { - // create a row - r = s.createRow(rownum); - // on every other row - if ((rownum % 2) == 0) - { - // make the row height bigger (in twips - 1/20 of a point) - r.setHeight((short) 0x249); - } - - //r.setRowNum(( short ) rownum); - // create 50 cells (0-49) (the += 2 becomes apparent later - for (int cellnum = 0; cellnum < 50; cellnum += 2) - { - // create a numeric cell - c = r.createCell(cellnum); - // do some goofy math to demonstrate decimals - c.setCellValue(rownum * 10000 + cellnum - + (((double) rownum / 1000) - + ((double) cellnum / 10000))); - - // on every other row - if ((rownum % 2) == 0) - { - // set this cell to the first cell style we defined - c.setCellStyle(cs); - } - - // create a string cell (see why += 2 in the - c = r.createCell(cellnum + 1); - - // set the cell's string value to "TEST" - c.setCellValue("TEST"); - // make this column a bit wider - s.setColumnWidth(cellnum + 1, (int)((50 * 8) / ((double) 1 / 20))); - - // on every other row - if ((rownum % 2) == 0) - { - // set this to the white on red cell style - // we defined above - c.setCellStyle(cs2); - } - - } - } - - //draw a thick black border on the row at the bottom using BLANKS - // advance 2 rows - rownum++; - rownum++; - - r = s.createRow(rownum); - - // define the third style to be the default - // except with a thick black border at the bottom - cs3.setBorderBottom(cs3.BORDER_THICK); - - //create 50 cells - for (int cellnum =0; cellnum < 50; cellnum++) { - //create a blank type cell (no value) - c = r.createCell(cellnum); - // set it to the thick black border style - c.setCellStyle(cs3); - } - - //end draw thick black border - - - // demonstrate adding/naming and deleting a sheet - // create a sheet, set its title then delete it - s = wb.createSheet(); - wb.setSheetName(1, "DeletedSheet"); - wb.removeSheetAt(1); - //end deleted sheet - - // write the workbook to the output stream - // close our file (don't blow out our file handles - wb.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java deleted file mode 100644 index d29635004a..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.util.HSSFColor; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Demonstrates how to create borders around cells. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class Borders { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(1); - - // Create a cell and put a value in it. - HSSFCell cell = row.createCell(1); - cell.setCellValue(4); - - // Style the cell with borders all around. - HSSFCellStyle style = wb.createCellStyle(); - style.setBorderBottom(HSSFCellStyle.BORDER_THIN); - style.setBottomBorderColor(HSSFColor.BLACK.index); - style.setBorderLeft(HSSFCellStyle.BORDER_THIN); - style.setLeftBorderColor(HSSFColor.GREEN.index); - style.setBorderRight(HSSFCellStyle.BORDER_THIN); - style.setRightBorderColor(HSSFColor.BLUE.index); - style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED); - style.setTopBorderColor(HSSFColor.ORANGE.index); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java deleted file mode 100644 index c3a213d582..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java +++ /dev/null @@ -1,98 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.util.HSSFColor; - -import java.io.*; - -/** - * Demonstrates how to work with excel cell comments. - * - *

      - * Excel comment is a kind of a text shape, - * so inserting a comment is very similar to placing a text box in a worksheet - *

      - * - * @author Yegor Kozlov - */ -public class CellComments { - - public static void main(String[] args) throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF"); - - // Create the drawing patriarch. This is the top level container for all shapes including cell comments. - HSSFPatriarch patr = sheet.createDrawingPatriarch(); - - //create a cell in row 3 - HSSFCell cell1 = sheet.createRow(3).createCell(1); - cell1.setCellValue(new HSSFRichTextString("Hello, World")); - - //anchor defines size and position of the comment in worksheet - HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5)); - - // set text in the comment - comment1.setString(new HSSFRichTextString("We can set comments in POI")); - - //set comment author. - //you can see it in the status bar when moving mouse over the commented cell - comment1.setAuthor("Apache Software Foundation"); - - // The first way to assign comment to a cell is via HSSFCell.setCellComment method - cell1.setCellComment(comment1); - - //create another cell in row 6 - HSSFCell cell2 = sheet.createRow(6).createCell(1); - cell2.setCellValue(36.6); - - - HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 8, (short) 6, 11)); - //modify background color of the comment - comment2.setFillColor(204, 236, 255); - - HSSFRichTextString string = new HSSFRichTextString("Normal body temperature"); - - //apply custom font to the text in the comment - HSSFFont font = wb.createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short)10); - font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - font.setColor(HSSFColor.RED.index); - string.applyFont(font); - - comment2.setString(string); - comment2.setVisible(true); //by default comments are hidden. This one is always visible. - - comment2.setAuthor("Bill Gates"); - - /** - * The second way to assign comment to a cell is to implicitly specify its row and column. - * Note, it is possible to set row and column of a non-existing cell. - * It works, the comment is visible. - */ - comment2.setRow(6); - comment2.setColumn(1); - - FileOutputStream out = new FileOutputStream("poi_comment.xls"); - wb.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java deleted file mode 100644 index 07b9b0165a..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -public class CellTypes { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - HSSFRow row = sheet.createRow(2); - row.createCell(0).setCellValue(1.1); - row.createCell(1).setCellValue(new Date()); - row.createCell(2).setCellValue("a string"); - row.createCell(3).setCellValue(true); - row.createCell(4).setCellType(HSSFCell.CELL_TYPE_ERROR); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java deleted file mode 100644 index ff8a0b73ca..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFCell; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Illustrates how to create cell values. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class CreateCells { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(0); - // Create a cell and put a value in it. - HSSFCell cell = row.createCell(0); - cell.setCellValue(1); - - // Or do it on one line. - row.createCell(1).setCellValue(1.2); - row.createCell(2).setCellValue("This is a string"); - row.createCell(3).setCellValue(true); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java deleted file mode 100644 index 746fd536b8..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -/** - * An example on how to cells with dates. The important thing to note - * about dates is that they are really normal numeric cells that are - * formatted specially. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class CreateDateCells { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(0); - - // Create a cell and put a date value in it. The first cell is not styled as a date. - HSSFCell cell = row.createCell(0); - cell.setCellValue(new Date()); - - // we style the second cell as a date (and time). It is important to create a new cell style from the workbook - // otherwise you can end up modifying the built in style and effecting not only this cell but other cells. - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); - cell = row.createCell(1); - cell.setCellValue(new Date()); - cell.setCellStyle(cellStyle); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmeddedObjects.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmeddedObjects.java deleted file mode 100644 index bb6f19d0a5..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmeddedObjects.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hslf.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.SlideShow; - -import java.io.FileInputStream; -import java.util.Iterator; - -/** - * Demonstrates how you can extract embedded data from a .xls file - */ -public class EmeddedObjects { - public static void main(String[] args) throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0])); - HSSFWorkbook workbook = new HSSFWorkbook(fs); - for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) { - //the OLE2 Class Name of the object - String oleName = obj.getOLE2ClassName(); - if (oleName.equals("Worksheet")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, fs, false); - //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets()); - } else if (oleName.equals("Document")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - HWPFDocument embeddedWordDocument = new HWPFDocument(dn); - //System.out.println(entry.getName() + ": " + embeddedWordDocument.getRange().text()); - } else if (oleName.equals("Presentation")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - SlideShow embeddedPowerPointDocument = new SlideShow(new HSLFSlideShow(dn)); - //System.out.println(entry.getName() + ": " + embeddedPowerPointDocument.getSlides().length); - } else { - if(obj.hasDirectoryEntry()){ - // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - for (Iterator entries = dn.getEntries(); entries.hasNext();) { - Entry entry = (Entry) entries.next(); - //System.out.println(oleName + "." + entry.getName()); - } - } else { - // There is no DirectoryEntry - // Recover the object's data from the HSSFObjectData instance. - byte[] objectData = obj.getObjectData(); - } - } - } - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/EventExample.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/EventExample.java deleted file mode 100644 index c5644c9597..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/EventExample.java +++ /dev/null @@ -1,118 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.record.*; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * This example shows how to use the event API for reading a file. - */ -public class EventExample - implements HSSFListener -{ - private SSTRecord sstrec; - - /** - * This method listens for incoming records and handles them as required. - * @param record The record that was found while reading. - */ - public void processRecord(Record record) - { - switch (record.getSid()) - { - // the BOFRecord can represent either the beginning of a sheet or the workbook - case BOFRecord.sid: - BOFRecord bof = (BOFRecord) record; - if (bof.getType() == bof.TYPE_WORKBOOK) - { - System.out.println("Encountered workbook"); - // assigned to the class level member - } else if (bof.getType() == bof.TYPE_WORKSHEET) - { - System.out.println("Encountered sheet reference"); - } - break; - case BoundSheetRecord.sid: - BoundSheetRecord bsr = (BoundSheetRecord) record; - System.out.println("New sheet named: " + bsr.getSheetname()); - break; - case RowRecord.sid: - RowRecord rowrec = (RowRecord) record; - System.out.println("Row found, first column at " - + rowrec.getFirstCol() + " last column at " + rowrec.getLastCol()); - break; - case NumberRecord.sid: - NumberRecord numrec = (NumberRecord) record; - System.out.println("Cell found with value " + numrec.getValue() - + " at row " + numrec.getRow() + " and column " + numrec.getColumn()); - break; - // SSTRecords store a array of unique strings used in Excel. - case SSTRecord.sid: - sstrec = (SSTRecord) record; - for (int k = 0; k < sstrec.getNumUniqueStrings(); k++) - { - System.out.println("String table value " + k + " = " + sstrec.getString(k)); - } - break; - case LabelSSTRecord.sid: - LabelSSTRecord lrec = (LabelSSTRecord) record; - System.out.println("String cell found with value " - + sstrec.getString(lrec.getSSTIndex())); - break; - } - } - - /** - * Read an excel file and spit out what we find. - * - * @param args Expect one argument that is the file to read. - * @throws IOException When there is an error processing the file. - */ - public static void main(String[] args) throws IOException - { - // create a new file input stream with the input file specified - // at the command line - FileInputStream fin = new FileInputStream(args[0]); - // create a new org.apache.poi.poifs.filesystem.Filesystem - POIFSFileSystem poifs = new POIFSFileSystem(fin); - // get the Workbook (excel part) stream in a InputStream - InputStream din = poifs.createDocumentInputStream("Workbook"); - // construct out HSSFRequest object - HSSFRequest req = new HSSFRequest(); - // lazy listen for ALL records with the listener shown above - req.addListenerForAllRecords(new EventExample()); - // create our event factory - HSSFEventFactory factory = new HSSFEventFactory(); - // process our events based on the document input stream - factory.processEvents(req, din); - // once all the events are processed close our file input stream - fin.close(); - // and our document input stream (don't want to leak these!) - din.close(); - System.out.println("done."); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java deleted file mode 100644 index 02b7cb3e39..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.util.HSSFColor; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Shows how to use various fills. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class FrillsAndFills { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(1); - - // Aqua background - HSSFCellStyle style = wb.createCellStyle(); - style.setFillBackgroundColor(HSSFColor.AQUA.index); - style.setFillPattern(HSSFCellStyle.BIG_SPOTS); - HSSFCell cell = row.createCell(1); - cell.setCellValue("X"); - cell.setCellStyle(style); - - // Orange "foreground", foreground being the fill foreground not the font color. - style = wb.createCellStyle(); - style.setFillForegroundColor(HSSFColor.ORANGE.index); - style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); - cell = row.createCell(2); - cell.setCellValue("X"); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java deleted file mode 100644 index 3cc124b67b..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java +++ /dev/null @@ -1,244 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * File for HSSF testing/examples - * - * THIS IS NOT THE MAIN HSSF FILE!! This is a utility for testing functionality. - * It does contain sample API usage that may be educational to regular API - * users. - * - * @see #main - * @author Andrew Oliver (acoliver at apache dot org) - */ -public final class HSSFReadWrite { - - /** - * creates an {@link HSSFWorkbook} the specified OS filename. - */ - private static HSSFWorkbook readFile(String filename) throws IOException { - return new HSSFWorkbook(new FileInputStream(filename)); - } - - /** - * given a filename this outputs a sample sheet with just a set of - * rows/cells. - */ - private static void testCreateSampleSheet(String outputFilename) throws IOException { - int rownum; - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - HSSFCellStyle cs3 = wb.createCellStyle(); - HSSFFont f = wb.createFont(); - HSSFFont f2 = wb.createFont(); - - f.setFontHeightInPoints((short) 12); - f.setColor((short) 0xA); - f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - f2.setFontHeightInPoints((short) 10); - f2.setColor((short) 0xf); - f2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - cs.setFont(f); - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - cs2.setBorderBottom(HSSFCellStyle.BORDER_THIN); - cs2.setFillPattern((short) 1); // fill w fg - cs2.setFillForegroundColor((short) 0xA); - cs2.setFont(f2); - wb.setSheetName(0, "HSSF Test"); - for (rownum = 0; rownum < 300; rownum++) { - HSSFRow r = s.createRow(rownum); - if ((rownum % 2) == 0) { - r.setHeight((short) 0x249); - } - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - HSSFCell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + (((double) rownum / 1000) + ((double) cellnum / 10000))); - if ((rownum % 2) == 0) { - c.setCellStyle(cs); - } - c = r.createCell(cellnum + 1); - c.setCellValue(new HSSFRichTextString("TEST")); - // 50 characters divided by 1/20th of a point - s.setColumnWidth(cellnum + 1, (int) (50 * 8 / 0.05)); - if ((rownum % 2) == 0) { - c.setCellStyle(cs2); - } - } - } - - // draw a thick black border on the row at the bottom using BLANKS - rownum++; - rownum++; - HSSFRow r = s.createRow(rownum); - cs3.setBorderBottom(HSSFCellStyle.BORDER_THICK); - for (int cellnum = 0; cellnum < 50; cellnum++) { - HSSFCell c = r.createCell(cellnum); - c.setCellStyle(cs3); - } - s.addMergedRegion(new CellRangeAddress(0, 3, 0, 3)); - s.addMergedRegion(new CellRangeAddress(100, 110, 100, 110)); - - // end draw thick black border - // create a sheet, set its title then delete it - s = wb.createSheet(); - wb.setSheetName(1, "DeletedSheet"); - wb.removeSheetAt(1); - - // end deleted sheet - FileOutputStream out = new FileOutputStream(outputFilename); - wb.write(out); - out.close(); - } - - /** - * Method main - * - * Given 1 argument takes that as the filename, inputs it and dumps the - * cell values/types out to sys.out.
      - * - * given 2 arguments where the second argument is the word "write" and the - * first is the filename - writes out a sample (test) spreadsheet - * see {@link HSSFReadWrite#testCreateSampleSheet(String)}.
      - * - * given 2 arguments where the first is an input filename and the second - * an output filename (not write), attempts to fully read in the - * spreadsheet and fully write it out.
      - * - * given 3 arguments where the first is an input filename and the second an - * output filename (not write) and the third is "modify1", attempts to read in the - * spreadsheet, deletes rows 0-24, 74-99. Changes cell at row 39, col 3 to - * "MODIFIED CELL" then writes it out. Hence this is "modify test 1". If you - * take the output from the write test, you'll have a valid scenario. - */ - public static void main(String[] args) { - if (args.length < 1) { - System.err.println("At least one argument expected"); - return; - } - - String fileName = args[0]; - try { - if (args.length < 2) { - - HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); - - System.out.println("Data dump:\n"); - - for (int k = 0; k < wb.getNumberOfSheets(); k++) { - HSSFSheet sheet = wb.getSheetAt(k); - int rows = sheet.getPhysicalNumberOfRows(); - System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows - + " row(s)."); - for (int r = 0; r < rows; r++) { - HSSFRow row = sheet.getRow(r); - if (row == null) { - continue; - } - - int cells = row.getPhysicalNumberOfCells(); - System.out.println("\nROW " + row.getRowNum() + " has " + cells - + " cell(s)."); - for (int c = 0; c < cells; c++) { - HSSFCell cell = row.getCell(c); - String value = null; - - switch (cell.getCellType()) { - - case HSSFCell.CELL_TYPE_FORMULA: - value = "FORMULA value=" + cell.getCellFormula(); - break; - - case HSSFCell.CELL_TYPE_NUMERIC: - value = "NUMERIC value=" + cell.getNumericCellValue(); - break; - - case HSSFCell.CELL_TYPE_STRING: - value = "STRING value=" + cell.getStringCellValue(); - break; - - default: - } - System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" - + value); - } - } - } - } else if (args.length == 2) { - if (args[1].toLowerCase().equals("write")) { - System.out.println("Write mode"); - long time = System.currentTimeMillis(); - HSSFReadWrite.testCreateSampleSheet(fileName); - - System.out.println("" + (System.currentTimeMillis() - time) - + " ms generation time"); - } else { - System.out.println("readwrite test"); - HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); - FileOutputStream stream = new FileOutputStream(args[1]); - - wb.write(stream); - stream.close(); - } - } else if (args.length == 3 && args[2].toLowerCase().equals("modify1")) { - // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!" - - HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); - FileOutputStream stream = new FileOutputStream(args[1]); - HSSFSheet sheet = wb.getSheetAt(0); - - for (int k = 0; k < 25; k++) { - HSSFRow row = sheet.getRow(k); - - sheet.removeRow(row); - } - for (int k = 74; k < 100; k++) { - HSSFRow row = sheet.getRow(k); - - sheet.removeRow(row); - } - HSSFRow row = sheet.getRow(39); - HSSFCell cell = row.getCell(3); - cell.setCellValue("MODIFIED CELL!!!!!"); - - wb.write(stream); - stream.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java deleted file mode 100644 index 8ed9213bfa..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Test if hyperlink formula, with url that got more than 127 characters, works - * - * @author Bernard Chesnoy - */ -public class HyperlinkFormula { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - HSSFRow row = sheet.createRow(0); - - HSSFCell cell = row.createCell(0); - cell.setCellType(HSSFCell.CELL_TYPE_FORMULA); - cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")"); - - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java deleted file mode 100644 index 0872749d02..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.util.HSSFColor; - -import java.io.IOException; -import java.io.FileOutputStream; - -/** - * Demonstrates how to create hyperlinks. - * - * @author Yegor Kozlov (yegor at apach.org) - */ -public class Hyperlinks { - - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - //cell style for hyperlinks - //by default hyperlinks are blue and underlined - HSSFCellStyle hlink_style = wb.createCellStyle(); - HSSFFont hlink_font = wb.createFont(); - hlink_font.setUnderline(HSSFFont.U_SINGLE); - hlink_font.setColor(HSSFColor.BLUE.index); - hlink_style.setFont(hlink_font); - - HSSFCell cell; - HSSFSheet sheet = wb.createSheet("Hyperlinks"); - - //URL - cell = sheet.createRow(0).createCell(0); - cell.setCellValue("URL Link"); - HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL); - link.setAddress("http://poi.apache.org/"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //link to a file in the current directory - cell = sheet.createRow(1).createCell(0); - cell.setCellValue("File Link"); - link = new HSSFHyperlink(HSSFHyperlink.LINK_FILE); - link.setAddress("link1.xls"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //e-mail link - cell = sheet.createRow(2).createCell(0); - cell.setCellValue("Email Link"); - link = new HSSFHyperlink(HSSFHyperlink.LINK_EMAIL); - //note, if subject contains white spaces, make sure they are url-encoded - link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //link to a place in this workbook - - //create a target sheet and cell - HSSFSheet sheet2 = wb.createSheet("Target Sheet"); - sheet2.createRow(0).createCell(0).setCellValue("Target Cell"); - - cell = sheet.createRow(3).createCell(0); - cell.setCellValue("Worksheet Link"); - link = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT); - link.setAddress("'Target Sheet'!A1"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - FileOutputStream out = new FileOutputStream("hssf-links.xls"); - wb.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/InCellLists.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/InCellLists.java deleted file mode 100644 index 3ecd30e450..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/InCellLists.java +++ /dev/null @@ -1,569 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; - -/** - * This class contains code that demonstrates how to insert plain, numbered - * and bulleted lists into an Excel spreadsheet cell. - * - * Look at the code contained in the demonstrateMethodCalls() method. It calls - * other methods that create plain, numbered and bulleted single and - * multi-level lists. The demonstrateMethodCalls() method appears at the top - * of the class definition. - * - * Though different methods are provided to construct single and multi-level - * plain, numbered and bulleted lists, close examination will reveal that they - * are not strictly necessary. If the inputs to the listInCell() and - * multilLevelListInCell() methods are constructed to include the bullet - * character or the item numbers then these methods alone may be sufficient. - * - * @author Mark Beardsley [msb at apache.org] - */ -public class InCellLists { - - // This character looks like a solid, black, loser case letter 'o' - // positioned up from the base line of the text. - private static final char BULLET_CHARACTER = '\u2022'; - - // The tab character - \t - cannot be used to create a tab space - // within a cell as it is rendered as a square. Therefore, four - // spaces are used to simulate that character. - private static final String TAB = " "; - - /** - * Call each of the list creation methods. - * - * @param outputFilename A String that encapsulates the name of and path to - * the Excel spreadsheet file this code will create. - */ - public void demonstrateMethodCalls(String outputFilename) { - HSSFWorkbook workbook = null; - HSSFSheet sheet = null; - HSSFRow row = null; - HSSFCell cell = null; - File outputFile = null; - FileOutputStream fos = null; - ArrayList multiLevelListItems = null; - ArrayList listItems = null; - String listItem = null; - try { - workbook = new HSSFWorkbook(); - sheet = workbook.createSheet("In Cell Lists"); - row = sheet.createRow(0); - - // Create a cell at A1 and insert a single, bulleted, item into - // that cell. - cell = row.createCell(0); - this.bulletedItemInCell(workbook, "List Item", cell); - - // Create a cell at A2 and insert a plain list - that is one - // whose items are neither bulleted or numbered - into that cell. - row = sheet.createRow(1); - cell = row.createCell(0); - listItems = new ArrayList(); - listItems.add("List Item One."); - listItems.add("List Item Two."); - listItems.add("List Item Three."); - listItems.add("List Item Four."); - this.listInCell(workbook, listItems, cell); - // The row height and cell width are set here to ensure that the - // list may be seen. - row.setHeight((short)1100); - sheet.setColumnWidth(0, 9500); - - // Create a cell at A3 and insert a numbered list into that cell. - // Note that a couple of items have been added to the listItems - // ArrayList - row = sheet.createRow(2); - cell = row.createCell(0); - listItems.add("List Item Five."); - listItems.add("List Item Six."); - this.numberedListInCell(workbook, listItems, cell, 1, 2); - row.setHeight((short)1550); - - // Create a cell at A4 and insert a numbered list into that cell. - // Note that a couple of items have been added to the listItems - // ArrayList - row = sheet.createRow(3); - cell = row.createCell(0); - listItems.add("List Item Seven."); - listItems.add("List Item Eight."); - listItems.add("List Item Nine."); - listItems.add("List Item Ten."); - this.bulletedListInCell(workbook, listItems, cell); - row.setHeight((short)2550); - - // Insert a plain, multi-level list into cell A5. Note that - // the major difference here is that the list items are passed as - // an ArrayList of MultiLevelListItems. Note that an ArrayList - // of instances of an inner class was used here in preference to - // a Hashtable or HashMap as the ArrayList will preserve the - // ordering of the items added to it; the first item added will - // be the first item recovered and the last item added, the last - // item recovered. - row = sheet.createRow(4); - cell = row.createCell(0); - multiLevelListItems = new ArrayList(); - listItems = new ArrayList(); - listItems.add("ML List Item One - Sub Item One."); - listItems.add("ML List Item One - Sub Item Two."); - listItems.add("ML List Item One - Sub Item Three."); - listItems.add("ML List Item One - Sub Item Four."); - multiLevelListItems.add(new MultiLevelListItem("List Item One.", listItems)); - // Passing either null or an empty ArrayList will signal that - // there are no lower level items associated with the top level - // item - multiLevelListItems.add(new MultiLevelListItem("List Item Two.", null)); - multiLevelListItems.add(new MultiLevelListItem("List Item Three.", null)); - listItems = new ArrayList(); - listItems.add("ML List Item Four - Sub Item One."); - listItems.add("ML List Item Four - Sub Item Two."); - listItems.add("ML List Item Four - Sub Item Three."); - multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems)); - this.multiLevelListInCell(workbook, multiLevelListItems, cell); - row.setHeight((short)2800); - - // Insert a numbered multi-level list into cell A6. Note that the - // same ArrayList as constructed for the above plain multi-level - // list example will be re-used - row = sheet.createRow(5); - cell = row.createCell(0); - this.multiLevelNumberedListInCell(workbook, multiLevelListItems, - cell, 1, 1, 1, 2); - row.setHeight((short)2800); - - // Insert a numbered multi-level list into cell A7. Note that the - // same ArrayList as constructed for the plain multi-level list - // example will be re-used - row = sheet.createRow(6); - cell = row.createCell(0); - this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell); - row.setHeight((short)2800); - - // Save the completed workbook - outputFile = new File(outputFilename); - fos = new FileOutputStream(outputFile); - workbook.write(fos); - } - catch(FileNotFoundException fnfEx) { - System.out.println("Caught a: " + fnfEx.getClass().getName()); - System.out.println("Message: " + fnfEx.getMessage()); - System.out.println("Stacktrace follows..........."); - fnfEx.printStackTrace(System.out); - } - catch(IOException ioEx) { - System.out.println("Caught a: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follows..........."); - ioEx.printStackTrace(System.out); - } - finally { - if(fos != null) { - try { - fos.close(); - } - catch(IOException ioEx) { - - } - } - } - } - - /** - * Inserts a single bulleted item into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param listItem An instance of the String class encapsulating the - * items text. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list item - * will be written. - */ - public void bulletedItemInCell(HSSFWorkbook workbook, String listItem, HSSFCell cell) { - // A format String must be built to ensure that the contents of the - // cell appear as a bulleted item. - HSSFDataFormat format = workbook.createDataFormat(); - String formatString = InCellLists.BULLET_CHARACTER + " @"; - int formatIndex = format.getFormat(formatString); - - // Construct an HSSFCellStyle and set it's data formt to use the - // object created above. - HSSFCellStyle bulletStyle = workbook.createCellStyle(); - bulletStyle.setDataFormat((short)formatIndex); - - // Set the cells contents and style. - cell.setCellValue(new HSSFRichTextString(listItem)); - cell.setCellStyle(bulletStyle); - } - - /** - * Inserts a list of plain items - that is items that are neither - * numbered or bulleted - into a single cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param listItems An ArrayList whose elements encapsulate the text for - * the list's items. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - */ - public void listInCell(HSSFWorkbook workbook, ArrayList listItems, HSSFCell cell) { - StringBuffer buffer = new StringBuffer(); - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - for(String listItem : listItems) { - buffer.append(listItem); - buffer.append("\n"); - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Inserts a numbered list into a single cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param listItems An ArrayList whose elements encapsulate the text for - * the lists items. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - * @param startingValue A primitive int containing the number for the first - * item in the list. - * @param increment A primitive int containing the value that should be used - * to calculate subsequent item numbers. - */ - public void numberedListInCell(HSSFWorkbook workbook, - ArrayList listItems, - HSSFCell cell, - int startingValue, - int increment) { - StringBuffer buffer = new StringBuffer(); - int itemNumber = startingValue; - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Note that the basic method is identical to the listInCell() method - // with one difference; a number prefixed to the items text. - for(String listItem : listItems) { - buffer.append(String.valueOf(itemNumber) + ". "); - buffer.append(listItem); - buffer.append("\n"); - itemNumber += increment; - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Insert a bulleted list into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param listItems An ArrayList whose elements encapsulate the text for - * the lists items. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - */ - public void bulletedListInCell(HSSFWorkbook workbook, - ArrayList listItems, - HSSFCell cell) { - StringBuffer buffer = new StringBuffer(); - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Note that the basic method is identical to the listInCell() method - // with one difference; the bullet character prefixed to the items text. - for(String listItem : listItems) { - buffer.append(InCellLists.BULLET_CHARACTER + " "); - buffer.append(listItem); - buffer.append("\n"); - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Insert a multi-level list into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param multiLevelListItems An ArrayList whose elements contain instances - * of the MultiLevelListItem class. Each element - * encapsulates the text for the high level item - * along with an ArrayList. Each element of this - * ArrayList encapsulates the text for a lower - * level item. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - */ - public void multiLevelListInCell(HSSFWorkbook workbook, - ArrayList multiLevelListItems, - HSSFCell cell) { - StringBuffer buffer = new StringBuffer(); - ArrayList lowerLevelItems = null; - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Step through the ArrayList of MultilLevelListItem instances. - for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { - // For each element in the ArrayList, get the text for the high - // level list item...... - buffer.append(multiLevelListItem.getItemText()); - buffer.append("\n"); - // and then an ArrayList whose elements encapsulate the text - // for the lower level list items. - lowerLevelItems = multiLevelListItem.getLowerLevelItems(); - if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { - for(String item : lowerLevelItems) { - buffer.append(InCellLists.TAB); - buffer.append(item); - buffer.append("\n"); - } - } - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Insert a multi-level list into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param multiLevelListItems An ArrayList whose elements contain instances - * of the MultiLevelListItem class. Each element - * encapsulates the text for the high level item - * along with an ArrayList. Each element of this - * ArrayList encapsulates the text for a lower - * level item. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - * @param highLevelStartingValue A primitive int containing the number - * for the first high level item in the list. - * @param highLevelIncrement A primitive int containing the value that - * should be used to calculate the number of - * subsequent high level item. - * @param lowLevelStartingValue A primitive int will containing the number - * for the first low level item associated - * with a high level item. - * @param lowLevelIncrement A primitive int containing the value that - * should be used to calculate the number of - * subsequent low level item. - */ - public void multiLevelNumberedListInCell(HSSFWorkbook workbook, - ArrayList multiLevelListItems, - HSSFCell cell, - int highLevelStartingValue, - int highLevelIncrement, - int lowLevelStartingValue, - int lowLevelIncrement) { - StringBuffer buffer = new StringBuffer(); - int highLevelItemNumber = highLevelStartingValue; - int lowLevelItemNumber = 0; - ArrayList lowerLevelItems = null; - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Step through the ArrayList of MultilLevelListItem instances. - for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { - // For each element in the ArrayList, get the text for the high - // level list item...... - buffer.append(String.valueOf(highLevelItemNumber)); - buffer.append(". "); - buffer.append(multiLevelListItem.getItemText()); - buffer.append("\n"); - // and then an ArrayList whose elements encapsulate the text - // for the lower level list items. - lowerLevelItems = multiLevelListItem.getLowerLevelItems(); - if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { - lowLevelItemNumber = lowLevelStartingValue; - for(String item : lowerLevelItems) { - buffer.append(InCellLists.TAB); - buffer.append(String.valueOf(highLevelItemNumber)); - buffer.append("."); - buffer.append(String.valueOf(lowLevelItemNumber)); - buffer.append(" "); - buffer.append(item); - buffer.append("\n"); - lowLevelItemNumber += lowLevelIncrement; - } - } - highLevelItemNumber += highLevelIncrement; - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Insert a bulleted multi-level list into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param multiLevelListItems An ArrayList whose elements contain instances - * of the MultiLevelListItem class. Each element - * encapsulates the text for the high level item - * along with an ArrayList. Each element of this - * ArrayList encapsulates the text for a lower - * level item. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - */ - public void multiLevelBulletedListInCell(HSSFWorkbook workbook, - ArrayList multiLevelListItems, - HSSFCell cell) { - StringBuffer buffer = new StringBuffer(); - ArrayList lowerLevelItems = null; - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Step through the ArrayList of MultilLevelListItem instances. - for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { - // For each element in the ArrayList, get the text for the high - // level list item...... - buffer.append(InCellLists.BULLET_CHARACTER); - buffer.append(" "); - buffer.append(multiLevelListItem.getItemText()); - buffer.append("\n"); - // and then an ArrayList whose elements encapsulate the text - // for the lower level list items. - lowerLevelItems = multiLevelListItem.getLowerLevelItems(); - if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { - for(String item : lowerLevelItems) { - buffer.append(InCellLists.TAB); - buffer.append(InCellLists.BULLET_CHARACTER); - buffer.append(" "); - buffer.append(item); - buffer.append("\n"); - } - } - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * The main entry point to the program. Demonstrates how to call the method - * that will create an Excel workbook containing many different sorts of - * lists. - * - * @param args the command line arguments. - */ - public static void main(String[] args) { - new InCellLists().demonstrateMethodCalls("C:/temp/Latest In Cell List.xls"); - } - - /** - * An instance of this inner class models an item or element in a - * multi-level list. Each multi-level list item consists of the text for the - * high level items and an ArrayList containing the text for each of the - * associated lower level items. When written into a cell, each multi-level - * list item will have this general appearance. - * - * Item One - * Sub Item One. - * Sub Item Two. - * Item Two - * Sub Item One. - * Sub Item Two. - * etc. - * - * It would be quite possible to modify this class to model much more - * complex list structures descending through two, three or even more - * levels. - */ - public final class MultiLevelListItem { - - private String itemText = null; - private ArrayList lowerLevelItems = null; - - /** - * Create a new instance of the MultiLevelListItem class using the - * following parameters. - * - * @param itemText A String that encapsulates the text for the high - * level list item. - * @param lowerLevelItems An ArrayList whose elements encapsulate the - * text for the associated lower level list - * items. - */ - public MultiLevelListItem(String itemText, ArrayList lowerLevelItems) { - this.itemText = itemText; - this.lowerLevelItems = lowerLevelItems; - } - - /** - * Get the text for the high level list item. - * - * @return A String that encapsulates the text for the high level list - * item. - */ - public String getItemText() { - return(this.itemText); - } - - /** - * Get the text for the associated lower level list items. - * - * @return An ArrayList whose elements each encapsulate the text for a - * single associated lower level list item. - */ - public ArrayList getLowerLevelItems() { - return(this.lowerLevelItems); - } - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java deleted file mode 100644 index 31e5215b8e..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; - -import java.io.IOException; -import java.io.FileOutputStream; - -/** - * An example of how to merge regions of cells. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class MergedCells { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - HSSFRow row = sheet.createRow(1); - HSSFCell cell = row.createCell(1); - cell.setCellValue("This is a test of merging"); - - sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2)); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java deleted file mode 100644 index 7653a0b527..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Demonstrates how to use newlines in cells. - * - * @author Glen Stampoultzis (glens at apache.org) - * @author Fauzia Lala - */ -public class NewLinesInCells { - public static void main( String[] args ) throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - HSSFCellStyle cs = wb.createCellStyle(); - HSSFFont f2 = wb.createFont(); - - cs = wb.createCellStyle(); - - cs.setFont(f2); - // Word Wrap MUST be turned on - cs.setWrapText(true); - - r = s.createRow(2); - r.setHeight((short) 0x349); - c = r.createCell(2); - c.setCellType(HSSFCell.CELL_TYPE_STRING); - c.setCellValue("Use \n with word wrap on to create a new line"); - c.setCellStyle(cs); - s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20))); - - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewSheet.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewSheet.java deleted file mode 100644 index 40754feec4..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewSheet.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.ss.util.WorkbookUtil; - -import java.io.IOException; -import java.io.FileOutputStream; - -/** - * Creates a new workbook with a sheet that's been explicitly defined. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class NewSheet { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - HSSFSheet sheet2 = wb.createSheet(); // create with default name - final String name = "second sheet"; - wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name)); // setting sheet name later - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java deleted file mode 100644 index c1614e6c1a..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java +++ /dev/null @@ -1,42 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * This example creates a new blank workbook. This workbook will contain a single blank sheet. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class NewWorkbook -{ - public static void main(String[] args) - throws IOException - { - HSSFWorkbook wb = new HSSFWorkbook(); - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java deleted file mode 100644 index 1b580d35f0..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java +++ /dev/null @@ -1,321 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.io.*; - -/** - * Demonstrates how to use the office drawing capabilities of POI. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class OfficeDrawing { - public static void main(String[] args) throws IOException { - // Create the workbook and sheets. - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - HSSFSheet sheet2 = wb.createSheet("second sheet"); - HSSFSheet sheet3 = wb.createSheet("third sheet"); - HSSFSheet sheet4 = wb.createSheet("fourth sheet"); - HSSFSheet sheet5 = wb.createSheet("fifth sheet"); - - // Draw stuff in them - drawSheet1( sheet1 ); - drawSheet2( sheet2 ); - drawSheet3( sheet3 ); - drawSheet4( sheet4, wb ); - drawSheet5( sheet5, wb ); - - // Write the file out. - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } - - private static void drawSheet1( HSSFSheet sheet1 ) - { - // Create a row and size one of the cells reasonably large. - HSSFRow row = sheet1.createRow(2); - row.setHeight((short) 2800); - row.createCell(1); - sheet1.setColumnWidth(2, 9000); - - // Create the drawing patriarch. This is the top level container for - // all shapes. - HSSFPatriarch patriarch = sheet1.createDrawingPatriarch(); - - // Draw some lines and an oval. - drawLinesToCenter( patriarch ); - drawManyLines( patriarch ); - drawOval( patriarch ); - drawPolygon( patriarch ); - - // Draw a rectangle. - HSSFSimpleShape rect = patriarch.createSimpleShape( new HSSFClientAnchor(100, 100, 900, 200, (short)0, 0, (short)0, 0) ); - rect.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - } - - private static void drawSheet2( HSSFSheet sheet2 ) - { - // Create a row and size one of the cells reasonably large. - HSSFRow row = sheet2.createRow(2); - row.createCell(1); - row.setHeightInPoints(240); - sheet2.setColumnWidth(2, 9000); - - // Create the drawing patriarch. This is the top level container for - // all shapes. This will clear out any existing shapes for that sheet. - HSSFPatriarch patriarch = sheet2.createDrawingPatriarch(); - - // Draw a grid in one of the cells. - drawGrid( patriarch ); - } - - private static void drawSheet3( HSSFSheet sheet3 ) - { - // Create a row and size one of the cells reasonably large - HSSFRow row = sheet3.createRow(2); - row.setHeightInPoints(140); - row.createCell(1); - sheet3.setColumnWidth(2, 9000); - - // Create the drawing patriarch. This is the top level container for - // all shapes. This will clear out any existing shapes for that sheet. - HSSFPatriarch patriarch = sheet3.createDrawingPatriarch(); - - // Create a shape group. - HSSFShapeGroup group = patriarch.createGroup( - new HSSFClientAnchor(0,0,900,200,(short)2,2,(short)2,2)); - - // Create a couple of lines in the group. - HSSFSimpleShape shape1 = group.createShape(new HSSFChildAnchor(3,3,500,500)); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - ( (HSSFChildAnchor) shape1.getAnchor() ).setAnchor((short)3,3,500,500); - HSSFSimpleShape shape2 = group.createShape(new HSSFChildAnchor((short)1,200,400,600)); - shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - - } - - private static void drawSheet4( HSSFSheet sheet4, HSSFWorkbook wb ) - { - // Create the drawing patriarch. This is the top level container for - // all shapes. This will clear out any existing shapes for that sheet. - HSSFPatriarch patriarch = sheet4.createDrawingPatriarch(); - - // Create a couple of textboxes - HSSFTextbox textbox1 = patriarch.createTextbox( - new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)2,2)); - textbox1.setString(new HSSFRichTextString("This is a test") ); - HSSFTextbox textbox2 = patriarch.createTextbox( - new HSSFClientAnchor(0,0,900,100,(short)3,3,(short)3,4)); - textbox2.setString(new HSSFRichTextString("Woo") ); - textbox2.setFillColor(200,0,0); - textbox2.setLineStyle(HSSFSimpleShape.LINESTYLE_DOTGEL); - - // Create third one with some fancy font styling. - HSSFTextbox textbox3 = patriarch.createTextbox( - new HSSFClientAnchor(0,0,900,100,(short)4,4,(short)5,4+1)); - HSSFFont font = wb.createFont(); - font.setItalic(true); - font.setUnderline(HSSFFont.U_DOUBLE); - HSSFRichTextString string = new HSSFRichTextString("Woo!!!"); - string.applyFont(2,5,font); - textbox3.setString(string ); - textbox3.setFillColor(0x08000030); - textbox3.setLineStyle(HSSFSimpleShape.LINESTYLE_NONE); // no line around the textbox. - textbox3.setNoFill(true); // make it transparent - } - - private static void drawSheet5( HSSFSheet sheet5, HSSFWorkbook wb ) throws IOException - { - - // Create the drawing patriarch. This is the top level container for - // all shapes. This will clear out any existing shapes for that sheet. - HSSFPatriarch patriarch = sheet5.createDrawingPatriarch(); - - HSSFClientAnchor anchor; - anchor = new HSSFClientAnchor(0,0,0,255,(short)2,2,(short)4,7); - anchor.setAnchorType( 2 ); - patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4.png", wb )); - - anchor = new HSSFClientAnchor(0,0,0,255,(short)4,2,(short)5,7); - anchor.setAnchorType( 2 ); - patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4edited.png", wb )); - - anchor = new HSSFClientAnchor(0,0,1023,255,(short)6,2,(short)8,7); - anchor.setAnchorType( 2 ); - HSSFPicture picture = patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4s.png", wb )); - //Reset the image to the original size. - picture.resize(); - picture.setLineStyle( picture.LINESTYLE_DASHDOTGEL ); - - } - - private static int loadPicture( String path, HSSFWorkbook wb ) throws IOException - { - int pictureIndex; - FileInputStream fis = null; - ByteArrayOutputStream bos = null; - try - { - fis = new FileInputStream( path); - bos = new ByteArrayOutputStream( ); - int c; - while ( (c = fis.read()) != -1) - bos.write( c ); - pictureIndex = wb.addPicture( bos.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG ); - } - finally - { - if (fis != null) - fis.close(); - if (bos != null) - bos.close(); - } - return pictureIndex; - } - - private static void drawOval( HSSFPatriarch patriarch ) - { - // Create an oval and style to taste. - HSSFClientAnchor a = new HSSFClientAnchor(); - a.setAnchor((short)2, 2, 20, 20, (short) 2, 2, 190, 80); - HSSFSimpleShape s = patriarch.createSimpleShape(a); - s.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL); - s.setLineStyleColor(10,10,10); - s.setFillColor(90,10,200); - s.setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3); - s.setLineStyle(HSSFShape.LINESTYLE_DOTSYS); - } - - private static void drawPolygon( HSSFPatriarch patriarch ) - { - // HSSFClientAnchor a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 2, 2, (short) 3, 3 ); - // HSSFPolygon p = patriarch.createPolygon(a); - // p.setPolygonDrawArea(100,100); - // p.setPoints( new int[]{30, 90, 50}, new int[]{88, 5, 44} ); - - - HSSFClientAnchor a = new HSSFClientAnchor(); - a.setAnchor( (short) 2, 2, 0, 0, (short) 3, 3, 1023, 255 ); - HSSFShapeGroup g = patriarch.createGroup( a ); - g.setCoordinates(0,0,200,200); - HSSFPolygon p1 = g.createPolygon( new HSSFChildAnchor( 0, 0, 200, 200 ) ); - p1.setPolygonDrawArea( 100, 100 ); - p1.setPoints( new int[]{0, 90, 50}, new int[]{5, 5, 44} ); - p1.setFillColor( 0, 255, 0 ); - HSSFPolygon p2 = g.createPolygon( new HSSFChildAnchor( 20, 20, 200, 200 ) ); - p2.setPolygonDrawArea( 200, 200 ); - p2.setPoints( new int[]{120, 20, 150}, new int[]{105, 30, 195} ); - p2.setFillColor( 255, 0, 0 ); - } - - private static void drawManyLines( HSSFPatriarch patriarch ) - { - // Draw bunch of lines - int x1 = 100; - int y1 = 100; - int x2 = 800; - int y2 = 200; - int color = 0; - for (int i = 0; i < 10; i++) - { - HSSFClientAnchor a2 = new HSSFClientAnchor(); - a2.setAnchor((short) 2, 2, x1, y1, (short) 2, 2, x2, y2); - HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); - shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - shape2.setLineStyleColor(color); - y1 -= 10; - y2 -= 10; - color += 30; - } - } - - private static void drawGrid( HSSFPatriarch patriarch ) - { - // This draws a grid of lines. Since the coordinates space fixed at - // 1024 by 256 we use a ratio to get a reasonably square grids. - - double xRatio = 3.22; - double yRatio = 0.6711; - - int x1 = 000; - int y1 = 000; - int x2 = 000; - int y2 = 200; - for (int i = 0; i < 20; i++) - { - HSSFClientAnchor a2 = new HSSFClientAnchor(); - a2.setAnchor((short) 2, 2, (int) ( x1 * xRatio ), (int) ( y1 * yRatio ), - (short) 2, 2, (int) ( x2 * xRatio ), (int) ( y2 * yRatio )); - HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); - shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - - x1 += 10; - x2 += 10; - } - - x1 = 000; - y1 = 000; - x2 = 200; - y2 = 000; - for (int i = 0; i < 20; i++) - { - HSSFClientAnchor a2 = new HSSFClientAnchor(); - a2.setAnchor((short) 2, 2, (int) ( x1 * xRatio ), (int) ( y1 * yRatio ), - (short) 2, 2, (int) ( x2 * xRatio ), (int) ( y2 * yRatio )); - HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); - shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - - y1 += 10; - y2 += 10; - } - } - - private static void drawLinesToCenter( HSSFPatriarch patriarch ) - { - // Draw some lines from and to the corners - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)2, 2, 0, 0, (short) 2, 2, 512, 128); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)2, 2, 512, 128, (short) 2, 2, 1024, 0); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)1, 1, 0, 0, (short) 1, 1, 512, 100); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)1, 1, 512, 100, (short) 1, 1, 1024, 0); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java deleted file mode 100644 index 4de1207f42..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.awt.*; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Demonstrates the use of the EscherGraphics2d library. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class OfficeDrawingWithGraphics { - public static void main( String[] args ) throws IOException { - // Create a workbook with one sheet and size the first three somewhat - // larger so we can fit the chemical structure diagram in. - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet( "my drawing" ); - sheet.setColumnWidth(1, 256 * 27); - HSSFRow row1 = sheet.createRow(0); - row1.setHeightInPoints(10 * 15); - HSSFRow row2 = sheet.createRow(1); - row2.setHeightInPoints(5 * 15); - HSSFRow row3 = sheet.createRow(2); - row3.setHeightInPoints(10 * 15); - - // Add some cells so we can test that the anchoring works when we - // sort them. - row1.createCell(0).setCellValue("C"); - row2.createCell(0).setCellValue("A"); - row3.createCell(0).setCellValue("B"); - - // Create the top level drawing patriarch. - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFClientAnchor a; - HSSFShapeGroup group; - EscherGraphics g; - EscherGraphics2d g2d; - // Anchor entirely within one cell. - a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 ); - group = patriarch.createGroup( a ); - group.setCoordinates( 0, 0, 320, 276 ); - float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1()); - g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel ); - g2d = new EscherGraphics2d( g ); - drawStar( g2d ); - - a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 1, (short) 1, 1 ); - group = patriarch.createGroup( a ); - group.setCoordinates( 0, 0, 640, 276 ); - verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1()); -// verticalPixelsPerPoint = (float)Math.abs(group.getY2() - group.getY1()) / a.getAnchorHeightInPoints(sheet); - g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel ); - g2d = new EscherGraphics2d( g ); - drawStar( g2d ); - - FileOutputStream out = new FileOutputStream("workbook.xls"); - wb.write(out); - out.close(); - - } - - private static void drawStar( EscherGraphics2d g2d ) - { - g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); - for (double i = 0; i < Math.PI; i += 0.1) - { - g2d.setColor( new Color((int)(i * 5343062d) ) ); - int x1 = (int) ( Math.cos(i) * 160.0 ) + 160; - int y1 = (int) ( Math.sin(i) * 138.0 ) + 138; - int x2 = (int) ( -Math.cos(i) * 160.0 ) + 160; - int y2 = (int) ( -Math.sin(i) * 138.0 ) + 138; - g2d.setStroke(new BasicStroke(2)); - g2d.drawLine(x1,y1,x2,y2); - } - g2d.setFont(new Font("SansSerif",Font.BOLD | Font.ITALIC, 20)); - g2d.drawString("EscherGraphics2d",70,100); - g2d.setColor(Color.yellow); - g2d.fillOval( 160-20,138-20,40,40); - g2d.setColor(Color.black); - g2d.fillPolygon(new int[] {-10+160,0+160,10+160,0+160}, new int[] {0+138,10+138,0+138,-10+138}, 4); - g2d.drawPolygon(new int[] {-160+160,0+160,160+160,0+160}, new int[] {0+138,138+138,0+138,-138+138}, 4); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Outlines.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Outlines.java deleted file mode 100644 index c04d608ed0..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Outlines.java +++ /dev/null @@ -1,259 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFCell; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Creates outlines. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class Outlines { - public static void main(String[] args) throws IOException { - createCase1( "outline1.xls" ); - System.out.println( "outline1.xls written. Two expanded groups." ); - createCase2( "outline2.xls" ); - System.out.println( "outline2.xls written. Two groups. Inner group collapsed." ); - createCase3( "outline3.xls" ); - System.out.println( "outline3.xls written. Two groups. Both collapsed." ); - createCase4( "outline4.xls" ); - System.out.println( "outline4.xls written. Two groups. Collapsed then inner group expanded." ); - createCase5( "outline5.xls" ); - System.out.println( "outline5.xls written. Two groups. Collapsed then reexpanded." ); - createCase6( "outline6.xls" ); - System.out.println( "outline6.xls written. Two groups with matching end points. Second group collapsed." ); - createCase7( "outline7.xls" ); - System.out.println( "outline7.xls written. Row outlines." ); - createCase8( "outline8.xls" ); - System.out.println( "outline8.xls written. Row outlines. Inner group collapsed." ); - createCase9( "outline9.xls" ); - System.out.println( "outline9.xls written. Row outlines. Both collapsed." ); - createCase10( "outline10.xls" ); - System.out.println( "outline10.xls written. Row outlines. Collapsed then inner group expanded." ); - createCase11( "outline11.xls" ); - System.out.println( "outline11.xls written. Row outlines. Collapsed then expanded." ); - createCase12( "outline12.xls" ); - System.out.println( "outline12.xls written. Row outlines. Two row groups with matching end points. Second group collapsed." ); - createCase13( "outline13.xls" ); - System.out.println( "outline13.xls written. Mixed bag." ); - } - - private static void createCase1(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupColumn(4, 7); - - for (int row = 0; row < 200; row++) { - HSSFRow r = sheet1.createRow(row); - for (int column = 0; column < 200; column++) { - HSSFCell c = r.createCell(column); - c.setCellValue(column); - } - } - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase2(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 7); - sheet1.setColumnGroupCollapsed(4, true); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase3(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 7); - sheet1.setColumnGroupCollapsed(4, true); - sheet1.setColumnGroupCollapsed(2, true); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase4(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 7); - sheet1.setColumnGroupCollapsed(4, true); - sheet1.setColumnGroupCollapsed(2, true); - - sheet1.setColumnGroupCollapsed(4, false); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase5(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 7); - sheet1.setColumnGroupCollapsed(4, true); - sheet1.setColumnGroupCollapsed(2, true); - - sheet1.setColumnGroupCollapsed(4, false); - sheet1.setColumnGroupCollapsed(3, false); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase6(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 10); - sheet1.setColumnGroupCollapsed(4, true); - sheet1.setColumnGroupCollapsed(2, true); - - sheet1.setColumnGroupCollapsed(3, false); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase7(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase8(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - sheet1.setRowGroupCollapsed(7, true); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase9(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - sheet1.setRowGroupCollapsed(7, true); - sheet1.setRowGroupCollapsed(5, true); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase10(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - sheet1.setRowGroupCollapsed(7, true); - sheet1.setRowGroupCollapsed(5, true); - sheet1.setRowGroupCollapsed(8, false); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase11(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - sheet1.setRowGroupCollapsed(7, true); - sheet1.setRowGroupCollapsed(5, true); - sheet1.setRowGroupCollapsed(8, false); - sheet1.setRowGroupCollapsed(14, false); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase12(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 14); - sheet1.setRowGroupCollapsed(7, true); - sheet1.setRowGroupCollapsed(5, true); - sheet1.setRowGroupCollapsed(6, false); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } - - private static void createCase13(String filename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 14); - sheet1.groupRow(16, 19); - - sheet1.groupColumn(4, 7); - sheet1.groupColumn(9, 12); - sheet1.groupColumn(10, 11); - - FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/ReadWriteWorkbook.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/ReadWriteWorkbook.java deleted file mode 100644 index 26bba44674..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/ReadWriteWorkbook.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFCell; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * This example demonstrates opening a workbook, modifying it and writing - * the results back out. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class ReadWriteWorkbook { - public static void main(String[] args) throws IOException { - FileInputStream fileIn = null; - FileOutputStream fileOut = null; - - try - { - fileIn = new FileInputStream("workbook.xls"); - POIFSFileSystem fs = new POIFSFileSystem(fileIn); - HSSFWorkbook wb = new HSSFWorkbook(fs); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(2); - if (row == null) - row = sheet.createRow(2); - HSSFCell cell = row.getCell(3); - if (cell == null) - cell = row.createCell(3); - cell.setCellType(HSSFCell.CELL_TYPE_STRING); - cell.setCellValue("a test"); - - // Write the output to a file - fileOut = new FileOutputStream("workbookout.xls"); - wb.write(fileOut); - } finally { - if (fileOut != null) - fileOut.close(); - if (fileIn != null) - fileIn.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java deleted file mode 100644 index df4e3bb64c..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.io.IOException; -import java.io.FileOutputStream; - -/** - * @author Glen Stampoultzis (glens at apache.org) - */ -public class RepeatingRowsAndColumns { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("first sheet"); - wb.createSheet("second sheet"); - wb.createSheet("third sheet"); - - HSSFFont boldFont = wb.createFont(); - boldFont.setFontHeightInPoints((short)22); - boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - - HSSFCellStyle boldStyle = wb.createCellStyle(); - boldStyle.setFont(boldFont); - - HSSFRow row = sheet1.createRow(1); - HSSFCell cell = row.createCell(0); - cell.setCellValue("This quick brown fox"); - cell.setCellStyle(boldStyle); - - // Set the columns to repeat from column 0 to 2 on the first sheet - wb.setRepeatingRowsAndColumns(0,0,2,-1,-1); - // Set the rows to repeat from row 0 to 2 on the second sheet. - wb.setRepeatingRowsAndColumns(1,-1,-1,0,2); - // Set the the repeating rows and columns on the third sheet. - wb.setRepeatingRowsAndColumns(2,4,5,1,2); - - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java deleted file mode 100644 index 6e93a317f0..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java +++ /dev/null @@ -1,55 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; - -import java.io.IOException; -import java.io.FileOutputStream; - -/** - * @author Glen Stampoultzis (glens at apache.org) - */ -public class SplitAndFreezePanes -{ - public static void main(String[] args) - throws IOException - { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - HSSFSheet sheet2 = wb.createSheet("second sheet"); - HSSFSheet sheet3 = wb.createSheet("third sheet"); - HSSFSheet sheet4 = wb.createSheet("fourth sheet"); - - // Freeze just one row - sheet1.createFreezePane( 0, 1, 0, 1 ); - // Freeze just one column - sheet2.createFreezePane( 1, 0, 1, 0 ); - // Freeze the columns and rows (forget about scrolling position of the lower right quadrant). - sheet3.createFreezePane( 2, 2 ); - // Create a split with the lower left side being the active quadrant - sheet4.createSplitPane( 2000, 2000, 0, 0, HSSFSheet.PANE_LOWER_LEFT ); - - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java deleted file mode 100644 index 6cb15941f2..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Demonstrates how to create and use fonts. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class WorkingWithFonts { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(1); - - // Create a new font and alter it. - HSSFFont font = wb.createFont(); - font.setFontHeightInPoints((short)24); - font.setFontName("Courier New"); - font.setItalic(true); - font.setStrikeout(true); - - // Fonts are set into a style so create a new one to use. - HSSFCellStyle style = wb.createCellStyle(); - style.setFont(font); - - // Create a cell and put a value in it. - HSSFCell cell = row.createCell(1); - cell.setCellValue("This is a test of fonts"); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/ZoomSheet.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/ZoomSheet.java deleted file mode 100644 index c65c62f18f..0000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/ZoomSheet.java +++ /dev/null @@ -1,45 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; - -import java.io.IOException; -import java.io.FileOutputStream; - -/** - * Sets the zoom magnication for a sheet. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class ZoomSheet -{ - public static void main(String[] args) - throws IOException - { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - sheet1.setZoom(3,4); // 75 percent magnification - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVBorder.java b/src/examples/src/org/apache/poi/hssf/view/SVBorder.java deleted file mode 100644 index 083b9cc18e..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVBorder.java +++ /dev/null @@ -1,564 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.view; - -import java.awt.*; - -import javax.swing.border.AbstractBorder; - -import org.apache.poi.hssf.usermodel.HSSFCellStyle; - -/** - * This is an attempt to implement Excel style borders for the SheetViewer. - * Mostly just overrides stuff so the javadoc won't appear here but will - * appear in the generated stuff. - * - * @author Andrew C. Oliver (acoliver at apache dot org) - * @author Jason Height - */ -public class SVBorder extends AbstractBorder { - private Color northColor = null; - private Color eastColor = null; - private Color southColor = null; - private Color westColor = null; - private int northBorderType = HSSFCellStyle.BORDER_NONE; - private int eastBorderType =HSSFCellStyle.BORDER_NONE; - private int southBorderType = HSSFCellStyle.BORDER_NONE; - private int westBorderType = HSSFCellStyle.BORDER_NONE; - private boolean northBorder=false; - private boolean eastBorder=false; - private boolean southBorder=false; - private boolean westBorder=false; - private boolean selected = false; - - public void setBorder(Color northColor, Color eastColor, - Color southColor, Color westColor, - int northBorderType, int eastBorderType, - int southBorderType, int westBorderType, - boolean selected) { - this.eastColor = eastColor; - this.southColor = southColor; - this.westColor = westColor; - this.northBorderType = northBorderType; - this.eastBorderType = eastBorderType; - this.southBorderType = southBorderType; - this.westBorderType = westBorderType; - this.northBorder=northBorderType != HSSFCellStyle.BORDER_NONE; - this.eastBorder=eastBorderType != HSSFCellStyle.BORDER_NONE; - this.southBorder=southBorderType != HSSFCellStyle.BORDER_NONE; - this.westBorder=westBorderType != HSSFCellStyle.BORDER_NONE; - this.selected = selected; - } - - public void paintBorder(Component c, Graphics g, int x, int y, int width, - int height) { - Color oldColor = g.getColor(); - - - paintSelectedBorder(g, x, y, width, height); - paintNormalBorders(g, x, y, width, height); - paintDottedBorders(g, x, y, width, height); - paintDashedBorders(g, x, y, width, height); - paintDoubleBorders(g, x, y, width, height); - paintDashDotDotBorders(g, x, y, width, height); - - - g.setColor(oldColor); - } - - /** - * Called by paintBorder to paint the border of a selected cell. - * The paramaters are the Graphics object, location and dimensions of the - * cell. - */ - private void paintSelectedBorder(Graphics g, int x, int y, int width, - int height) { - if (selected) { - //Need to setup thickness of 2 - g.setColor(Color.black); - //paint the border - g.drawRect(x,y,width-1,height-1); - - //paint the filled rectangle at the bottom left hand position - g.fillRect(x+width-5, y+height-5, 5, 5); - } - } - - - /** - * Called by paintBorder to paint the various versions of normal line - * borders for a cell. - */ - private void paintNormalBorders(Graphics g, int x, int y, int width, - int height) { - - if (northBorder && - ((northBorderType == HSSFCellStyle.BORDER_THIN) || - (northBorderType == HSSFCellStyle.BORDER_MEDIUM) || - (northBorderType == HSSFCellStyle.BORDER_THICK) - ) - ) { - - int thickness = getThickness(northBorderType); - - g.setColor(northColor); - - for (int k=0; k < thickness; k++) { - g.drawLine(x,y+k,width,y+k); - } - } - - if (eastBorder && - ((eastBorderType == HSSFCellStyle.BORDER_THIN) || - (eastBorderType == HSSFCellStyle.BORDER_MEDIUM) || - (eastBorderType == HSSFCellStyle.BORDER_THICK) - ) - ) { - - int thickness = getThickness(eastBorderType); - - g.setColor(eastColor); - - for (int k=0; k < thickness; k++) { - g.drawLine(width-k,y,width-k,height); - } - } - - if (southBorder && - ((southBorderType == HSSFCellStyle.BORDER_THIN) || - (southBorderType == HSSFCellStyle.BORDER_MEDIUM) || - (southBorderType == HSSFCellStyle.BORDER_THICK) - ) - ) { - - int thickness = getThickness(southBorderType); - - g.setColor(southColor); - for (int k=0; k < thickness; k++) { - g.drawLine(x,height - k,width,height - k); - } - } - - if (westBorder && - ((westBorderType == HSSFCellStyle.BORDER_THIN) || - (westBorderType == HSSFCellStyle.BORDER_MEDIUM) || - (westBorderType == HSSFCellStyle.BORDER_THICK) - ) - ) { - - int thickness = getThickness(westBorderType); - - g.setColor(westColor); - - for (int k=0; k < thickness; k++) { - g.drawLine(x+k,y,x+k,height); - } - } - } - - /** - * Called by paintBorder to paint the dotted line - * borders for a cell. - */ - private void paintDottedBorders(Graphics g, int x, int y, int width, - int height) { - if (northBorder && - northBorderType == HSSFCellStyle.BORDER_DOTTED) { - int thickness = getThickness(northBorderType); - - g.setColor(northColor); - - for (int k=0; k < thickness; k++) { - for (int xc = x; xc < width; xc=xc+2) { - g.drawLine(xc,y+k,xc,y+k); - } - } - } - - if (eastBorder && - eastBorderType == HSSFCellStyle.BORDER_DOTTED - ) { - - int thickness = getThickness(eastBorderType); - thickness++; //need for dotted borders to show up east - - g.setColor(eastColor); - - for (int k=0; k < thickness; k++) { - for (int yc=y;yc < height; yc=yc+2) { - g.drawLine(width-k,yc,width-k,yc); - } - } - } - - if (southBorder && - southBorderType == HSSFCellStyle.BORDER_DOTTED - ) { - - int thickness = getThickness(southBorderType); - thickness++; - g.setColor(southColor); - for (int k=0; k < thickness; k++) { - for (int xc = x; xc < width; xc=xc+2) { - g.drawLine(xc,height-k,xc,height-k); - } - } - } - - if (westBorder && - westBorderType == HSSFCellStyle.BORDER_DOTTED - ) { - - int thickness = getThickness(westBorderType); -// thickness++; - - g.setColor(westColor); - - for (int k=0; k < thickness; k++) { - for (int yc=y;yc < height; yc=yc+2) { - g.drawLine(x+k,yc,x+k,yc); - } - } - } - } - - /** - * Called by paintBorder to paint the various versions of dotted line - * borders for a cell. - */ - private void paintDashedBorders(Graphics g, int x, int y, int width, - int height) { - if (northBorder && - ((northBorderType == HSSFCellStyle.BORDER_DASHED) || - (northBorderType == HSSFCellStyle.BORDER_HAIR)) - ) { - int thickness = getThickness(northBorderType); - - int dashlength = 1; - - if (northBorderType == HSSFCellStyle.BORDER_DASHED) - dashlength = 2; - - g.setColor(northColor); - - for (int k=0; k < thickness; k++) { - for (int xc = x; xc < width; xc=xc+5) { - g.drawLine(xc,y+k,xc+dashlength,y+k); - } - } - } - - if (eastBorder && - ((eastBorderType == HSSFCellStyle.BORDER_DASHED) || - (eastBorderType == HSSFCellStyle.BORDER_HAIR)) - ) { - - int thickness = getThickness(eastBorderType); - thickness++; //need for dotted borders to show up east - - - int dashlength = 1; - - if (eastBorderType == HSSFCellStyle.BORDER_DASHED) - dashlength = 2; - - g.setColor(eastColor); - - for (int k=0; k < thickness; k++) { - for (int yc=y;yc < height; yc=yc+5) { - g.drawLine(width-k,yc,width-k,yc+dashlength); - } - } - } - - if (southBorder && - ((southBorderType == HSSFCellStyle.BORDER_DASHED) || - (southBorderType == HSSFCellStyle.BORDER_HAIR)) - ) { - - int thickness = getThickness(southBorderType); - thickness++; - - int dashlength = 1; - - if (southBorderType == HSSFCellStyle.BORDER_DASHED) - dashlength = 2; - - g.setColor(southColor); - for (int k=0; k < thickness; k++) { - for (int xc = x; xc < width; xc=xc+5) { - g.drawLine(xc,height-k,xc+dashlength,height-k); - } - } - } - - if (westBorder && - ((westBorderType == HSSFCellStyle.BORDER_DASHED) || - (westBorderType == HSSFCellStyle.BORDER_HAIR)) - ) { - - int thickness = getThickness(westBorderType); -// thickness++; - - int dashlength = 1; - - if (westBorderType == HSSFCellStyle.BORDER_DASHED) - dashlength = 2; - - g.setColor(westColor); - - for (int k=0; k < thickness; k++) { - for (int yc=y;yc < height; yc=yc+5) { - g.drawLine(x+k,yc,x+k,yc+dashlength); - } - } - } - } - - /** - * Called by paintBorder to paint the double line - * borders for a cell. - */ - private void paintDoubleBorders(Graphics g, int x, int y, int width, - int height) { - if (northBorder && - northBorderType == HSSFCellStyle.BORDER_DOUBLE) { - - g.setColor(northColor); - - int leftx=x; - int rightx=width; - - // if there are borders on the west or east then - // the second line shouldn't cross them - if (westBorder) - leftx = x+3; - - if (eastBorder) - rightx = width-3; - - g.drawLine(x,y,width,y); - g.drawLine(leftx,y+2,rightx,y+2); - } - - if (eastBorder && - eastBorderType == HSSFCellStyle.BORDER_DOUBLE - ) { - - int thickness = getThickness(eastBorderType); - thickness++; //need for dotted borders to show up east - - g.setColor(eastColor); - - int topy=y; - int bottomy=height; - - if (northBorder) - topy=y+3; - - if (southBorder) - bottomy=height-3; - - g.drawLine(width-1,y,width-1,height); - g.drawLine(width-3,topy,width-3,bottomy); - } - - if (southBorder && - southBorderType == HSSFCellStyle.BORDER_DOUBLE - ) { - - g.setColor(southColor); - - int leftx=y; - int rightx=width; - - if (westBorder) - leftx=x+3; - - if (eastBorder) - rightx=width-3; - - - g.drawLine(x,height - 1,width,height - 1); - g.drawLine(leftx,height - 3,rightx,height - 3); - } - - if (westBorder && - westBorderType == HSSFCellStyle.BORDER_DOUBLE - ) { - - int thickness = getThickness(westBorderType); -// thickness++; - - g.setColor(westColor); - - int topy=y; - int bottomy=height-3; - - if (northBorder) - topy=y+2; - - if (southBorder) - bottomy=height-3; - - g.drawLine(x,y,x,height); - g.drawLine(x+2,topy,x+2,bottomy); - } - } - - /** - * Called by paintBorder to paint the various versions of dash dot dot line - * borders for a cell. - */ - private void paintDashDotDotBorders(Graphics g, int x, int y, int width, - int height) { - if (northBorder && - ((northBorderType == HSSFCellStyle.BORDER_DASH_DOT_DOT) || - (northBorderType == HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT)) - ) { - int thickness = getThickness(northBorderType); - - g.setColor(northColor); - for (int l=x; l < width;) { - l=l+drawDashDotDot(g, l, y, thickness, true, true); - } - - } - - if (eastBorder && - ((eastBorderType == HSSFCellStyle.BORDER_DASH_DOT_DOT) || - (eastBorderType == HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT)) - ) { - - int thickness = getThickness(eastBorderType); - - g.setColor(eastColor); - - for (int l=y;l < height;) { - //System.err.println("drawing east"); - l=l+drawDashDotDot(g,width-1,l,thickness,false,false); - } - } - - if (southBorder && - ((southBorderType == HSSFCellStyle.BORDER_DASH_DOT_DOT) || - (southBorderType == HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT)) - ) { - - int thickness = getThickness(southBorderType); - - g.setColor(southColor); - - for (int l=x; l < width;) { - //System.err.println("drawing south"); - l=l+drawDashDotDot(g, l, height-1, thickness, true, false); - } - } - - if (westBorder && - ((westBorderType == HSSFCellStyle.BORDER_DASH_DOT_DOT) || - (westBorderType == HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT)) - ) { - - int thickness = getThickness(westBorderType); - - g.setColor(westColor); - - for (int l=y;l < height;) { - //System.err.println("drawing west"); - l=l+drawDashDotDot(g,x,l,thickness,false,true); - } - - } - } - - /** - * Draws one dash dot dot horizontally or vertically with thickness drawn - * incrementally to either the right or left. - * - * @param g graphics object for drawing with - * @param x the x origin of the line - * @param y the y origin of the line - * @param thickness the thickness of the line - * @param horizontal or vertical (true for horizontal) - * @param right/bottom or left/top thickness (true for right or top), - * if true then the x or y origin will be incremented to provide - * thickness, if false, they'll be decremented. For vertical - * borders, x is incremented or decremented, for horizontal its y. - * Just set to true for north and west, and false for east and - * south. - * @returns length - returns the length of the line. - */ - private int drawDashDotDot(Graphics g,int x, int y, int thickness, - boolean horizontal, - boolean rightBottom) { - - for (int t=0; t < thickness; t++) { - if (!rightBottom) { - t = 0 - t; //add negative thickness so we go the other way - //then we'll decrement instead of increment. - } - if (horizontal) { - g.drawLine(x,y+t,x+5,y+t); - g.drawLine(x+8,y+t,x+10,y+t); - g.drawLine(x+13,y+t,x+15,y+t); - } else { - g.drawLine(x+t,y,x+t,y+5); - g.drawLine(x+t,y+8,x+t,y+10); - g.drawLine(x+t,y+13,x+t,y+15); - } - } - return 18; - } - - /** - * @returns the line thickness for a border based on border type - */ - private int getThickness(int thickness) { - int retval=1; - switch (thickness) { - case HSSFCellStyle.BORDER_THIN: - retval=2; - break; - case HSSFCellStyle.BORDER_MEDIUM: - retval=3; - break; - case HSSFCellStyle.BORDER_THICK: - retval=4; - break; - case HSSFCellStyle.BORDER_DASHED: - retval=1; - break; - case HSSFCellStyle.BORDER_DASH_DOT_DOT: - retval=1; - break; - case HSSFCellStyle.BORDER_MEDIUM_DASH_DOT_DOT: - retval=3; - break; - case HSSFCellStyle.BORDER_HAIR: - retval=1; - break; - default: - retval=1; - } - return retval; - } - - -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVFractionalFormat.java b/src/examples/src/org/apache/poi/hssf/view/SVFractionalFormat.java deleted file mode 100644 index cd6ff6ea72..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVFractionalFormat.java +++ /dev/null @@ -1,220 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.view; - -import java.text.*; - -/** - * This class is used to format cells into their fractional format. - * - * I cant be 100% sure that the same fractional value will be displayed as in - * excel but then again it is a lossy formating mode anyway - * - * @author Jason Height - * @since 15 July 2002 - */ -public class SVFractionalFormat extends Format { - private short ONE_DIGIT = 1; - private short TWO_DIGIT = 2; - private short THREE_DIGIT = 3; - private short UNITS = 4; - private int units = 1; - private short mode = -1; - - /** Constructs a new FractionalFormatter - * - * The formatStr defines how the number will be formatted - * # ?/? Up to one digit - * # ??/?? Up to two digits - * # ???/??? Up to three digits - * # ?/2 In halves - * # ?/4 In quarters - * # ?/8 In eighths - * # ?/16 In sixteenths - * # ?/10 In tenths - * # ?/100 In hundredths - */ - public SVFractionalFormat(String formatStr) { - if ("# ?/?".equals(formatStr)) - mode = ONE_DIGIT; - else if ("# ??/??".equals(formatStr)) - mode = TWO_DIGIT; - else if ("# ???/???".equals(formatStr)) - mode = THREE_DIGIT; - else if ("# ?/2".equals(formatStr)) { - mode = UNITS; - units = 2; - } else if ("# ?/4".equals(formatStr)) { - mode = UNITS; - units = 4; - } else if ("# ?/8".equals(formatStr)) { - mode = UNITS; - units = 8; - } else if ("# ?/16".equals(formatStr)) { - mode = UNITS; - units = 16; - } else if ("# ?/10".equals(formatStr)) { - mode = UNITS; - units = 10; - } else if ("# ?/100".equals(formatStr)) { - mode = UNITS; - units = 100; - } - } - - /** - * Returns a fractional string representation of a double to a maximum denominator size - * - * This code has been translated to java from the following web page. - * http://www.codeproject.com/cpp/fraction.asp - * Originally coded in c++ By Dean Wyant dwyant@mindspring.com - * The code on the web page is freely available. - * - * @param f Description of the Parameter - * @param MaxDen Description of the Parameter - * @return Description of the Return Value - */ - private String format(final double f, final int MaxDen) { - long Whole = (long)f; - int sign = 1; - if (f < 0) { - sign = -1; - } - double Precision = 0.00001; - double AllowedError = Precision; - double d = Math.abs(f); - d -= Whole; - double Frac = d; - double Diff = Frac; - long Num = 1; - long Den = 0; - long A = 0; - long B = 0; - long i = 0; - if (Frac > Precision) { - while (true) { - d = 1.0 / d; - i = (long) (d + Precision); - d -= i; - if (A > 0) { - Num = i * Num + B; - } - Den = (long) (Num / Frac + 0.5); - Diff = Math.abs((double) Num / Den - Frac); - if (Den > MaxDen) { - if (A > 0) { - Num = A; - Den = (long) (Num / Frac + 0.5); - Diff = Math.abs((double) Num / Den - Frac); - } else { - Den = MaxDen; - Num = 1; - Diff = Math.abs((double) Num / Den - Frac); - if (Diff > Frac) { - Num = 0; - Den = 1; - // Keeps final check below from adding 1 and keeps Den from being 0 - Diff = Frac; - } - } - break; - } - if ((Diff <= AllowedError) || (d < Precision)) { - break; - } - Precision = AllowedError / Diff; - // This calcualtion of Precision does not always provide results within - // Allowed Error. It compensates for loss of significant digits that occurs. - // It helps to round the inprecise reciprocal values to i. - B = A; - A = Num; - } - } - if (Num == Den) { - Whole++; - Num = 0; - Den = 0; - } else if (Den == 0) { - Num = 0; - } - if (sign < 0) { - if (Whole == 0) { - Num = -Num; - } else { - Whole = -Whole; - } - } - return new StringBuffer().append(Whole).append(" ").append(Num).append("/").append(Den).toString(); - } - - /** This method formats the double in the units specified. - * The usints could be any number but in this current implementation it is - * halves (2), quaters (4), eigths (8) etc - */ - private String formatUnit(double f, int units) { - long Whole = (long)f; - f -= Whole; - long Num = Math.round(f * units); - - return new StringBuffer().append(Whole).append(" ").append(Num).append("/").append(units).toString(); - } - - public final String format(double val) { - if (mode == ONE_DIGIT) { - return format(val, 9); - } else if (mode == TWO_DIGIT) { - return format(val, 99); - } else if (mode == THREE_DIGIT) { - return format(val, 999); - } else if (mode == UNITS) { - return formatUnit(val , units); - } - throw new RuntimeException("Unexpected Case"); - } - - public StringBuffer format(Object obj, - StringBuffer toAppendTo, - FieldPosition pos) { - if (obj instanceof Number) { - toAppendTo.append(format(((Number)obj).doubleValue())); - return toAppendTo; - } - throw new IllegalArgumentException("Can only handle Numbers"); - } - - public Object parseObject(String source, - ParsePosition status) { - //JMH TBD - return null; - } - - public Object parseObject(String source) - throws ParseException { - //JMH TBD - return null; - } - - public Object clone() { - //JMH TBD - return null; - } - - -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVRowHeader.java b/src/examples/src/org/apache/poi/hssf/view/SVRowHeader.java deleted file mode 100644 index c6db2f71a4..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVRowHeader.java +++ /dev/null @@ -1,96 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi.hssf.view; - -import java.awt.*; -import javax.swing.*; -import javax.swing.table.*; - -import org.apache.poi.hssf.usermodel.*; - -/** - * This class presents the row header to the table. - * - * - * @author Jason Height - */ -public class SVRowHeader extends JList { - /** This model simply returns an integer number up to the number of rows - * that are present in the sheet. - * - */ - private class SVRowHeaderModel extends AbstractListModel { - private HSSFSheet sheet; - - public SVRowHeaderModel(HSSFSheet sheet) { - this.sheet = sheet; - } - - public int getSize() { - return sheet.getLastRowNum() + 1; - } - public Object getElementAt(int index) { - return Integer.toString(index+1); - } - } - - /** Renderes the row number*/ - private class RowHeaderRenderer extends JLabel implements ListCellRenderer { - private HSSFSheet sheet; - private int extraHeight; - - RowHeaderRenderer(HSSFSheet sheet, JTable table, int extraHeight) { - this.sheet = sheet; - this.extraHeight = extraHeight; - JTableHeader header = table.getTableHeader(); - setOpaque(true); - setBorder(UIManager.getBorder("TableHeader.cellBorder")); - setHorizontalAlignment(CENTER); - setForeground(header.getForeground()); - setBackground(header.getBackground()); - setFont(header.getFont()); - } - - public Component getListCellRendererComponent( JList list, - Object value, int index, boolean isSelected, boolean cellHasFocus) { - Dimension d = getPreferredSize(); - HSSFRow row = sheet.getRow(index); - int rowHeight; - if(row == null) { - rowHeight = (int)sheet.getDefaultRowHeightInPoints(); - } else { - rowHeight = (int)row.getHeightInPoints(); - } - d.height = rowHeight+extraHeight; - setPreferredSize(d); - setText((value == null) ? "" : value.toString()); - return this; - } - } - - public SVRowHeader(HSSFSheet sheet, JTable table, int extraHeight) { - ListModel lm = new SVRowHeaderModel(sheet); - this.setModel(lm); - - setFixedCellWidth(50); - setCellRenderer(new RowHeaderRenderer(sheet, table, extraHeight)); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVSheetTable.java b/src/examples/src/org/apache/poi/hssf/view/SVSheetTable.java deleted file mode 100644 index ed2fd8fb6d..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVSheetTable.java +++ /dev/null @@ -1,241 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.view; - -import org.apache.poi.hssf.view.brush.PendingPaintings; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; - -import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.*; -import javax.swing.text.JTextComponent; -import java.awt.*; -import java.awt.event.HierarchyEvent; -import java.awt.event.HierarchyListener; - -/** - * This class is a table that represents the values in a single worksheet. - * - * @author Ken Arnold, Industrious Media LLC - */ -public class SVSheetTable extends JTable { - private final HSSFSheet sheet; - private final PendingPaintings pendingPaintings; - private FormulaDisplayListener formulaListener; - private JScrollPane scroll; - - private static final Color HEADER_BACKGROUND = new Color(235, 235, 235); - - /** - * This field is the magic number to convert from a Character width to a java - * pixel width. - *

      - * When the "normal" font size in a workbook changes, this effects all of the - * heights and widths. Unfortunately there is no way to retrieve this - * information, hence the MAGIC number. - *

      - * This number may only work for the normal style font size of Arial size 10. - */ - private static final int magicCharFactor = 7; - - private class HeaderCell extends JLabel { - private final int row; - - public HeaderCell(Object value, int row) { - super(value.toString(), CENTER); - this.row = row; - setBackground(HEADER_BACKGROUND); - setOpaque(true); - setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); - setRowSelectionAllowed(false); - } - - @Override - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - if (row >= 0) { - d.height = getRowHeight(row); - } - return d; - } - - @Override - public Dimension getMaximumSize() { - Dimension d = super.getMaximumSize(); - if (row >= 0) { - d.height = getRowHeight(row); - } - return d; - } - - @Override - public Dimension getMinimumSize() { - Dimension d = super.getMinimumSize(); - if (row >= 0) { - d.height = getRowHeight(row); - } - return d; - } - } - - private class HeaderCellRenderer implements TableCellRenderer { - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - - return new HeaderCell(value, row); - } - } - - private class FormulaDisplayListener implements ListSelectionListener { - private final JTextComponent formulaDisplay; - - public FormulaDisplayListener(JTextComponent formulaDisplay) { - this.formulaDisplay = formulaDisplay; - } - - public void valueChanged(ListSelectionEvent e) { - int row = getSelectedRow(); - int col = getSelectedColumn(); - if (row < 0 || col < 0) { - return; - } - - if (e.getValueIsAdjusting()) { - return; - } - - HSSFCell cell = (HSSFCell) getValueAt(row, col); - String formula = ""; - if (cell != null) { - if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { - formula = cell.getCellFormula(); - } else { - formula = cell.toString(); - } - if (formula == null) - formula = ""; - } - formulaDisplay.setText(formula); - } - } - - public SVSheetTable(HSSFSheet sheet) { - super(new SVTableModel(sheet)); - this.sheet = sheet; - - setIntercellSpacing(new Dimension(0, 0)); - setAutoResizeMode(AUTO_RESIZE_OFF); - JTableHeader header = getTableHeader(); - header.setDefaultRenderer(new HeaderCellRenderer()); - pendingPaintings = new PendingPaintings(this); - - //Set the columns the correct size - TableColumnModel columns = getColumnModel(); - for (int i = 0; i < columns.getColumnCount(); i++) { - TableColumn column = columns.getColumn(i); - int width = sheet.getColumnWidth(i); - //256 is because the width is in 256ths of a character - column.setPreferredWidth(width / 256 * magicCharFactor); - } - - Toolkit t = getToolkit(); - int res = t.getScreenResolution(); - TableModel model = getModel(); - for (int i = 0; i < model.getRowCount(); i++) { - Row row = sheet.getRow(i - sheet.getFirstRowNum()); - if (row != null) { - short h = row.getHeight(); - int height = Math.round(Math.max(1, h / (res / 70 * 20) + 3)); - System.out.printf("%d: %d (%d @ %d)%n", i, height, h, res); - setRowHeight(i, height); - } - } - - addHierarchyListener(new HierarchyListener() { - public void hierarchyChanged(HierarchyEvent e) { - if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) { - Container changedParent = e.getChangedParent(); - if (changedParent instanceof JViewport) { - Container grandparent = changedParent.getParent(); - if (grandparent instanceof JScrollPane) { - JScrollPane jScrollPane = (JScrollPane) grandparent; - setupScroll(jScrollPane); - } - } - } - } - }); - } - - public void setupScroll(JScrollPane scroll) { - if (scroll == this.scroll) - return; - - this.scroll = scroll; - if (scroll == null) - return; - - SVRowHeader rowHeader = new SVRowHeader(sheet, this, 0); - scroll.setRowHeaderView(rowHeader); - scroll.setCorner(JScrollPane.UPPER_LEADING_CORNER, headerCell("?")); - } - - public void setFormulaDisplay(JTextComponent formulaDisplay) { - ListSelectionModel rowSelMod = getSelectionModel(); - ListSelectionModel colSelMod = getColumnModel().getSelectionModel(); - - if (formulaDisplay == null) { - rowSelMod.removeListSelectionListener(formulaListener); - colSelMod.removeListSelectionListener(formulaListener); - formulaListener = null; - } - - if (formulaDisplay != null) { - formulaListener = new FormulaDisplayListener(formulaDisplay); - rowSelMod.addListSelectionListener(formulaListener); - colSelMod.addListSelectionListener(formulaListener); - } - } - - public JTextComponent getFormulaDisplay() { - if (formulaListener == null) - return null; - else - return formulaListener.formulaDisplay; - } - - public Component headerCell(String text) { - return new HeaderCell(text, -1); - } - - @Override - public void paintComponent(Graphics g1) { - Graphics2D g = (Graphics2D) g1; - - pendingPaintings.clear(); - - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - super.paintComponent(g); - - pendingPaintings.paint(g); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/hssf/view/SVTableCellEditor.java b/src/examples/src/org/apache/poi/hssf/view/SVTableCellEditor.java deleted file mode 100644 index b0c57b0fe0..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVTableCellEditor.java +++ /dev/null @@ -1,203 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.view; - -import java.awt.*; -import java.awt.event.*; -import java.util.*; - -import javax.swing.*; -import javax.swing.table.*; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.util.HSSFColor; - -/** - * Sheet Viewer Table Cell Editor -- not commented via javadoc as it - * nearly completely consists of overridden methods. - * - * @author Jason Height - */ -public class SVTableCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener { - private static final Color black = getAWTColor(new HSSFColor.BLACK()); - private static final Color white = getAWTColor(new HSSFColor.WHITE()); - private Map colors = HSSFColor.getIndexHash(); - - - private HSSFWorkbook wb; - private JTextField editor; - - private HSSFCell editorValue; - - - public SVTableCellEditor(HSSFWorkbook wb) { - this.wb = wb; - this.editor = new JTextField(); - } - - - /** - * Gets the cellEditable attribute of the SVTableCellEditor object - * - * @return The cellEditable value - */ - public boolean isCellEditable(java.util.EventObject e) { - if (e instanceof MouseEvent) { - return ((MouseEvent) e).getClickCount() >= 2; - } - return false; - } - - - public boolean shouldSelectCell(EventObject anEvent) { - return true; - } - - - public boolean startCellEditing(EventObject anEvent) { - System.out.println("Start Cell Editing"); - return true; - } - - - public boolean stopCellEditing() { - System.out.println("Stop Cell Editing"); - fireEditingStopped(); - return true; - } - - - public void cancelCellEditing() { - System.out.println("Cancel Cell Editing"); - fireEditingCanceled(); - } - - - public void actionPerformed(ActionEvent e) { - System.out.println("Action performed"); - stopCellEditing(); - } - - - /** - * Gets the cellEditorValue attribute of the SVTableCellEditor object - * - * @return The cellEditorValue value - */ - public Object getCellEditorValue() { - System.out.println("GetCellEditorValue"); - //JMH Look at when this method is called. Should it return a HSSFCell? - return editor.getText(); - } - - - /** - * Gets the tableCellEditorComponent attribute of the SVTableCellEditor object - * - * @return The tableCellEditorComponent value - */ - public Component getTableCellEditorComponent(JTable table, Object value, - boolean isSelected, - int row, - int column) { - System.out.println("GetTableCellEditorComponent"); - HSSFCell cell = (HSSFCell) value; - if (cell != null) { - HSSFCellStyle style = cell.getCellStyle(); - HSSFFont f = wb.getFontAt(style.getFontIndex()); - boolean isbold = f.getBoldweight() > HSSFFont.BOLDWEIGHT_NORMAL; - boolean isitalics = f.getItalic(); - - int fontstyle = Font.PLAIN; - - if (isbold) fontstyle = Font.BOLD; - if (isitalics) fontstyle = fontstyle | Font.ITALIC; - - int fontheight = f.getFontHeightInPoints(); - if (fontheight == 9) fontheight = 10; //fix for stupid ol Windows - - Font font = new Font(f.getFontName(),fontstyle,fontheight); - editor.setFont(font); - - if (style.getFillPattern() == HSSFCellStyle.SOLID_FOREGROUND) { - editor.setBackground(getAWTColor(style.getFillForegroundColor(), white)); - } else editor.setBackground(white); - - editor.setForeground(getAWTColor(f.getColor(), black)); - - - //Set the value that is rendered for the cell - switch (cell.getCellType()) { - case HSSFCell.CELL_TYPE_BLANK: - editor.setText(""); - break; - case HSSFCell.CELL_TYPE_BOOLEAN: - if (cell.getBooleanCellValue()) { - editor.setText("true"); - } else { - editor.setText("false"); - } - break; - case HSSFCell.CELL_TYPE_NUMERIC: - editor.setText(Double.toString(cell.getNumericCellValue())); - break; - case HSSFCell.CELL_TYPE_STRING: - editor.setText(cell.getRichStringCellValue().getString()); - break; - case HSSFCell.CELL_TYPE_FORMULA: - default: - editor.setText("?"); - } - switch (style.getAlignment()) { - case HSSFCellStyle.ALIGN_LEFT: - case HSSFCellStyle.ALIGN_JUSTIFY: - case HSSFCellStyle.ALIGN_FILL: - editor.setHorizontalAlignment(SwingConstants.LEFT); - break; - case HSSFCellStyle.ALIGN_CENTER: - case HSSFCellStyle.ALIGN_CENTER_SELECTION: - editor.setHorizontalAlignment(SwingConstants.CENTER); - break; - case HSSFCellStyle.ALIGN_GENERAL: - case HSSFCellStyle.ALIGN_RIGHT: - editor.setHorizontalAlignment(SwingConstants.RIGHT); - break; - default: - editor.setHorizontalAlignment(SwingConstants.LEFT); - break; - } - - } - return editor; - } - - /** This method retrieves the AWT Color representation from the colour hash table - * - */ - private final Color getAWTColor(int index, Color deflt) { - HSSFColor clr = (HSSFColor)colors.get(Integer.valueOf(index)); - if (clr == null) return deflt; - return getAWTColor(clr); - } - - private static final Color getAWTColor(HSSFColor clr) { - short[] rgb = clr.getTriplet(); - return new Color(rgb[0],rgb[1],rgb[2]); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVTableCellRenderer.java b/src/examples/src/org/apache/poi/hssf/view/SVTableCellRenderer.java deleted file mode 100644 index 4b2e634bb3..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVTableCellRenderer.java +++ /dev/null @@ -1,274 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.view; - -import javax.swing.*; -import javax.swing.table.TableCellRenderer; -import javax.swing.border.*; - -import java.awt.Component; -import java.awt.Color; -import java.awt.Rectangle; - -import java.io.Serializable; -import java.text.*; - -import org.apache.poi.hssf.usermodel.*; - - -/** - * Sheet Viewer Table Cell Render -- not commented via javadoc as it - * nearly completely consists of overridden methods. - * - * @author Andrew C. Oliver - */ -public class SVTableCellRenderer extends JLabel - implements TableCellRenderer, Serializable -{ - protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); - protected SVBorder cellBorder = new SVBorder(); - - - private HSSFWorkbook wb = null; - - /** This class holds the references to the predefined cell formats. - */ - private class CellFormatter { - private Format[] textFormatter; - - private DecimalFormat generalNumberFormat = new DecimalFormat("0"); - - public CellFormatter() { - textFormatter = new Format[0x31]; - - textFormatter[0x01] = new DecimalFormat("0"); - textFormatter[0x02] = new DecimalFormat("0.00"); - textFormatter[0x03] = new DecimalFormat("#,##0"); - textFormatter[0x04] = new DecimalFormat("#,##0.00"); - textFormatter[0x05] = new DecimalFormat("$#,##0;$#,##0"); - textFormatter[0x06] = new DecimalFormat("$#,##0;$#,##0"); - textFormatter[0x07] = new DecimalFormat("$#,##0.00;$#,##0.00"); - textFormatter[0x08] = new DecimalFormat("$#,##0.00;$#,##0.00"); - textFormatter[0x09] = new DecimalFormat("0%"); - textFormatter[0x0A] = new DecimalFormat("0.00%"); - textFormatter[0x0B] = new DecimalFormat("0.00E0"); - textFormatter[0x0C] = new SVFractionalFormat("# ?/?"); - textFormatter[0x0D] = new SVFractionalFormat("# ??/??"); - textFormatter[0x0E] = new SimpleDateFormat("M/d/yy"); - textFormatter[0x0F] = new SimpleDateFormat("d-MMM-yy"); - textFormatter[0x10] = new SimpleDateFormat("d-MMM"); - textFormatter[0x11] = new SimpleDateFormat("MMM-yy"); - textFormatter[0x12] = new SimpleDateFormat("h:mm a"); - textFormatter[0x13] = new SimpleDateFormat("h:mm:ss a"); - textFormatter[0x14] = new SimpleDateFormat("h:mm"); - textFormatter[0x15] = new SimpleDateFormat("h:mm:ss"); - textFormatter[0x16] = new SimpleDateFormat("M/d/yy h:mm"); - // 0x17 - 0x24 reserved for international and undocumented 0x25, "(#,##0_);(#,##0)" - //start at 0x26 - //jmh need to do colour - //"(#,##0_);[Red](#,##0)" - textFormatter[0x26] = new DecimalFormat("#,##0;#,##0"); - //jmh need to do colour - //(#,##0.00_);(#,##0.00) - textFormatter[0x27] = new DecimalFormat("#,##0.00;#,##0.00"); - textFormatter[0x28] = new DecimalFormat("#,##0.00;#,##0.00"); -//?? textFormatter[0x29] = new DecimalFormat("_(*#,##0_);_(*(#,##0);_(* \"-\"_);_(@_)"); -//?? textFormatter[0x2A] = new DecimalFormat("_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"); -//?? textFormatter[0x2B] = new DecimalFormat("_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"); -//?? textFormatter[0x2C] = new DecimalFormat("_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"); - textFormatter[0x2D] = new SimpleDateFormat("mm:ss"); -//?? textFormatter[0x2E] = new SimpleDateFormat("[h]:mm:ss"); - textFormatter[0x2F] = new SimpleDateFormat("mm:ss.0"); - textFormatter[0x30] = new DecimalFormat("##0.0E0"); - } - - public String format(short index, Object value) { - if (index == 0) - return value.toString(); - if (textFormatter[index] == null) - throw new RuntimeException("Sorry. I cant handle the format code :"+Integer.toHexString(index)); - return textFormatter[index].format(value); - } - - public String format(short index, double value) { - if ( index <= 0 ) - return generalNumberFormat.format(value); - if (textFormatter[index] == null) - throw new RuntimeException("Sorry. I cant handle the format code :"+Integer.toHexString(index)); - if (textFormatter[index] instanceof DecimalFormat) { - return ((DecimalFormat)textFormatter[index]).format(value); - } - if (textFormatter[index] instanceof SVFractionalFormat) { - return ((SVFractionalFormat)textFormatter[index]).format(value); - } - throw new RuntimeException("Sorry. I cant handle a non decimal formatter for a decimal value :"+Integer.toHexString(index)); - } - - public boolean useRedColor(short index, double value) { - return (((index == 0x06)||(index == 0x08)||(index == 0x26) || (index == 0x27)) && (value < 0)); - } - } - - private final CellFormatter cellFormatter = new CellFormatter(); - - public SVTableCellRenderer(HSSFWorkbook wb) { - super(); - setOpaque(true); - setBorder(noFocusBorder); - this.wb = wb; - } - - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - boolean isBorderSet = false; - - //If the JTables default cell renderer has been setup correctly the - //value will be the HSSFCell that we are trying to render - HSSFCell c = (HSSFCell)value; - - if (c != null) { - HSSFCellStyle s = c.getCellStyle(); - HSSFFont f = wb.getFontAt(s.getFontIndex()); - setFont(SVTableUtils.makeFont(f)); - - if (s.getFillPattern() == HSSFCellStyle.SOLID_FOREGROUND) { - setBackground(SVTableUtils.getAWTColor(s.getFillForegroundColor(), SVTableUtils.white)); - } else setBackground(SVTableUtils.white); - - setForeground(SVTableUtils.getAWTColor(f.getColor(), SVTableUtils.black)); - - cellBorder.setBorder(SVTableUtils.getAWTColor(s.getTopBorderColor(), SVTableUtils.black), - SVTableUtils.getAWTColor(s.getRightBorderColor(), SVTableUtils.black), - SVTableUtils.getAWTColor(s.getBottomBorderColor(), SVTableUtils.black), - SVTableUtils.getAWTColor(s.getLeftBorderColor(), SVTableUtils.black), - s.getBorderTop(), s.getBorderRight(), - s.getBorderBottom(), s.getBorderLeft(), - hasFocus); - setBorder(cellBorder); - isBorderSet=true; - - //Set the value that is rendered for the cell - switch (c.getCellType()) { - case HSSFCell.CELL_TYPE_BLANK: - setValue(""); - break; - case HSSFCell.CELL_TYPE_BOOLEAN: - if (c.getBooleanCellValue()) { - setValue("true"); - } else { - setValue("false"); - } - break; - case HSSFCell.CELL_TYPE_NUMERIC: - short format = s.getDataFormat(); - double numericValue = c.getNumericCellValue(); - if (cellFormatter.useRedColor(format, numericValue)) - setForeground(Color.red); - else setForeground(null); - setValue(cellFormatter.format(format, c.getNumericCellValue())); - break; - case HSSFCell.CELL_TYPE_STRING: - setValue(c.getRichStringCellValue().getString()); - break; - case HSSFCell.CELL_TYPE_FORMULA: - default: - setValue("?"); - } - //Set the text alignment of the cell - switch (s.getAlignment()) { - case HSSFCellStyle.ALIGN_LEFT: - case HSSFCellStyle.ALIGN_JUSTIFY: - case HSSFCellStyle.ALIGN_FILL: - setHorizontalAlignment(SwingConstants.LEFT); - break; - case HSSFCellStyle.ALIGN_CENTER: - case HSSFCellStyle.ALIGN_CENTER_SELECTION: - setHorizontalAlignment(SwingConstants.CENTER); - break; - case HSSFCellStyle.ALIGN_GENERAL: - case HSSFCellStyle.ALIGN_RIGHT: - setHorizontalAlignment(SwingConstants.RIGHT); - break; - default: - setHorizontalAlignment(SwingConstants.LEFT); - break; - } - } else { - setValue(""); - setBackground(SVTableUtils.white); - } - - - if (hasFocus) { - if (!isBorderSet) { - //This is the border to paint when there is no border - //and the cell has focus - cellBorder.setBorder(SVTableUtils.black, - SVTableUtils.black, - SVTableUtils.black, - SVTableUtils.black, - HSSFCellStyle.BORDER_NONE, - HSSFCellStyle.BORDER_NONE, - HSSFCellStyle.BORDER_NONE, - HSSFCellStyle.BORDER_NONE, - isSelected); - setBorder(cellBorder); - } - if (table.isCellEditable(row, column)) { - setForeground( UIManager.getColor("Table.focusCellForeground") ); - setBackground( UIManager.getColor("Table.focusCellBackground") ); - } - } else if (!isBorderSet) { - setBorder(noFocusBorder); - } - - // ---- begin optimization to avoid painting background ---- - Color back = getBackground(); - boolean colorMatch = (back != null) && ( back.equals(table.getBackground()) ) && table.isOpaque(); - setOpaque(!colorMatch); - // ---- end optimization to aviod painting background ---- - return this; - } - - public void validate() {} - - public void revalidate() {} - - public void repaint(long tm, int x, int y, int width, int height) {} - - public void repaint(Rectangle r) { } - - protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - // Strings get interned... - if (propertyName=="text") { - super.firePropertyChange(propertyName, oldValue, newValue); - } - } - - public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { } - - /** - * Sets the string to either the value or "" if the value is null. - * - */ - protected void setValue(Object value) { - setText((value == null) ? "" : value.toString()); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVTableModel.java b/src/examples/src/org/apache/poi/hssf/view/SVTableModel.java deleted file mode 100644 index 170dacb697..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVTableModel.java +++ /dev/null @@ -1,87 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi.hssf.view; - -import java.util.Iterator; -import javax.swing.table.*; - -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFCell; - -/** - * Sheet Viewer Table Model - The model for the Sheet Viewer just overrides things. - * @author Andrew C. Oliver - */ - -public class SVTableModel extends AbstractTableModel { - private HSSFSheet st = null; - int maxcol = 0; - - public SVTableModel(HSSFSheet st, int maxcol) { - this.st = st; - this.maxcol=maxcol; - } - - public SVTableModel(HSSFSheet st) { - this.st = st; - Iterator i = st.rowIterator(); - - while (i.hasNext()) { - HSSFRow row = (HSSFRow)i.next(); - if (maxcol < (row.getLastCellNum()+1)) { - this.maxcol = row.getLastCellNum(); - } - } - } - - - public int getColumnCount() { - return this.maxcol+1; - } - public Object getValueAt(int row, int col) { - HSSFRow r = st.getRow(row); - HSSFCell c = null; - if (r != null) { - c = r.getCell(col); - } - return c; - } - public int getRowCount() { - return st.getLastRowNum() + 1; - } - - public Class getColumnClass(int c) { - return HSSFCell.class; - } - - public boolean isCellEditable(int rowIndex, int columnIndex) { - return true; - } - - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - if (aValue != null) - System.out.println("SVTableModel.setValueAt. value type = "+aValue.getClass().getName()); - else System.out.println("SVTableModel.setValueAt. value type = null"); - } - - -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVTableUtils.java b/src/examples/src/org/apache/poi/hssf/view/SVTableUtils.java deleted file mode 100644 index 23ffb851bd..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVTableUtils.java +++ /dev/null @@ -1,93 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.view; - -import java.util.*; -import java.awt.*; -import javax.swing.border.*; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.util.*; - -/** - * SVTableCell Editor and Renderer helper functions. - * - * @author Jason Height - */ -public class SVTableUtils { - private final static Map colors = HSSFColor.getIndexHash(); - /** Description of the Field */ - public final static Color black = getAWTColor(new HSSFColor.BLACK()); - /** Description of the Field */ - public final static Color white = getAWTColor(new HSSFColor.WHITE()); - /** Description of the Field */ - public static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); - - - /** - * Creates a new font for a specific cell style - */ - public static Font makeFont(HSSFFont font) { - boolean isbold = font.getBoldweight() > HSSFFont.BOLDWEIGHT_NORMAL; - boolean isitalics = font.getItalic(); - int fontstyle = Font.PLAIN; - if (isbold) { - fontstyle = Font.BOLD; - } - if (isitalics) { - fontstyle = fontstyle | Font.ITALIC; - } - - int fontheight = font.getFontHeightInPoints(); - if (fontheight == 9) { - //fix for stupid ol Windows - fontheight = 10; - } - - return new Font(font.getFontName(), fontstyle, fontheight); - } - - - /** - * This method retrieves the AWT Color representation from the colour hash table - * - * @param index Description of the Parameter - * @param deflt Description of the Parameter - * @return The aWTColor value - */ - public final static Color getAWTColor(int index, Color deflt) { - HSSFColor clr = (HSSFColor) colors.get(Integer.valueOf(index)); - if (clr == null) { - return deflt; - } - return getAWTColor(clr); - } - - - /** - * Gets the aWTColor attribute of the SVTableUtils class - * - * @param clr Description of the Parameter - * @return The aWTColor value - */ - public final static Color getAWTColor(HSSFColor clr) { - short[] rgb = clr.getTriplet(); - return new Color(rgb[0], rgb[1], rgb[2]); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SViewer.java b/src/examples/src/org/apache/poi/hssf/view/SViewer.java deleted file mode 100644 index de2cfb1f6d..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SViewer.java +++ /dev/null @@ -1,172 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi.hssf.view; - -import java.awt.*; -import java.awt.event.*; -import java.net.*; -import java.io.*; -import javax.swing.*; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Sheet Viewer - Views XLS files via HSSF. Can be used as an applet with - * filename="" or as a applications (pass the filename as the first parameter). - * Or you can pass it a URL in a "url" parameter when run as an applet or just - * that first parameter must start with http:// and it will guess its a url. I - * only tested it as an applet though, so it probably won't work...you fix it. - * - * @author Andrew C. Oliver - * @author Jason Height - */ -public class SViewer extends JApplet { - private SViewerPanel panel; - boolean isStandalone = false; - String filename = null; - - /**Get a parameter value*/ - public String getParameter(String key, String def) { - return isStandalone ? System.getProperty(key, def) : - (getParameter(key) != null ? getParameter(key) : def); - } - - /**Construct the applet*/ - public SViewer() { - } - - /**Initialize the applet*/ - public void init() { - try { - jbInit(); - } - catch(Exception e) { - e.printStackTrace(); - System.exit(1); - } - } - - /**Component initialization*/ - private void jbInit() throws Exception { - InputStream i = null; - boolean isurl = false; - if (filename == null) filename = getParameter("filename"); - - if (filename == null || filename.substring(0,7).equals("http://")) { - isurl = true; - if (filename == null) filename = getParameter("url"); - i = getXLSFromURL(filename); - } - - HSSFWorkbook wb = null; - if (isurl) { - wb = constructWorkbook(i); - } else { - wb = constructWorkbook(filename); - } - panel = new SViewerPanel(wb, false); - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(panel, BorderLayout.CENTER); - } - - private HSSFWorkbook constructWorkbook(String filename) throws FileNotFoundException, IOException { - HSSFWorkbook wb = null; - FileInputStream in = new FileInputStream(filename); - wb = new HSSFWorkbook(in); - in.close(); - return wb; - } - - private HSSFWorkbook constructWorkbook(InputStream in) throws IOException { - HSSFWorkbook wb = null; - - wb = new HSSFWorkbook(in); - in.close(); - return wb; - } - - /**Start the applet*/ - public void start() { - } - /**Stop the applet*/ - public void stop() { - } - /**Destroy the applet*/ - public void destroy() { - } - /**Get Applet information*/ - public String getAppletInfo() { - return "Applet Information"; - } - /**Get parameter info*/ - public String[][] getParameterInfo() { - return null; - } - - /** - * opens a url and returns an inputstream - * - */ - private InputStream getXLSFromURL(String urlstring) throws MalformedURLException, IOException { - URL url = new URL(urlstring); - URLConnection uc = url.openConnection(); - String field = uc.getHeaderField(0); - for (int i=0;field != null; i++) { - System.out.println(field); - field = uc.getHeaderField(i); - } - BufferedInputStream is = new BufferedInputStream(uc.getInputStream()); - return is; - } - - - /**Main method*/ - public static void main(String[] args) { - if(args.length < 1) { - throw new IllegalArgumentException("A filename to view must be supplied as the first argument, but none was given"); - } - - SViewer applet = new SViewer(); - applet.isStandalone = true; - applet.filename = args[0]; - Frame frame; - frame = new Frame() { - protected void processWindowEvent(WindowEvent e) { - super.processWindowEvent(e); - if (e.getID() == WindowEvent.WINDOW_CLOSING) { - System.exit(0); - } - } - public synchronized void setTitle(String title) { - super.setTitle(title); - enableEvents(AWTEvent.WINDOW_EVENT_MASK); - } - }; - frame.setTitle("Applet Frame"); - frame.add(applet, BorderLayout.CENTER); - applet.init(); - applet.start(); - frame.setSize(400,320); - Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); - frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2); - frame.setVisible(true); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java b/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java deleted file mode 100644 index 5fe596220a..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java +++ /dev/null @@ -1,292 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.view; - -import java.awt.*; -import java.awt.event.*; -import java.io.*; -import javax.swing.*; -import javax.swing.table.*; - -import org.apache.poi.hssf.usermodel.*; - -/** - * This class presents the sheets to the user. - * - * - * @author Andrew C. Oliver - * @author Jason Height - */ -public class SViewerPanel extends JPanel { - /** This field is the magic number to convert from a Character width to a - * java pixel width. - * - * When the "normal" font size in a workbook changes, this effects all - * of the heights and widths. Unfortunately there is no way to retrieve this - * information, hence the MAGIC number. - * - * This number may only work for the normal style font size of Arial size 10. - * - */ - private static final int magicCharFactor = 7; - /** Reference to the wookbook that is being displayed*/ - /* package */ HSSFWorkbook wb; - /** Reference to the tabs component*/ - /* package */ JTabbedPane sheetPane; - /** Reference to the cell renderer that is used to render all cells*/ - private SVTableCellRenderer cellRenderer; - /** Reference to the cell editor that is used to edit all cells. - * Only constructed if editing is allowed - */ - private SVTableCellEditor cellEditor; - /** Flag indicating if editing is allowed. Otherwise the viewer is in - * view only mode. - */ - private boolean allowEdits; - - /**Construct the representation of the workbook*/ - public SViewerPanel(HSSFWorkbook wb, boolean allowEdits) { - this.wb = wb; - this.allowEdits = allowEdits; - - initialiseGui(); - } - - private void initialiseGui() { - cellRenderer = new SVTableCellRenderer(this.wb); - if (allowEdits) - cellEditor = new SVTableCellEditor(this.wb); - - //Initialise the Panel - sheetPane = new JTabbedPane(JTabbedPane.BOTTOM); - - if (allowEdits) - sheetPane.addMouseListener(createTabListener()); - int sheetCount = wb.getNumberOfSheets(); - for (int i=0; i - * It is up to the parent component to invoke the {@link #paint(Graphics2D)} - * method of this objet at that appropriate time. - * - * @author Ken Arnold, Industrious Media LLC - */ -public class PendingPaintings { - /** - * The name of the client property that holds this object in the parent - * component. - */ - public static final String PENDING_PAINTINGS = - PendingPaintings.class.getSimpleName(); - - private final List paintings; - - /** A single painting description. */ - public static class Painting { - final Stroke stroke; - final Color color; - final Shape shape; - final AffineTransform transform; - - /** - * Creates a new painting description. - * - * @param stroke The stroke to paint. - * @param color The color of the stroke. - * @param shape The shape of the stroke. - * @param transform The transformation matrix to use. - */ - public Painting(Stroke stroke, Color color, Shape shape, - AffineTransform transform) { - - this.color = color; - this.shape = shape; - this.stroke = stroke; - this.transform = transform; - } - - /** - * Draw the painting. - * - * @param g The graphics object to use to draw with. - */ - public void draw(Graphics2D g) { - g.setTransform(transform); - g.setStroke(stroke); - g.setColor(color); - g.draw(shape); - } - } - - /** - * Creates a new object on the given parent. The created object will be - * stored as a client property. - * - * @param parent - */ - public PendingPaintings(JComponent parent) { - paintings = new ArrayList(); - parent.putClientProperty(PENDING_PAINTINGS, this); - } - - /** Drops all pending paintings. */ - public void clear() { - paintings.clear(); - } - - /** - * Paints all pending paintings. Once they have been painted they are - * removed from the list of pending paintings (they aren't pending anymore, - * after all). - * - * @param g The graphics object to draw with. - */ - public void paint(Graphics2D g) { - g.setBackground(Color.CYAN); - AffineTransform origTransform = g.getTransform(); - for (Painting c : paintings) { - c.draw(g); - } - g.setTransform(origTransform); - - clear(); - } - - /** - * Adds a new pending painting to the list on the given component. This - * will find the first ancestor that has a {@link PendingPaintings} client - * property, starting with the component itself. - * - * @param c The component for which the painting is being added. - * @param g The graphics object to draw with. - * @param stroke The stroke to draw. - * @param color The color to draw with. - * @param shape The shape to stroke. - */ - public static void add(JComponent c, Graphics2D g, Stroke stroke, - Color color, Shape shape) { - - add(c, new Painting(stroke, color, shape, g.getTransform())); - } - - /** - * Adds a new pending painting to the list on the given component. This - * will find the first ancestor that has a {@link PendingPaintings} client - * property, starting with the component itself. - * - * @param c The component for which the painting is being added. - * @param newPainting The new painting. - */ - public static void add(JComponent c, Painting newPainting) { - PendingPaintings pending = pendingPaintingsFor(c); - if (pending != null) { - pending.paintings.add(newPainting); - } - } - - /** - * Returns the pending painting object for the given component, if any. This - * is retrieved from the first object found that has a {@link - * #PENDING_PAINTINGS} client property, starting with this component and - * looking up its ancestors (parent, parent's parent, etc.) - *

      - * This allows any descendant of a component that has a {@link - * PendingPaintings} property to add its own pending paintings. - * - * @param c The component for which the painting is being added. - * - * @return The pending painting object for that component, or null - * if there is none. - */ - public static PendingPaintings pendingPaintingsFor(JComponent c) { - for (Component parent = c; - parent != null; - parent = parent.getParent()) { - if (parent instanceof JComponent) { - JComponent jc = (JComponent) parent; - Object pd = jc.getClientProperty(PENDING_PAINTINGS); - if (pd != null) - return (PendingPaintings) pd; - } - } - return null; - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/hssf/view/brush/package.html b/src/examples/src/org/apache/poi/hssf/view/brush/package.html deleted file mode 100644 index d9819fb669..0000000000 --- a/src/examples/src/org/apache/poi/hssf/view/brush/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - -This package contains some brushes that are used when drawing borders for Excel -cells. - - diff --git a/src/examples/src/org/apache/poi/hwpf/Word2Forrest.java b/src/examples/src/org/apache/poi/hwpf/Word2Forrest.java deleted file mode 100644 index 82d3a8a230..0000000000 --- a/src/examples/src/org/apache/poi/hwpf/Word2Forrest.java +++ /dev/null @@ -1,225 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.usermodel.*; -import org.apache.poi.hwpf.model.*; - -import java.io.*; - -public final class Word2Forrest -{ - Writer _out; - HWPFDocument _doc; - - public Word2Forrest(HWPFDocument doc, OutputStream stream) - throws IOException, UnsupportedEncodingException - { - OutputStreamWriter out = new OutputStreamWriter (stream, "UTF-8"); - _out = out; - _doc = doc; - - init (); - openDocument (); - openBody (); - - Range r = doc.getRange (); - StyleSheet styleSheet = doc.getStyleSheet (); - - int sectionLevel = 0; - int lenParagraph = r.numParagraphs (); - boolean inCode = false; - for (int x = 0; x < lenParagraph; x++) - { - Paragraph p = r.getParagraph (x); - String text = p.text (); - if (text.trim ().length () == 0) - { - continue; - } - StyleDescription paragraphStyle = styleSheet.getStyleDescription (p. - getStyleIndex ()); - String styleName = paragraphStyle.getName(); - if (styleName.startsWith ("Heading")) - { - if (inCode) - { - closeSource(); - inCode = false; - } - - int headerLevel = Integer.parseInt (styleName.substring (8)); - if (headerLevel > sectionLevel) - { - openSection (); - } - else - { - for (int y = 0; y < (sectionLevel - headerLevel) + 1; y++) - { - closeSection (); - } - openSection (); - } - sectionLevel = headerLevel; - openTitle (); - writePlainText (text); - closeTitle (); - } - else - { - int cruns = p.numCharacterRuns (); - CharacterRun run = p.getCharacterRun (0); - String fontName = run.getFontName(); - if (fontName.startsWith ("Courier")) - { - if (!inCode) - { - openSource (); - inCode = true; - } - writePlainText (p.text()); - } - else - { - if (inCode) - { - inCode = false; - closeSource(); - } - openParagraph(); - writePlainText(p.text()); - closeParagraph(); - } - } - } - for (int x = 0; x < sectionLevel; x++) - { - closeSection(); - } - closeBody(); - closeDocument(); - _out.flush(); - - } - - public void init () - throws IOException - { - _out.write ("\r\n"); - _out.write ("\r\n"); - } - - public void openDocument () - throws IOException - { - _out.write ("\r\n"); - } - public void closeDocument () - throws IOException - { - _out.write ("\r\n"); - } - - - public void openBody () - throws IOException - { - _out.write ("\r\n"); - } - - public void closeBody () - throws IOException - { - _out.write ("\r\n"); - } - - - public void openSection () - throws IOException - { - _out.write ("

      "); - - } - - public void closeSection () - throws IOException - { - _out.write ("
      "); - - } - - public void openTitle () - throws IOException - { - _out.write (""); - } - - public void closeTitle () - throws IOException - { - _out.write (""); - } - - public void writePlainText (String text) - throws IOException - { - _out.write (text); - } - - public void openParagraph () - throws IOException - { - _out.write ("

      "); - } - - public void closeParagraph () - throws IOException - { - _out.write ("

      "); - } - - public void openSource () - throws IOException - { - _out.write (""); - } - - - public static void main(String[] args) - { - try - { - OutputStream out = new FileOutputStream("c:\\test.xml"); - - new Word2Forrest(new HWPFDocument(new FileInputStream(args[0])), out); - out.close(); - } - catch (Throwable t) - { - t.printStackTrace(); - } - - } -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/Codec.java b/src/examples/src/org/apache/poi/poifs/poibrowser/Codec.java deleted file mode 100644 index 2660f5cc67..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/Codec.java +++ /dev/null @@ -1,241 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -import org.apache.poi.hpsf.ClassID; - - - -/** - *

      Provides utility methods for encoding and decoding hexadecimal - * data.

      - * - * @author Rainer Klute (klute@rainer-klute.de) - with portions from Tomcat - */ -public class Codec -{ - - /** - *

      The nibbles' hexadecimal values. A nibble is a half byte.

      - */ - protected static final byte hexval[] = - {(byte) '0', (byte) '1', (byte) '2', (byte) '3', - (byte) '4', (byte) '5', (byte) '6', (byte) '7', - (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', - (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F'}; - - - - /** - *

      Converts a string into its hexadecimal notation.

      - */ - public static String hexEncode(final String s) - { - return hexEncode(s.getBytes()); - } - - - - /** - *

      Converts a byte array into its hexadecimal notation.

      - */ - public static String hexEncode(final byte[] s) - { - return hexEncode(s, 0, s.length); - } - - - - /** - *

      Converts a part of a byte array into its hexadecimal - * notation.

      - */ - public static String hexEncode(final byte[] s, final int offset, - final int length) - { - StringBuffer b = new StringBuffer(length * 2); - for (int i = offset; i < offset + length; i++) - { - int c = s[i]; - b.append((char) hexval[(c & 0xF0) >> 4]); - b.append((char) hexval[(c & 0x0F) >> 0]); - } - return b.toString(); - } - - - - /** - *

      Converts a single byte into its hexadecimal notation.

      - */ - public static String hexEncode(final byte b) - { - StringBuffer sb = new StringBuffer(2); - sb.append((char) hexval[(b & 0xF0) >> 4]); - sb.append((char) hexval[(b & 0x0F) >> 0]); - return sb.toString(); - } - - - - /** - *

      Converts a short value (16-bit) into its hexadecimal - * notation.

      - */ - public static String hexEncode(final short s) - { - StringBuffer sb = new StringBuffer(4); - sb.append((char) hexval[(s & 0xF000) >> 12]); - sb.append((char) hexval[(s & 0x0F00) >> 8]); - sb.append((char) hexval[(s & 0x00F0) >> 4]); - sb.append((char) hexval[(s & 0x000F) >> 0]); - return sb.toString(); - } - - - - /** - *

      Converts an int value (32-bit) into its hexadecimal - * notation.

      - */ - public static String hexEncode(final int i) - { - StringBuffer sb = new StringBuffer(8); - sb.append((char) hexval[(i & 0xF0000000) >> 28]); - sb.append((char) hexval[(i & 0x0F000000) >> 24]); - sb.append((char) hexval[(i & 0x00F00000) >> 20]); - sb.append((char) hexval[(i & 0x000F0000) >> 16]); - sb.append((char) hexval[(i & 0x0000F000) >> 12]); - sb.append((char) hexval[(i & 0x00000F00) >> 8]); - sb.append((char) hexval[(i & 0x000000F0) >> 4]); - sb.append((char) hexval[(i & 0x0000000F) >> 0]); - return sb.toString(); - } - - - - /** - *

      Converts a long value (64-bit) into its hexadecimal - * notation.

      - */ - public static String hexEncode(final long l) - { - StringBuffer sb = new StringBuffer(16); - sb.append(hexEncode((int) (l & 0xFFFFFFFF00000000L) >> 32)); - sb.append(hexEncode((int) (l & 0x00000000FFFFFFFFL) >> 0)); - return sb.toString(); - } - - - - /** - *

      Converts a class ID into its hexadecimal notation.

      - */ - public static String hexEncode(final ClassID classID) - { - return hexEncode(classID.getBytes()); - } - - - - /** - *

      Decodes the hexadecimal representation of a sequence of - * bytes into a byte array. Each character in the string - * represents a nibble (half byte) and must be one of the - * characters '0'-'9', 'A'-'F' or 'a'-'f'.

      - * - * @param s The string to be decoded - * - * @return The bytes - * - * @throws IllegalArgumentException if the string does not contain - * a valid representation of a byte sequence. - */ - public static byte[] hexDecode(final String s) - { - final int length = s.length(); - - /* The string to be converted must have an even number of - characters. */ - if (length % 2 == 1) - throw new IllegalArgumentException - ("String has odd length " + length); - byte[] b = new byte[length / 2]; - char[] c = new char[length]; - s.toUpperCase().getChars(0, length, c, 0); - for (int i = 0; i < length; i += 2) - b[i/2] = (byte) (decodeNibble(c[i]) << 4 & 0xF0 | - decodeNibble(c[i+1]) & 0x0F); - return b; - } - - - - /** - *

      Decodes a nibble.

      - * - * @param c A character in the range '0'-'9' or 'A'-'F'. Lower - * case is not supported here. - * - * @return The decoded nibble in the range 0-15 - * - * @throws IllegalArgumentException if c is not a - * permitted character - */ - protected static byte decodeNibble(final char c) - { - for (byte i = 0; i < hexval.length; i++) - if ((byte) c == hexval[i]) - return i; - throw new IllegalArgumentException("\"" + c + "\"" + - " does not represent a nibble."); - } - - - - /** - *

      For testing.

      - */ - public static void main(final String args[]) - throws IOException - { - final BufferedReader in = - new BufferedReader(new InputStreamReader(System.in)); - String s; - do - { - s = in.readLine(); - if (s != null) - { - String bytes = hexEncode(s); - System.out.print("Hex encoded (String): "); - System.out.println(bytes); - System.out.print("Hex encoded (byte[]): "); - System.out.println(hexEncode(s.getBytes())); - System.out.print("Re-decoded (byte[]): "); - System.out.println(new String(hexDecode(bytes))); - } - } - while (s != null); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java b/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java deleted file mode 100644 index c9647f9a22..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.io.*; -import org.apache.poi.poifs.filesystem.*; - -/** - *

      Describes the most important (whatever that is) features of a - * {@link POIFSDocument}.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class DocumentDescriptor -{ - String name; - POIFSDocumentPath path; - DocumentInputStream stream; - - int size; - byte[] bytes; - - - /** - *

      Creates a {@link DocumentDescriptor}.

      - * - * @param name The stream's name. - * - * @param path The stream's path in the POI filesystem hierarchy. - * - * @param stream The stream. - * - * @param nrOfBytes The maximum number of bytes to display in a - * dump starting at the beginning of the stream. - */ - public DocumentDescriptor(final String name, - final POIFSDocumentPath path, - final DocumentInputStream stream, - final int nrOfBytes) - { - this.name = name; - this.path = path; - this.stream = stream; - try - { - size = stream.available(); - if (stream.markSupported()) - { - stream.mark(nrOfBytes); - final byte[] b = new byte[nrOfBytes]; - final int read = stream.read(b, 0, Math.min(size, b.length)); - bytes = new byte[read]; - System.arraycopy(b, 0, bytes, 0, read); - stream.reset(); - } - } - catch (IOException ex) - { - System.out.println(ex); - } - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java b/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java deleted file mode 100644 index 599ea7cc1c..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.*; -import javax.swing.*; -import javax.swing.tree.*; - -/** - *

      {@link TreeCellRenderer} for a {@link DocumentDescriptor}. The - * renderer is extremly rudimentary since displays only the document's - * name, its size and its fist few bytes.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class DocumentDescriptorRenderer extends DefaultTreeCellRenderer -{ - - public Component getTreeCellRendererComponent(final JTree tree, - final Object value, - final boolean selected, - final boolean expanded, - final boolean leaf, - final int row, - final boolean hasFocus) - { - final DocumentDescriptor d = (DocumentDescriptor) - ((DefaultMutableTreeNode) value).getUserObject(); - final JPanel p = new JPanel(); - final JTextArea text = new JTextArea(); - text.append(renderAsString(d)); - text.setFont(new Font("Monospaced", Font.PLAIN, 10)); - p.add(text); - if (selected) - Util.invert(text); - return p; - } - - - /** - *

      Renders {@link DocumentDescriptor} as a string.

      - */ - protected String renderAsString(final DocumentDescriptor d) - { - final StringBuffer b = new StringBuffer(); - b.append("Name: "); - b.append(d.name); - b.append(" ("); - b.append(Codec.hexEncode(d.name)); - b.append(") \n"); - - b.append("Size: "); - b.append(d.size); - b.append(" bytes\n"); - - b.append("First bytes: "); - b.append(Codec.hexEncode(d.bytes)); - - return b.toString(); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java b/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java deleted file mode 100644 index 7f73ebce46..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.*; -import javax.swing.*; -import javax.swing.tree.*; -import java.util.*; - -/** - *

      This is a {@link TreeCellRenderer} implementation which is able - * to render arbitrary objects. The {@link ExtendableTreeCellRenderer} - * does not do the rendering itself but instead dispatches to - * class-specific renderers. A class/renderer pair must be registered - * using the {@link #register} method. If a class has no registered - * renderer, the renderer of its closest superclass is used. Since the - * {@link ExtendableTreeCellRenderer} always has a default renderer - * for the {@link Object} class, rendering is always possible. The - * default {@link Object} renderer can be replaced by another renderer - * but it cannot be unregistered.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class ExtendableTreeCellRenderer implements TreeCellRenderer -{ - - /** - *

      Maps classes to renderers.

      - */ - protected Map renderers; - - - - public ExtendableTreeCellRenderer() - { - renderers = new HashMap(); - register(Object.class, new DefaultTreeCellRenderer() - { - public Component getTreeCellRendererComponent - (JTree tree, Object value, boolean selected, - boolean expanded, boolean leaf, int row, boolean hasFocus) - { - final String s = value.toString(); - final JLabel l = new JLabel(s + " "); - if (selected) - { - Util.invert(l); - l.setOpaque(true); - } - return l; - } - }); - } - - - - /** - *

      Registers a renderer for a class.

      - **/ - public void register(final Class c, final TreeCellRenderer renderer) - { - renderers.put(c, renderer); - } - - - - /** - *

      Unregisters a renderer for a class. The renderer for the - * {@link Object} class cannot be unregistered.

      - */ - public void unregister(final Class c) - { - if (c == Object.class) - throw new IllegalArgumentException - ("Renderer for Object cannot be unregistered."); - renderers.put(c, null); - } - - - - /** - *

      Renders an object in a tree cell depending of the object's - * class.

      - * - * @see TreeCellRenderer#getTreeCellRendererComponent - */ - public Component getTreeCellRendererComponent - (final JTree tree, final Object value, final boolean selected, - final boolean expanded, final boolean leaf, final int row, - final boolean hasFocus) - { - final String NULL = "null"; - TreeCellRenderer r; - Object userObject; - if (value == null) - userObject = NULL; - else - { - userObject = ((DefaultMutableTreeNode) value).getUserObject(); - if (userObject == null) - userObject = NULL; - } - r = findRenderer(userObject.getClass()); - return r.getTreeCellRendererComponent - (tree, value, selected, expanded, leaf, row, - hasFocus); - } - - - - /** - *

      Find the renderer for the specified class.

      - */ - protected TreeCellRenderer findRenderer(final Class c) - { - final TreeCellRenderer r = (TreeCellRenderer) renderers.get(c); - if (r != null) - /* The class has a renderer. */ - return r; - - /* The class has no renderer, try the superclass, if any. */ - final Class superclass = c.getSuperclass(); - if (superclass != null) { - return findRenderer(superclass); - } - return null; - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java b/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java deleted file mode 100644 index 7dc487db85..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.FileInputStream; -import java.io.IOException; - -import javax.swing.JFrame; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.MutableTreeNode; - -import org.apache.poi.poifs.eventfilesystem.POIFSReader; - -/** - *

      The main class of the POI Browser. It shows the structure of POI - * filesystems (Microsoft Office documents) in a {@link - * JTree}. Specify their filenames on the command line!

      - * - * @see POIFSReader - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class POIBrowser extends JFrame -{ - - /** - *

      The tree's root node must be visible to all methods.

      - */ - protected MutableTreeNode rootNode; - - - - /** - *

      Takes a bunch of file names as command line parameters, - * opens each of them as a POI filesystem and displays their - * internal structures in a {@link JTree}.

      - */ - public static void main(String[] args) - { - new POIBrowser().run(args); - } - - - - protected void run(String[] args) - { - addWindowListener(new WindowAdapter() - { - public void windowClosing(WindowEvent e) - { - System.exit(0); - } - }); - - /* Create the tree model with a root node. The latter is - * invisible but it must be present because a tree model - * always needs a root. */ - rootNode = new DefaultMutableTreeNode("POI Filesystems"); - DefaultTreeModel treeModel = new DefaultTreeModel(rootNode); - - /* Create the tree UI element. */ - final JTree treeUI = new JTree(treeModel); - getContentPane().add(new JScrollPane(treeUI)); - - /* Add the POI filesystems to the tree. */ - int displayedFiles = 0; - for (int i = 0; i < args.length; i++) - { - final String filename = args[i]; - try - { - POIFSReader r = new POIFSReader(); - r.registerListener(new TreeReaderListener(filename, rootNode)); - r.read(new FileInputStream(filename)); - displayedFiles++; - } - catch (IOException ex) - { - System.err.println(filename + ": " + ex); - } - catch (Throwable t) - { - System.err.println("Unexpected exception while reading \"" + - filename + "\":"); - t.printStackTrace(System.err); - } - } - - /* Exit if there is no file to display (none specified or only - * files with problems). */ - if (displayedFiles == 0) - { - System.out.println("No POI filesystem(s) to display."); - System.exit(0); - } - - /* Make the tree UI element visible. */ - treeUI.setRootVisible(true); - treeUI.setShowsRootHandles(true); - ExtendableTreeCellRenderer etcr = new ExtendableTreeCellRenderer(); - etcr.register(DocumentDescriptor.class, - new DocumentDescriptorRenderer()); - etcr.register(PropertySetDescriptor.class, - new PropertySetDescriptorRenderer()); - treeUI.setCellRenderer(etcr); - setSize(600, 450); - setTitle("POI Browser 0.09"); - setVisible(true); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java b/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java deleted file mode 100644 index 4596d0260d..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; - -/** - *

      Describes the most important (whatever that is) features of a - * stream containing a {@link PropertySet}.

      - * - * @author Rainer Klute (klute@rainer-klute.de) - */ -public class PropertySetDescriptor extends DocumentDescriptor -{ - - protected PropertySet propertySet; - - /** - *

      Returns this {@link PropertySetDescriptor}'s {@link - * PropertySet}.

      - */ - public PropertySet getPropertySet() - { - return propertySet; - } - - - - /** - *

      Creates a {@link PropertySetDescriptor} by reading a {@link - * PropertySet} from a {@link DocumentInputStream}.

      - * - * @param name The stream's name. - * - * @param path The stream's path in the POI filesystem hierarchy. - * - * @param stream The stream. - * - * @param nrOfBytesToDump The maximum number of bytes to display in a - * dump starting at the beginning of the stream. - */ - public PropertySetDescriptor(final String name, - final POIFSDocumentPath path, - final DocumentInputStream stream, - final int nrOfBytesToDump) - throws NoPropertySetStreamException, - MarkUnsupportedException, UnsupportedEncodingException, - IOException - { - super(name, path, stream, nrOfBytesToDump); - propertySet = PropertySetFactory.create(stream); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java b/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java deleted file mode 100644 index 75277d2f34..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.util.Iterator; -import java.util.List; - -import javax.swing.JPanel; -import javax.swing.JTextArea; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; - -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; - -/** - *

      Renders a {@link PropertySetDescriptor} by more or less dumping - * the stuff into a {@link JTextArea}.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class PropertySetDescriptorRenderer extends DocumentDescriptorRenderer -{ - - public Component getTreeCellRendererComponent(final JTree tree, - final Object value, - final boolean selected, - final boolean expanded, - final boolean leaf, - final int row, - final boolean hasFocus) - { - final PropertySetDescriptor d = (PropertySetDescriptor) - ((DefaultMutableTreeNode) value).getUserObject(); - final PropertySet ps = d.getPropertySet(); - final JPanel p = new JPanel(); - final JTextArea text = new JTextArea(); - text.setBackground(new Color(200, 255, 200)); - text.setFont(new Font("Monospaced", Font.PLAIN, 10)); - text.append(renderAsString(d)); - text.append("\nByte order: " + - Codec.hexEncode((short) ps.getByteOrder())); - text.append("\nFormat: " + - Codec.hexEncode((short) ps.getFormat())); - text.append("\nOS version: " + - Codec.hexEncode(ps.getOSVersion())); - text.append("\nClass ID: " + - Codec.hexEncode(ps.getClassID())); - text.append("\nSection count: " + ps.getSectionCount()); - text.append(sectionsToString(ps.getSections())); - p.add(text); - - if (ps instanceof SummaryInformation) - { - /* Use the convenience methods. */ - final SummaryInformation si = (SummaryInformation) ps; - text.append("\n"); - text.append("\nTitle: " + si.getTitle()); - text.append("\nSubject: " + si.getSubject()); - text.append("\nAuthor: " + si.getAuthor()); - text.append("\nKeywords: " + si.getKeywords()); - text.append("\nComments: " + si.getComments()); - text.append("\nTemplate: " + si.getTemplate()); - text.append("\nLast Author: " + si.getLastAuthor()); - text.append("\nRev. Number: " + si.getRevNumber()); - text.append("\nEdit Time: " + si.getEditTime()); - text.append("\nLast Printed: " + si.getLastPrinted()); - text.append("\nCreate Date/Time: " + si.getCreateDateTime()); - text.append("\nLast Save Date/Time: " + si.getLastSaveDateTime()); - text.append("\nPage Count: " + si.getPageCount()); - text.append("\nWord Count: " + si.getWordCount()); - text.append("\nChar Count: " + si.getCharCount()); - // text.append("\nThumbnail: " + si.getThumbnail()); - text.append("\nApplication Name: " + si.getApplicationName()); - text.append("\nSecurity: " + si.getSecurity()); - } - - if (selected) - Util.invert(text); - return p; - } - - - - /** - *

      Returns a string representation of a list of {@link - * Section}s.

      - */ - protected String sectionsToString(final List sections) - { - final StringBuffer b = new StringBuffer(); - int count = 1; - for (Iterator i = sections.iterator(); i.hasNext();) - { - Section s = (Section) i.next(); - String d = toString(s, "Section " + count++); - b.append(d); - } - return b.toString(); - } - - - - /** - *

      Returns a string representation of a {@link Section}.

      - * @param s the section - * @param name the section's name - * @return a string representation of the {@link Section} - */ - protected String toString(final Section s, final String name) - { - final StringBuffer b = new StringBuffer(); - b.append("\n" + name + " Format ID: "); - b.append(Codec.hexEncode(s.getFormatID())); - b.append("\n" + name + " Offset: " + s.getOffset()); - b.append("\n" + name + " Section size: " + s.getSize()); - b.append("\n" + name + " Property count: " + s.getPropertyCount()); - - final Property[] properties = s.getProperties(); - for (int i = 0; i < properties.length; i++) - { - final Property p = properties[i]; - final long id = p.getID(); - final long type = p.getType(); - final Object value = p.getValue(); - b.append('\n'); - b.append(name); - b.append(", Name: "); - b.append(id); - b.append(" ("); - b.append(s.getPIDString(id)); - b.append("), Type: "); - b.append(type); - b.append(", Value: "); - if (value instanceof byte[]) - { - byte[] b2 = (byte[]) value; - b.append("0x" + Codec.hexEncode(b2, 0, 4)); - b.append(' '); - b.append("0x" + Codec.hexEncode(b2, 4, b2.length - 4)); - } - else if (value != null) - b.append(value.toString()); - else - b.append("null"); - } - return b.toString(); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java b/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java deleted file mode 100644 index 34b59eb458..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java +++ /dev/null @@ -1,219 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.util.HashMap; -import java.util.Map; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.MutableTreeNode; - -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; - -/** - *

      Organizes document information in a tree model in order to be - * e.g. displayed in a Swing {@link javax.swing.JTree}. An instance of this - * class is created with a root tree node ({@link MutableTreeNode}) and - * registered as a {@link POIFSReaderListener} with a {@link - * org.apache.poi.poifs.eventfilesystem.POIFSReader}. While the latter processes - * a POI filesystem it calls this class' {@link #processPOIFSReaderEvent} for - * each document it has been registered for. This method appends the document it - * processes at the appropriate position into the tree rooted at the - * above mentioned root tree node.

      - * - *

      The root tree node should be the root tree node of a {@link - * javax.swing.tree.TreeModel}.

      - * - *

      A top-level element in the tree model, i.e. an immediate child - * node of the root node, describes a POI filesystem as such. It is - * suggested to use the file's name (as seen by the operating system) - * but it could be any other string.

      - * - *

      The value of a tree node is a {@link DocumentDescriptor}. Unlike - * a {@link org.apache.poi.poifs.filesystem.POIFSDocument} which may be as heavy - * as many megabytes, an instance of {@link DocumentDescriptor} is a - * light-weight object and contains only some meta-information about a - * document.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class TreeReaderListener implements POIFSReaderListener -{ - - /** - *

      The tree's root node. POI filesystems get attached to this - * node as children.

      - */ - protected MutableTreeNode rootNode; - - /** - *

      Maps filenames and POI document paths to their associated - * tree nodes.

      - */ - protected Map pathToNode; - - /** - *

      The name of the file this {@link TreeReaderListener} - * processes. It is used to identify a top-level element in the - * tree. Alternatively any other string can be used. It is just a - * label which should identify a POI filesystem.

      - */ - protected String filename; - - - - /** - *

      Creates a {@link TreeReaderListener} which should then be - * registered with a - * {@link org.apache.poi.poifs.eventfilesystem.POIFSReader}.

      - * - * @param filename The name of the POI filesystem, i.e. the name - * of the file the POI filesystem resides in. Alternatively any - * other string can be used. - * - * @param rootNode All document information will be attached as - * descendands to this tree node. - */ - public TreeReaderListener(final String filename, - final MutableTreeNode rootNode) - { - this.filename = filename; - this.rootNode = rootNode; - pathToNode = new HashMap(15); // Should be a reasonable guess. - } - - - - /**

      The number of bytes to dump.

      */ - private int nrOfBytes = 50; - - public void setNrOfBytes(final int nrOfBytes) - { - this.nrOfBytes = nrOfBytes; - } - - public int getNrOfBytes() - { - return nrOfBytes; - } - - - - /** - *

      A document in the POI filesystem has been opened for - * reading. This method retrieves properties of the document and - * adds them to a tree model.

      - */ - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - DocumentDescriptor d; - final DocumentInputStream is = event.getStream(); - if (!is.markSupported()) - throw new UnsupportedOperationException(is.getClass().getName() + - " does not support mark()."); - - /* Try do handle this document as a property set. We receive - * an exception if is no property set and handle it as a - * document of some other format. We are not concerned about - * that document's details. */ - try - { - d = new PropertySetDescriptor(event.getName(), event.getPath(), - is, nrOfBytes); - } - catch (HPSFException ex) - { - d = new DocumentDescriptor(event.getName(), event.getPath(), - is, nrOfBytes); - } - catch (Throwable t) - { - System.err.println - ("Unexpected exception while processing " + - event.getName() + " in " + event.getPath().toString()); - t.printStackTrace(System.err); - throw new RuntimeException(t.getMessage()); - } - - is.close(); - - final MutableTreeNode parentNode = getNode(d.path, filename, rootNode); - final MutableTreeNode nameNode = new DefaultMutableTreeNode(d.name); - parentNode.insert(nameNode, 0); - final MutableTreeNode dNode = new DefaultMutableTreeNode(d); - nameNode.insert(dNode, 0); - } - - - - /** - *

      Locates the parent node for a document entry in the tree - * model. If the parent node does not yet exist it will be - * created, too. This is done recursively, if needed.

      - * - * @param path The tree node for this path is located. - * - * @param fsName The name of the POI filesystem. This is just a - * string which is displayed in the tree at the top lovel. - * - * @param root The root node. - */ - private MutableTreeNode getNode(final POIFSDocumentPath path, - final String fsName, - final MutableTreeNode root) - { - MutableTreeNode n = (MutableTreeNode) pathToNode.get(path); - if (n != null) - /* Node found in map, just return it. */ - return n; - if (path.length() == 0) - { - /* This is the root path of the POI filesystem. Its tree - * node is resp. must be located below the tree node of - * the POI filesystem itself. This is a tree node with the - * POI filesystem's name (this the operating system file's - * name) as its key it the path-to-node map. */ - n = (MutableTreeNode) pathToNode.get(fsName); - if (n == null) - { - /* A tree node for the POI filesystem does not yet - * exist. */ - n = new DefaultMutableTreeNode(fsName); - pathToNode.put(fsName, n); - root.insert(n, 0); - } - return n; - } - /* else - The path is somewhere down in the POI filesystem's - * hierarchy. We need the tree node of this path's parent - * and attach our new node to it. */ - final String name = path.getComponent(path.length() - 1); - final POIFSDocumentPath parentPath = path.getParent(); - final MutableTreeNode parentNode = - getNode(parentPath, fsName, root); - n = new DefaultMutableTreeNode(name); - pathToNode.put(path, n); - parentNode.insert(n, 0); - return n; - } -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/Util.java b/src/examples/src/org/apache/poi/poifs/poibrowser/Util.java deleted file mode 100644 index 6f5bc6f424..0000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/Util.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.*; -import javax.swing.*; - -/** - *

      Contains various (well, just one at the moment) static utility - * methods.

      - * - * @author Rainer Klute <klute@rainer-klute.de> - */ -public class Util { - - /** - *

      Makes a Swing component inverted by swapping its foreground - * and background colors. Hint: Depending on your needs it might - * also be a good idea to call c.setOpaque(true).

      - */ - public static void invert(JComponent c) { - Color invBackground = c.getForeground(); - Color invForeground = c.getBackground(); - c.setBackground(invBackground); - c.setForeground(invForeground); - } -} - diff --git a/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java b/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java deleted file mode 100644 index 6eb493ca92..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java +++ /dev/null @@ -1,1046 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.ss.examples; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.URL; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.IOUtils; - - -/** - * Demonstrates how to add an image to a worksheet and set that images size - * to a specific number of millimetres irrespective of the width of the columns - * or height of the rows. Overridden methods are provided so that the location - * of the image - the cells row and column coordinates that define the top - * left hand corners of the image - can be identified either in the familiar - * Excel manner - A1 for instance - or using POI's methodology of a column and - * row index where 0, 0 would indicate cell A1. - * - * The best way to make use of these techniques is to delay adding the image to - * the sheet until all other work has been completed. That way, the sizes of - * all rows and columns will have been adjusted - assuming that step was - * necessary. Even though the anchors type is set to prevent the image moving - * or re-sizing, this setting does not have any effect until the sheet is being - * viewed using the Excel application. - * - * The key to the process is the ClientAnchor class. It defines methods that allow - * us to define the location of an image by specifying the following; - * - * * How far - in terms of coordinate positions - the image should be inset - * from the left hand border of a cell. - * * How far - in terms of coordinate positions - the image should be inset - * from the from the top of the cell. - * * How far - in terms of coordinate positions - the right hand edge of - * the image should protrude into a cell (measured from the cells left hand - * edge to the images right hand edge). - * * How far - in terms of coordinate positions - the bottom edge of the - * image should protrude into a row (measured from the cells top edge to - * the images bottom edge). - * * The index of the column that contains the cell whose top left hand - * corner should be aligned with the top left hand corner of the image. - * * The index of the row that contains the cell whose top left hand corner - * should be aligned with the images top left hand corner. - * * The index of the column that contains the cell whose top left hand - * corner should be aligned with the images bottom right hand corner - * * The index number of the row that contains the cell whose top left - * hand corner should be aligned with the images bottom right hand corner. - * - * It can be used to add an image into cell A1, for example, in the following - * manner; - * - * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); - * - * anchor.setDx1(0); - * anchor.setDy1(0); - * anchor.setDx2(0); - * anchor.setDy2(0); - * anchor.setCol1(0); - * anchor.setRow1(0); - * anchor.setCol2(1); - * anchor.setRow2(1); - * - * Taken together, the first four methods define the locations of the top left - * and bottom right hand corners of the image if you imagine that the image is - * represented by a simple rectangle. The setDx1() and setDy1() methods locate - * the top left hand corner of the image while setDx2() and and Dy2() locate the - * bottom right hand corner of the image. An individual image can be inserted - * into a single cell or is can lie across many cells and the latter four methods - * are used to define just where the image should be positioned. They do this by - * again by identifying where the top left and bottom right hand corners of the - * image should be located but this time in terms of the indexes of the cells - * in which those corners should be located. The setCol1() and setRow1() methods - * together identify the cell that should contain the top left hand corner of - * the image while setCol2() and setRow2() do the same for the images bottom - * right hand corner. - * - * Knowing that, it is possible to look again at the example above and to see - * that the top left hand corner of the image will be located in cell A1 (0, 0) - * and it will be aligned with the very top left hand corner of the cell. Likewise, - * the bottom right hand corner of the image will be located in cell B2 (1, 1) and - * it will again be aligned with the top left hand corner of the cell. This has the - * effect of making the image seem to occupy the whole of cell A1. Interestingly, it - * also has an effect on the images resizing behaviour because testing has - * demonstrated that if the image is wholly contained within one cell and is not - * 'attached' for want of a better word, to a neighbouring cell, then that image - * will not increase in size in response to the user dragging the column wider - * or the cell higher. - * - * The following example demonstrates a slightly different way to insert an - * image into cell A1 and to ensure that it occupies the whole of the cell. This - * is accomplished by specifying the the images bottom right hand corner should be - * aligned with the bottom right hand corner of the cell. It is also a case - * where the image will not increase in size if the user increases the size of - * the enclosing cell - irrespective of the anchors type - but it will reduce in - * size if the cell is made smaller. - * - * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); - * - * anchor.setDx1(0); - * anchor.setDy1(0); - * anchor.setDx2(1023); - * anchor.setDy2(255); - * anchor.setCol1(0); - * anchor.setRow1(0); - * anchor.setCol2(0); - * anchor.setRow2(0); - * - * Note that the final four method calls all pass the same value and seem to - * indicate that the images top left hand corner is aligned with the top left - * hand corner of cell A1 and that it's bottom right hand corner is also - * aligned with the top left hand corner of cell A1. Yet, running this code - * would see the image fully occupying cell A1. That is the result of the - * values passed to parameters three and four; these I have referred to as - * determining the images coordinates within the cell. They indicate that the - * image should occupy - in order - the full width of the column and the full - * height of the row. - * - * The co-ordinate values shown are the maxima; and they are independent of - * row height/column width and of the font used. Passing 255 will always result - * in the image occupying the full height of the row and passing 1023 will - * always result in the image occupying the full width of the column. They help - * in situations where an image is larger than a column/row and must overlap - * into the next column/row. Using them does mean, however, that it is often - * necessary to perform conversions between Excels characters units, points, - * pixels and millimetres in order to establish how many rows/columns an image - * should occupy and just what the various insets ought to be. - * - * Note that the setDx1(int) and setDy1(int) methods of the ClientAchor class - * are not made use of in the code that follows. It would be fairly trivial - * however to extend this example further and provide methods that would centre - * an image within a cell or allow the user to specify that a plain border a - * fixed number of millimetres wide should wrap around the image. Those first - * two parameters would make this sort of functionality perfectly possible. - * - * Owing to the various conversions used, the actual size of the image may vary - * from that required; testing has so far found this to be in the region of - * plus or minus two millimetres. Most likely by modifying the way the - * calculations are performed - possibly using double(s) throughout and - * rounding the values at the correct point - it is likely that these errors - * could be reduced or removed. - * - * A note concerning Excels image resizing behaviour. The ClientAnchor - * class contains a method called setAnchorType(int) which can be used to - * determine how Excel will resize an image in response to the user increasing - * or decreasing the dimensions of the cell containing the image. There are - * three values that can be passed to this method; 0 = To move and size the - * image with the cell, 2 = To move but don't size the image with the cell, - * 3 = To prevent the image from moving or being resized along with the cell. If - * an image is inserted using this class and placed into a single cell then if - * the setAnchorType(int) method is called and a value of either 0 or 2 passed - * to it, the resultant resizing behaviour may be a surprise. The image will not - * grow in size of the column is made wider or the row higher but it will shrink - * if the columns width or rows height are reduced. - * - * @author Mark Beardsley [msb at apache.org] and Mark Southern [southern at scripps.edu] - * @version 1.00 5th August 2009. - * 2.00 26th February 2010. - * Ported to make use of the the SS usermodel classes. - * Ability to reuse the Drawing Patriarch so that multiple images - * can be inserted without unintentionally erasing earlier images. - * Check on image type added; i.e. jpg, jpeg or png. - * The String used to contain the files name is now converted - * into a URL. - * 2.10 17th May 2012 - * Corrected gross error that occurred when using the code with - * XSSF or SXSSF workbooks. In short, the code did not correctly - * calculate the size of the image(s) owing to the use of EMUs - * within the OOXML file format. That problem has largely been - * corrected although it should be mentioned that images are not - * sized with the same level of accuracy. Discrepancies of up to - * 2mm have been noted in testing. Further investigation will - * continue to rectify this issue. - */ -public class AddDimensionedImage { - - // Four constants that determine how - and indeed whether - the rows - // and columns an image may overlie should be expanded to accomodate that - // image. - // Passing EXPAND_ROW will result in the height of a row being increased - // to accomodate the image if it is not already larger. The image will - // be layed across one or more columns. - // Passing EXPAND_COLUMN will result in the width of the column being - // increased to accomodate the image if it is not already larger. The image - // will be layed across one or many rows. - // Passing EXPAND_ROW_AND_COLUMN will result in the height of the row - // bing increased along with the width of the column to accomdate the - // image if either is not already larger. - // Passing OVERLAY_ROW_AND_COLUMN will result in the image being layed - // over one or more rows and columns. No row or column will be resized, - // instead, code will determine how many rows and columns the image should - // overlie. - public static final int EXPAND_ROW = 1; - public static final int EXPAND_COLUMN = 2; - public static final int EXPAND_ROW_AND_COLUMN = 3; - public static final int OVERLAY_ROW_AND_COLUMN = 7; - - // Modified to support EMU - English Metric Units - used within the OOXML - // workbooks, this multoplier is used to convert between measurements in - // millimetres and in EMUs - private static final int EMU_PER_MM = 36000; - - /** - * Add an image to a worksheet. - * - * @param cellNumber A String that contains the location of the cell whose - * top left hand corner should be aligned with the top - * left hand corner of the image; for example "A1", "A2" - * etc. This is to support the familiar Excel syntax. - * Whilst images are are not actually inserted into cells - * this provides a convenient method of indicating where - * the image should be positioned on the sheet. - * @param sheet A reference to the sheet that contains the cell referenced - * above. - * @param drawing An instance of the DrawingPatriarch class. This is now - * passed into the method where it was, previously, recovered - * from the sheet in order to allow multiple pictures be - * inserted. If the patriarch was not 'cached in this manner - * each time it was created any previously positioned images - * would be simply over-written. - * @param imageFile An instance of the URL class that encapsulates the name - * of and path to the image that is to be 'inserted into' - * the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres. - * @param resizeBehaviour A primitive int whose value will determine how - * the code should react if the image is larger than - * the cell referenced by the cellNumber parameter. - * Four constants are provided to determine what - * should happen; - * AddDimensionedImage.EXPAND_ROW - * AddDimensionedImage.EXPAND_COLUMN - * AddDimensionedImage.EXPAND_ROW_AND_COLUMN - * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN - * @throws java.io.FileNotFoundException If the file containing the image - * cannot be located. - * @throws java.io.IOException If a problem occurs whilst reading the file - * of image data. - * @throws java.lang.IllegalArgumentException If an invalid value is passed - * to the resizeBehaviour - * parameter. - */ - public void addImageToSheet(String cellNumber, Sheet sheet, Drawing drawing, - URL imageFile, double reqImageWidthMM, double reqImageHeightMM, - int resizeBehaviour) throws IOException, IllegalArgumentException { - // Convert the String into column and row indices then chain the - // call to the overridden addImageToSheet() method. - CellReference cellRef = new CellReference(cellNumber); - this.addImageToSheet(cellRef.getCol(), cellRef.getRow(), sheet, drawing, - imageFile, reqImageWidthMM, reqImageHeightMM,resizeBehaviour); - } - - /** - * Add an image to a worksheet. - * - * @param colNumber A primitive int that contains the index number of a - * column on the worksheet; POI column indices are zero - * based. Together with the rowNumber parameter's value, - * this parameter identifies a cell on the worksheet. The - * images top left hand corner will be aligned with the - * top left hand corner of this cell. - * @param rowNumber A primitive int that contains the index number of a row - * on the worksheet; POI row indices are zero based. - * Together with the rowNumber parameter's value, this - * parameter identifies a cell on the worksheet. The - * images top left hand corner will be aligned with the - * top left hand corner of this cell. - * @param sheet A reference to the sheet that contains the cell identified - * by the two parameters above. - * @param drawing An instance of the DrawingPatriarch class. This is now - * passed into the method where it was, previously, recovered - * from the sheet in order to allow multiple pictures be - * inserted. If the patriarch was not 'cached in this manner - * each time it was created any previously positioned images - * would be simply over-written. - * @param imageFile An instance of the URL class that encapsulates the name - * of and path to the image that is to be 'inserted into' - * the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres. - * @param resizeBehaviour A primitive int whose value will determine how - * the code should react if the image is larger than - * the cell referenced by the colNumber and - * rowNumber parameters. Four constants are provided - * to determine what should happen; - * AddDimensionedImage.EXPAND_ROW - * AddDimensionedImage.EXPAND_COLUMN - * AddDimensionedImage.EXPAND_ROW_AND_COLUMN - * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN - * @throws java.io.FileNotFoundException If the file containing the image - * cannot be located. - * @throws java.io.IOException If a problem occurs whilst reading the file - * of image data. - * @throws java.lang.IllegalArgumentException If an invalid value is passed - * to the resizeBehaviour - * parameter or if the extension - * of the image file indicates that - * it is of a type that cannot - * currently be added to the worksheet. - */ - public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing drawing, - URL imageFile, double reqImageWidthMM, double reqImageHeightMM, - int resizeBehaviour) throws IOException, - IllegalArgumentException { - ClientAnchor anchor = null; - ClientAnchorDetail rowClientAnchorDetail = null; - ClientAnchorDetail colClientAnchorDetail = null; - int imageType = 0; - - // Validate the resizeBehaviour parameter. - if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) && - (resizeBehaviour != AddDimensionedImage.EXPAND_ROW) && - (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN) && - (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) { - throw new IllegalArgumentException("Invalid value passed to the " + - "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()"); - } - - // Call methods to calculate how the image and sheet should be - // manipulated to accomodate the image; columns and then rows. - colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, - reqImageWidthMM, resizeBehaviour); - rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, - reqImageHeightMM, resizeBehaviour); - - // Having determined if and how to resize the rows, columns and/or the - // image, create the ClientAnchor object to position the image on - // the worksheet. Note how the two ClientAnchorDetail records are - // interrogated to recover the row/column co-ordinates and any insets. - // The first two parameters are not used currently but could be if the - // need arose to extend the functionality of this code by adding the - // ability to specify that a clear 'border' be placed around the image. - anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); - - anchor.setDx1(0); - anchor.setDy1(0); - anchor.setDx2(colClientAnchorDetail.getInset()); - anchor.setDy2(rowClientAnchorDetail.getInset()); - anchor.setCol1(colClientAnchorDetail.getFromIndex()); - anchor.setRow1(rowClientAnchorDetail.getFromIndex()); - anchor.setCol2(colClientAnchorDetail.getToIndex()); - anchor.setRow2(rowClientAnchorDetail.getToIndex()); - - // For now, set the anchor type to do not move or resize the - // image as the size of the row/column is adjusted. This could easilly - // become another parameter passed to the method. Please read the note - // above regarding the behaviour of image resizing. - anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE); - - // Now, add the picture to the workbook. Note that unlike the similar - // method in the HSSF Examples section, the image type is checked. First, - // the image files location is identified by interrogating the URL passed - // to the method, the images type is identified before it is added to the - // sheet. - String sURL = imageFile.toString().toLowerCase(); - if( sURL.endsWith(".png") ) { - imageType = Workbook.PICTURE_TYPE_PNG; - } - else if( sURL.endsWith("jpg") || sURL.endsWith(".jpeg") ) { - imageType = Workbook.PICTURE_TYPE_JPEG; - } - else { - throw new IllegalArgumentException("Invalid Image file : " + - sURL); - } - int index = sheet.getWorkbook().addPicture( - IOUtils.toByteArray(imageFile.openStream()), imageType); - drawing.createPicture(anchor, index); - } - - /** - * Determines whether the sheets columns should be re-sized to accomodate - * the image, adjusts the columns width if necessary and creates then - * returns a ClientAnchorDetail object that facilitates construction of - * an ClientAnchor that will fix the image on the sheet and establish - * it's size. - * - * @param sheet A reference to the sheet that will 'contain' the image. - * @param colNumber A primtive int that contains the index number of a - * column on the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres - * @param resizeBehaviour A primitive int whose value will indicate how the - * width of the column should be adjusted if the - * required width of the image is greater than the - * width of the column. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the column containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number column containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the right hand - * edge of the image can protrude into the next column - expressed - * as a specific number of coordinate positions. - */ - private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber, - double reqImageWidthMM, int resizeBehaviour) { - - double colWidthMM = 0.0D; - double colCoordinatesPerMM = 0.0D; - int pictureWidthCoordinates = 0; - ClientAnchorDetail colClientAnchorDetail = null; - - // Get the colum's width in millimetres - colWidthMM = ConvertImageUnits.widthUnits2Millimetres( - (short)sheet.getColumnWidth(colNumber)); - - // Check that the column's width will accomodate the image at the - // required dimension. If the width of the column is LESS than the - // required width of the image, decide how the application should - // respond - resize the column or overlay the image across one or more - // columns. - if(colWidthMM < reqImageWidthMM) { - - // Should the column's width simply be expanded? - if((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { - // Set the width of the column by converting the required image - // width from millimetres into Excel's column width units. - sheet.setColumnWidth(colNumber, - ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM)); - // To make the image occupy the full width of the column, convert - // the required width of the image into co-ordinates. This value - // will become the inset for the ClientAnchorDetail class that - // is then instantiated. - if(sheet instanceof HSSFSheet) { - colWidthMM = reqImageWidthMM; - colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); - - } - else { - pictureWidthCoordinates = (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM; - } - colClientAnchorDetail = new ClientAnchorDetail(colNumber, - colNumber, pictureWidthCoordinates); - } - // If the user has chosen to overlay both rows and columns or just - // to expand ONLY the size of the rows, then calculate how to lay - // the image out across one or more columns. - else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) { - colClientAnchorDetail = this.calculateColumnLocation(sheet, - colNumber, reqImageWidthMM); - } - } - // If the column is wider than the image. - else { - if(sheet instanceof HSSFSheet) { - // Mow many co-ordinate positions are there per millimetre? - colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - // Given the width of the image, what should be it's co-ordinate? - pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); - } - else { - pictureWidthCoordinates = (int)reqImageWidthMM * - AddDimensionedImage.EMU_PER_MM; - } - colClientAnchorDetail = new ClientAnchorDetail(colNumber, - colNumber, pictureWidthCoordinates); - } - return(colClientAnchorDetail); - } - - /** - * Determines whether the sheets row should be re-sized to accomodate - * the image, adjusts the rows height if necessary and creates then - * returns a ClientAnchorDetail object that facilitates construction of - * a ClientAnchor that will fix the image on the sheet and establish - * it's size. - * - * @param sheet A reference to the sheet that will 'contain' the image. - * @param rowNumber A primitive int that contains the index number of a - * row on the sheet. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres - * @param resizeBehaviour A primitive int whose value will indicate how the - * height of the row should be adjusted if the - * required height of the image is greater than the - * height of the row. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the row containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number of the row containing the cell whose - * top left hand corner also defines the bottom right hand - * corner of the image and an inset that determines how far the - * bottom edge of the image can protrude into the next (lower) - * row - expressed as a specific number of coordinate positions. - */ - private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber, - double reqImageHeightMM, int resizeBehaviour) { - Row row = null; - double rowHeightMM = 0.0D; - double rowCoordinatesPerMM = 0.0D; - int pictureHeightCoordinates = 0; - ClientAnchorDetail rowClientAnchorDetail = null; - - // Get the row and it's height - row = sheet.getRow(rowNumber); - if(row == null) { - // Create row if it does not exist. - row = sheet.createRow(rowNumber); - } - - // Get the row's height in millimetres - rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE; - - // Check that the row's height will accomodate the image at the required - // dimensions. If the height of the row is LESS than the required height - // of the image, decide how the application should respond - resize the - // row or overlay the image across a series of rows. - if(rowHeightMM < reqImageHeightMM) { - if((resizeBehaviour == AddDimensionedImage.EXPAND_ROW) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { - row.setHeightInPoints((float)(reqImageHeightMM * - ConvertImageUnits.POINTS_PER_MILLIMETRE)); - if(sheet instanceof HSSFSheet) { - rowHeightMM = reqImageHeightMM; - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - pictureHeightCoordinates = (int)(reqImageHeightMM * - rowCoordinatesPerMM); - } - else { - pictureHeightCoordinates = (int)(reqImageHeightMM * - AddDimensionedImage.EMU_PER_MM); - } - rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, - rowNumber, pictureHeightCoordinates); - } - // If the user has chosen to overlay both rows and columns or just - // to expand ONLY the size of the columns, then calculate how to lay - // the image out ver one or more rows. - else if((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) { - rowClientAnchorDetail = this.calculateRowLocation(sheet, - rowNumber, reqImageHeightMM); - } - } - // Else, if the image is smaller than the space available - else { - if(sheet instanceof HSSFSheet) { - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); - } - else { - pictureHeightCoordinates = (int)(reqImageHeightMM * - AddDimensionedImage.EMU_PER_MM); - } - rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, - rowNumber, pictureHeightCoordinates); - } - return(rowClientAnchorDetail); - } - - /** - * If the image is to overlie more than one column, calculations need to be - * performed to determine how many columns and whether the image will - * overlie just a part of one column in order to be presented at the - * required size. - * - * @param sheet The sheet that will 'contain' the image. - * @param startingColumn A primitive int whose value is the index of the - * column that contains the cell whose top left hand - * corner should be aligned with the top left hand - * corner of the image. - * @param reqImageWidthMM A primitive double whose value will indicate the - * required width of the image in millimetres. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the column containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number column containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the right hand - * edge of the image can protrude into the next column - expressed - * as a specific number of coordinate positions. - */ - private ClientAnchorDetail calculateColumnLocation(Sheet sheet, - int startingColumn, - double reqImageWidthMM) { - ClientAnchorDetail anchorDetail = null; - double totalWidthMM = 0.0D; - double colWidthMM = 0.0D; - double overlapMM = 0.0D; - double coordinatePositionsPerMM = 0.0D; - int toColumn = startingColumn; - int inset = 0; - - // Calculate how many columns the image will have to - // span in order to be presented at the required size. - while(totalWidthMM < reqImageWidthMM) { - colWidthMM = ConvertImageUnits.widthUnits2Millimetres( - (short)(sheet.getColumnWidth(toColumn))); - // Note use of the cell border width constant. Testing with an image - // declared to fit exactly into one column demonstrated that it's - // width was greater than the width of the column the POI returned. - // Further, this difference was a constant value that I am assuming - // related to the cell's borders. Either way, that difference needs - // to be allowed for in this calculation. - totalWidthMM += (colWidthMM + ConvertImageUnits.CELL_BORDER_WIDTH_MILLIMETRES); - toColumn++; - } - // De-crement by one the last column value. - toColumn--; - // Highly unlikely that this will be true but, if the width of a series - // of columns is exactly equal to the required width of the image, then - // simply build a ClientAnchorDetail object with an inset equal to the - // total number of co-ordinate positions available in a column, a - // from column co-ordinate (top left hand corner) equal to the value - // of the startingColumn parameter and a to column co-ordinate equal - // to the toColumn variable. - // - // Convert both values to ints to perform the test. - if((int)totalWidthMM == (int)reqImageWidthMM) { - // A problem could occur if the image is sized to fit into one or - // more columns. If that occurs, the value in the toColumn variable - // will be in error. To overcome this, there are two options, to - // ibcrement the toColumn variable's value by one or to pass the - // total number of co-ordinate positions to the third paramater - // of the ClientAnchorDetail constructor. For no sepcific reason, - // the latter option is used below. - if(sheet instanceof HSSFSheet) { - anchorDetail = new ClientAnchorDetail(startingColumn, - toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS); - } - else { - anchorDetail = new ClientAnchorDetail(startingColumn, - toColumn, (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM); - } - } - // In this case, the image will overlap part of another column and it is - // necessary to calculate just how much - this will become the inset - // for the ClientAnchorDetail object. - else { - // Firstly, claculate how much of the image should overlap into - // the next column. - overlapMM = reqImageWidthMM - (totalWidthMM - colWidthMM); - - // When the required size is very close indded to the column size, - // the calcaulation above can produce a negative value. To prevent - // problems occuring in later caculations, this is simply removed - // be setting the overlapMM value to zero. - if(overlapMM < 0) { - overlapMM = 0.0D; - } - - if(sheet instanceof HSSFSheet) { - // Next, from the columns width, calculate how many co-ordinate - // positons there are per millimetre - coordinatePositionsPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - // From this figure, determine how many co-ordinat positions to - // inset the left hand or bottom edge of the image. - inset = (int)(coordinatePositionsPerMM * overlapMM); - } - else { - inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM; - } - - // Now create the ClientAnchorDetail object, setting the from and to - // columns and the inset. - anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, inset); - } - return(anchorDetail); - } - - /** - * If the image is to overlie more than one rows, calculations need to be - * performed to determine how many rows and whether the image will - * overlie just a part of one row in order to be presented at the - * required size. - * - * @param sheet The sheet that will 'contain' the image. - * @param startingRow A primitive int whose value is the index of the row - * that contains the cell whose top left hand corner - * should be aligned with the top left hand corner of - * the image. - * @param reqImageHeightMM A primitive double whose value will indicate the - * required height of the image in millimetres. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the row containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number of the row containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the bottom edge - * can protrude into the next (lower) row - expressed as a specific - * number of co-ordinate positions. - */ - private ClientAnchorDetail calculateRowLocation(Sheet sheet, - int startingRow, double reqImageHeightMM) { - ClientAnchorDetail clientAnchorDetail = null; - Row row = null; - double rowHeightMM = 0.0D; - double totalRowHeightMM = 0.0D; - double overlapMM = 0.0D; - double rowCoordinatesPerMM = 0.0D; - int toRow = startingRow; - int inset = 0; - - // Step through the rows in the sheet and accumulate a total of their - // heights. - while(totalRowHeightMM < reqImageHeightMM) { - row = sheet.getRow(toRow); - // Note, if the row does not already exist on the sheet then create - // it here. - if(row == null) { - row = sheet.createRow(toRow); - } - // Get the row's height in millimetres and add to the running total. - rowHeightMM = row.getHeightInPoints() / - ConvertImageUnits.POINTS_PER_MILLIMETRE; - totalRowHeightMM += rowHeightMM; - toRow++; - } - // Owing to the way the loop above works, the rowNumber will have been - // incremented one row too far. Undo that here. - toRow--; - // Check to see whether the image should occupy an exact number of - // rows. If so, build the ClientAnchorDetail record to point - // to those rows and with an inset of the total number of co-ordinate - // position in the row. - // - // To overcome problems that can occur with comparing double values for - // equality, cast both to int(s) to truncate the value; VERY crude and - // I do not really like it!! - if((int)totalRowHeightMM == (int)reqImageHeightMM) { - if(sheet instanceof HSSFSheet) { - clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, - ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS); - } - else { - clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, - (int)reqImageHeightMM * AddDimensionedImage.EMU_PER_MM); - } - } - else { - // Calculate how far the image will project into the next row. Note - // that the height of the last row assessed is subtracted from the - // total height of all rows assessed so far. - overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM); - - // To prevent an exception being thrown when the required width of - // the image is very close indeed to the column size. - if(overlapMM < 0) { - overlapMM = 0.0D; - } - - if(sheet instanceof HSSFSheet) { - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - inset = (int)(overlapMM * rowCoordinatesPerMM); - } - else { - inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM; - } - clientAnchorDetail = new ClientAnchorDetail(startingRow, - toRow, inset); - } - return(clientAnchorDetail); - } - - /** - * The main entry point to the program. It contains code that demonstrates - * one way to use the program. - * - * Note, the code is not restricted to use on new workbooks only. If an - * image is to be inserted into an existing workbook. just open that - * workbook, gat a reference to a sheet and pass that; - * - * AddDimensionedImage addImage = new AddDimensionedImage(); - * - * File file = new File("....... Existing Workbook ......."); - * FileInputStream fis = new FileInputStream(file); - * Workbook workbook = new HSSFWorkbook(fis); - * HSSFSheet sheet = workbook.getSheetAt(0); - * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20, - * AddDimensionedImage.EXPAND.ROW); - * - * @param args the command line arguments - */ - public static void main(String[] args) { - String imageFile = null; - String outputFile = null; - FileOutputStream fos = null; - Workbook workbook = null; - Sheet sheet = null; - try { - if(args.length < 2){ - System.err.println("Usage: AddDimensionedImage imageFile outputFile"); - return; - } - workbook = new HSSFWorkbook(); // OR XSSFWorkbook - sheet = workbook.createSheet("Picture Test"); - imageFile = args[0]; - outputFile = args[1]; - new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(), - new File(imageFile).toURI().toURL(), 100, 40, - AddDimensionedImage.EXPAND_ROW_AND_COLUMN); - fos = new FileOutputStream(outputFile); - workbook.write(fos); - } - catch(FileNotFoundException fnfEx) { - System.out.println("Caught an: " + fnfEx.getClass().getName()); - System.out.println("Message: " + fnfEx.getMessage()); - System.out.println("Stacktrace follows..........."); - fnfEx.printStackTrace(System.out); - } - catch(IOException ioEx) { - System.out.println("Caught an: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follows..........."); - ioEx.printStackTrace(System.out); - } - finally { - if(fos != null) { - try { - fos.close(); - fos = null; - } - catch(IOException ioEx) { - // I G N O R E - } - } - } - } - - /** - * The HSSFClientAnchor class accepts eight arguments. In order, these are; - * - * * How far the left hand edge of the image is inset from the left hand - * edge of the cell - * * How far the top edge of the image is inset from the top of the cell - * * How far the right hand edge of the image is inset from the left - * hand edge of the cell - * * How far the bottom edge of the image is inset from the top of the - * cell. - * * Together, arguments five and six determine the column and row - * coordinates of the cell whose top left hand corner will be aligned - * with the images top left hand corner. - * * Together, arguments seven and eight determine the column and row - * coordinates of the cell whose top left hand corner will be aligned - * with the images bottom right hand corner. - * - * An instance of the ClientAnchorDetail class provides three of the eight - * parameters, one of the coordinates for the images top left hand corner, - * one of the coordinates for the images bottom right hand corner and - * either how far the image should be inset from the top or the left hand - * edge of the cell. - * - * @author Mark Beardsley [msb at apache.org] - * @version 1.00 5th August 2009. - */ - public class ClientAnchorDetail { - - public int fromIndex = 0; - public int toIndex = 0; - public int inset = 0; - - /** - * Create a new instance of the ClientAnchorDetail class using the - * following parameters. - * - * @param fromIndex A primitive int that contains one of the - * coordinates (row or column index) for the top left - * hand corner of the image. - * @param toIndex A primitive int that contains one of the - * coordinates (row or column index) for the bottom - * right hand corner of the image. - * @param inset A primitive int that contains a value which indicates - * how far the image should be inset from the top or the - * left hand edge of a cell. - */ - public ClientAnchorDetail(int fromIndex, int toIndex, int inset) { - this.fromIndex = fromIndex; - this.toIndex = toIndex; - this.inset = inset; - } - - /** - * Get one of the number of the column or row that contains the cell - * whose top left hand corner will be aligned with the top left hand - * corner of the image. - * - * @return The value - row or column index - for one of the coordinates - * of the top left hand corner of the image. - */ - public int getFromIndex() { - return(this.fromIndex); - } - - /** - * Get one of the number of the column or row that contains the cell - * whose top left hand corner will be aligned with the bottom right hand - * corner of the image. - * - * @return The value - row or column index - for one of the coordinates - * of the bottom right hand corner of the image. - */ - public int getToIndex() { - return(this.toIndex); - } - - /** - * Get the images offset from the edge of a cell. - * - * @return How far either the right hand or bottom edge of the image is - * inset from the left hand or top edge of a cell. - */ - public int getInset() { - return(this.inset); - } - } - - /** - * Utility methods used to convert Excels character based column and row - * size measurements into pixels and/or millimetres. The class also contains - * various constants that are required in other calculations. - * - * @author xio[darjino@hotmail.com] - * @version 1.01 30th July 2009. - * Added by Mark Beardsley [msb at apache.org]. - * Additional constants. - * widthUnits2Millimetres() and millimetres2Units() methods. - */ - public static class ConvertImageUnits { - - // Each cell conatins a fixed number of co-ordinate points; this number - // does not vary with row height or column width or with font. These two - // constants are defined below. - public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB - public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB - // The resoultion of an image can be expressed as a specific number - // of pixels per inch. Displays and printers differ but 96 pixels per - // inch is an acceptable standard to beging with. - public static final int PIXELS_PER_INCH = 96; // MB - // Cnstants that defines how many pixels and points there are in a - // millimetre. These values are required for the conversion algorithm. - public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB - public static final double POINTS_PER_MILLIMETRE = 2.83; // MB - // The column width returned by HSSF and the width of a picture when - // positioned to exactly cover one cell are different by almost exactly - // 2mm - give or take rounding errors. This constant allows that - // additional amount to be accounted for when calculating how many - // celles the image ought to overlie. - public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB - public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; - public static final int UNIT_OFFSET_LENGTH = 7; - public static final int[] UNIT_OFFSET_MAP = new int[] - { 0, 36, 73, 109, 146, 182, 219 }; - - /** - * pixel units to excel width units(units of 1/256th of a character width) - * @param pxs - * @return - */ - public static short pixel2WidthUnits(int pxs) { - short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * - (pxs / UNIT_OFFSET_LENGTH)); - widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)]; - return widthUnits; - } - - /** - * excel width units(units of 1/256th of a character width) to pixel - * units. - * - * @param widthUnits - * @return - */ - public static int widthUnits2Pixel(short widthUnits) { - int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) - * UNIT_OFFSET_LENGTH; - int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; - pixels += Math.round(offsetWidthUnits / - ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); - return pixels; - } - - /** - * Convert Excels width units into millimetres. - * - * @param widthUnits The width of the column or the height of the - * row in Excels units. - * @return A primitive double that contains the columns width or rows - * height in millimetres. - */ - public static double widthUnits2Millimetres(short widthUnits) { - return(ConvertImageUnits.widthUnits2Pixel(widthUnits) / - ConvertImageUnits.PIXELS_PER_MILLIMETRES); - } - - /** - * Convert into millimetres Excels width units.. - * - * @param millimetres A primitive double that contains the columns - * width or rows height in millimetres. - * @return A primitive int that contains the columns width or rows - * height in Excels units. - */ - public static int millimetres2WidthUnits(double millimetres) { - return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres * - ConvertImageUnits.PIXELS_PER_MILLIMETRES))); - } - - public static int pointsToPixels(double points) { - return (int) Math.round(points / 72D * PIXELS_PER_INCH); - } - - public static double pointsToMillimeters(double points) { - return points / 72D * 25.4; - } - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/AligningCells.java b/src/examples/src/org/apache/poi/ss/examples/AligningCells.java deleted file mode 100644 index 6571ff9dd9..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/AligningCells.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.*; - -/** - * Shows how various alignment options work. - */ -public class AligningCells { - - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow((short) 2); - row.setHeightInPoints(30); - for (int i = 0; i < 8; i++) { - //column width is set in units of 1/256th of a character width - sheet.setColumnWidth(i, 256 * 15); - } - - createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM); - createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM); - createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER); - createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER); - createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY); - createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP); - createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("ss-example-align.xlsx"); - wb.write(fileOut); - fileOut.close(); - } - - /** - * Creates a cell and aligns it a certain way. - * - * @param wb the workbook - * @param row the row to create the cell in - * @param column the column number to create the cell in - * @param halign the horizontal alignment for the cell. - */ - private static void createCell(Workbook wb, Row row, short column, short halign, short valign) { - CreationHelper ch = wb.getCreationHelper(); - Cell cell = row.createCell(column); - cell.setCellValue(ch.createRichTextString("Align It")); - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setAlignment(halign); - cellStyle.setVerticalAlignment(valign); - cell.setCellStyle(cellStyle); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java b/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java deleted file mode 100644 index 101eceda7b..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java +++ /dev/null @@ -1,325 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.util.Map; -import java.util.HashMap; -import java.util.Calendar; -import java.io.FileOutputStream; -import java.text.SimpleDateFormat; - -/** - * A business plan demo - * Usage: - * BusinessPlan -xls|xlsx - * - * @author Yegor Kozlov - */ -public class BusinessPlan { - - private static SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM"); - - private static final String[] titles = { - "ID", "Project Name", "Owner", "Days", "Start", "End"}; - - //sample data to fill the sheet. - private static final String[][] data = { - {"1.0", "Marketing Research Tactical Plan", "J. Dow", "70", "9-Jul", null, - "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"}, - null, - {"1.1", "Scope Definition Phase", "J. Dow", "10", "9-Jul", null, - "x", "x", null, null, null, null, null, null, null, null, null}, - {"1.1.1", "Define research objectives", "J. Dow", "3", "9-Jul", null, - "x", null, null, null, null, null, null, null, null, null, null}, - {"1.1.2", "Define research requirements", "S. Jones", "7", "10-Jul", null, - "x", "x", null, null, null, null, null, null, null, null, null}, - {"1.1.3", "Determine in-house resource or hire vendor", "J. Dow", "2", "15-Jul", null, - "x", "x", null, null, null, null, null, null, null, null, null}, - null, - {"1.2", "Vendor Selection Phase", "J. Dow", "19", "19-Jul", null, - null, "x", "x", "x", "x", null, null, null, null, null, null}, - {"1.2.1", "Define vendor selection criteria", "J. Dow", "3", "19-Jul", null, - null, "x", null, null, null, null, null, null, null, null, null}, - {"1.2.2", "Develop vendor selection questionnaire", "S. Jones, T. Wates", "2", "22-Jul", null, - null, "x", "x", null, null, null, null, null, null, null, null}, - {"1.2.3", "Develop Statement of Work", "S. Jones", "4", "26-Jul", null, - null, null, "x", "x", null, null, null, null, null, null, null}, - {"1.2.4", "Evaluate proposal", "J. Dow, S. Jones", "4", "2-Aug", null, - null, null, null, "x", "x", null, null, null, null, null, null}, - {"1.2.5", "Select vendor", "J. Dow", "1", "6-Aug", null, - null, null, null, null, "x", null, null, null, null, null, null}, - null, - {"1.3", "Research Phase", "G. Lee", "47", "9-Aug", null, - null, null, null, null, "x", "x", "x", "x", "x", "x", "x"}, - {"1.3.1", "Develop market research information needs questionnaire", "G. Lee", "2", "9-Aug", null, - null, null, null, null, "x", null, null, null, null, null, null}, - {"1.3.2", "Interview marketing group for market research needs", "G. Lee", "2", "11-Aug", null, - null, null, null, null, "x", "x", null, null, null, null, null}, - {"1.3.3", "Document information needs", "G. Lee, S. Jones", "1", "13-Aug", null, - null, null, null, null, null, "x", null, null, null, null, null}, - }; - - public static void main(String[] args) throws Exception { - Workbook wb; - - if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); - else wb = new XSSFWorkbook(); - - Map styles = createStyles(wb); - - Sheet sheet = wb.createSheet("Business Plan"); - - //turn off gridlines - sheet.setDisplayGridlines(false); - sheet.setPrintGridlines(false); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - PrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setLandscape(true); - - //the following three statements are required only for HSSF - sheet.setAutobreaks(true); - printSetup.setFitHeight((short)1); - printSetup.setFitWidth((short)1); - - //the header row: centered text in 48pt font - Row headerRow = sheet.createRow(0); - headerRow.setHeightInPoints(12.75f); - for (int i = 0; i < titles.length; i++) { - Cell cell = headerRow.createCell(i); - cell.setCellValue(titles[i]); - cell.setCellStyle(styles.get("header")); - } - //columns for 11 weeks starting from 9-Jul - Calendar calendar = Calendar.getInstance(); - int year = calendar.get(Calendar.YEAR); - - calendar.setTime(fmt.parse("9-Jul")); - calendar.set(Calendar.YEAR, year); - for (int i = 0; i < 11; i++) { - Cell cell = headerRow.createCell(titles.length + i); - cell.setCellValue(calendar); - cell.setCellStyle(styles.get("header_date")); - calendar.roll(Calendar.WEEK_OF_YEAR, true); - } - //freeze the first row - sheet.createFreezePane(0, 1); - - Row row; - Cell cell; - int rownum = 1; - for (int i = 0; i < data.length; i++, rownum++) { - row = sheet.createRow(rownum); - if(data[i] == null) continue; - - for (int j = 0; j < data[i].length; j++) { - cell = row.createCell(j); - String styleName; - boolean isHeader = i == 0 || data[i-1] == null; - switch(j){ - case 0: - if(isHeader) { - styleName = "cell_b"; - cell.setCellValue(Double.parseDouble(data[i][j])); - } else { - styleName = "cell_normal"; - cell.setCellValue(data[i][j]); - } - break; - case 1: - if(isHeader) { - styleName = i == 0 ? "cell_h" : "cell_bb"; - } else { - styleName = "cell_indented"; - } - cell.setCellValue(data[i][j]); - break; - case 2: - styleName = isHeader ? "cell_b" : "cell_normal"; - cell.setCellValue(data[i][j]); - break; - case 3: - styleName = isHeader ? "cell_b_centered" : "cell_normal_centered"; - cell.setCellValue(Integer.parseInt(data[i][j])); - break; - case 4: { - calendar.setTime(fmt.parse(data[i][j])); - calendar.set(Calendar.YEAR, year); - cell.setCellValue(calendar); - styleName = isHeader ? "cell_b_date" : "cell_normal_date"; - break; - } - case 5: { - int r = rownum + 1; - String fmla = "IF(AND(D"+r+",E"+r+"),E"+r+"+D"+r+",\"\")"; - cell.setCellFormula(fmla); - styleName = isHeader ? "cell_bg" : "cell_g"; - break; - } - default: - styleName = data[i][j] != null ? "cell_blue" : "cell_normal"; - } - - cell.setCellStyle(styles.get(styleName)); - } - } - - //group rows for each phase, row numbers are 0-based - sheet.groupRow(4, 6); - sheet.groupRow(9, 13); - sheet.groupRow(16, 18); - - //set column widths, the width is measured in units of 1/256th of a character width - sheet.setColumnWidth(0, 256*6); - sheet.setColumnWidth(1, 256*33); - sheet.setColumnWidth(2, 256*20); - sheet.setZoom(3, 4); - - - // Write the output to a file - String file = "businessplan.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - } - - /** - * create a library of cell styles - */ - private static Map createStyles(Workbook wb){ - Map styles = new HashMap(); - DataFormat df = wb.createDataFormat(); - - CellStyle style; - Font headerFont = wb.createFont(); - headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setFont(headerFont); - styles.put("header", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setFont(headerFont); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("header_date", style); - - Font font1 = wb.createFont(); - font1.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_LEFT); - style.setFont(font1); - styles.put("cell_b", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setFont(font1); - styles.put("cell_b_centered", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(font1); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("cell_b_date", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(font1); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("cell_g", style); - - Font font2 = wb.createFont(); - font2.setColor(IndexedColors.BLUE.getIndex()); - font2.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_LEFT); - style.setFont(font2); - styles.put("cell_bb", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(font1); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("cell_bg", style); - - Font font3 = wb.createFont(); - font3.setFontHeightInPoints((short)14); - font3.setColor(IndexedColors.DARK_BLUE.getIndex()); - font3.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_LEFT); - style.setFont(font3); - style.setWrapText(true); - styles.put("cell_h", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_LEFT); - style.setWrapText(true); - styles.put("cell_normal", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setWrapText(true); - styles.put("cell_normal_centered", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setWrapText(true); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("cell_normal_date", style); - - style = createBorderedStyle(wb); - style.setAlignment(CellStyle.ALIGN_LEFT); - style.setIndention((short)1); - style.setWrapText(true); - styles.put("cell_indented", style); - - style = createBorderedStyle(wb); - style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - styles.put("cell_blue", style); - - return styles; - } - - private static CellStyle createBorderedStyle(Workbook wb){ - CellStyle style = wb.createCellStyle(); - style.setBorderRight(CellStyle.BORDER_THIN); - style.setRightBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderLeft(CellStyle.BORDER_THIN); - style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderTop(CellStyle.BORDER_THIN); - style.setTopBorderColor(IndexedColors.BLACK.getIndex()); - return style; - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/CalendarDemo.java b/src/examples/src/org/apache/poi/ss/examples/CalendarDemo.java deleted file mode 100644 index bb120861f6..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/CalendarDemo.java +++ /dev/null @@ -1,243 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Map; -import java.util.HashMap; - -/** - * A monthly calendar created using Apache POI. Each month is on a separate sheet. - *
      - * Usage:
      - * CalendarDemo -xls|xlsx 
      - * 
      - * - * @author Yegor Kozlov - */ -public class CalendarDemo { - - private static final String[] days = { - "Sunday", "Monday", "Tuesday", - "Wednesday", "Thursday", "Friday", "Saturday"}; - - private static final String[] months = { - "January", "February", "March","April", "May", "June","July", "August", - "September","October", "November", "December"}; - - public static void main(String[] args) throws Exception { - - Calendar calendar = Calendar.getInstance(); - boolean xlsx = true; - for (int i = 0; i < args.length; i++) { - if(args[i].charAt(0) == '-'){ - xlsx = args[i].equals("-xlsx"); - } else { - calendar.set(Calendar.YEAR, Integer.parseInt(args[i])); - } - } - int year = calendar.get(Calendar.YEAR); - - Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook(); - - Map styles = createStyles(wb); - - for (int month = 0; month < 12; month++) { - calendar.set(Calendar.MONTH, month); - calendar.set(Calendar.DAY_OF_MONTH, 1); - //create a sheet for each month - Sheet sheet = wb.createSheet(months[month]); - - //turn off gridlines - sheet.setDisplayGridlines(false); - sheet.setPrintGridlines(false); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - PrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setLandscape(true); - - //the following three statements are required only for HSSF - sheet.setAutobreaks(true); - printSetup.setFitHeight((short)1); - printSetup.setFitWidth((short)1); - - //the header row: centered text in 48pt font - Row headerRow = sheet.createRow(0); - headerRow.setHeightInPoints(80); - Cell titleCell = headerRow.createCell(0); - titleCell.setCellValue(months[month] + " " + year); - titleCell.setCellStyle(styles.get("title")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1")); - - //header with month titles - Row monthRow = sheet.createRow(1); - for (int i = 0; i < days.length; i++) { - //set column widths, the width is measured in units of 1/256th of a character width - sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide - sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide - sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1)); - Cell monthCell = monthRow.createCell(i*2); - monthCell.setCellValue(days[i]); - monthCell.setCellStyle(styles.get("month")); - } - - int cnt = 1, day=1; - int rownum = 2; - for (int j = 0; j < 6; j++) { - Row row = sheet.createRow(rownum++); - row.setHeightInPoints(100); - for (int i = 0; i < days.length; i++) { - Cell dayCell_1 = row.createCell(i*2); - Cell dayCell_2 = row.createCell(i*2 + 1); - - int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); - if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) { - dayCell_1.setCellValue(day); - calendar.set(Calendar.DAY_OF_MONTH, ++day); - - if(i == 0 || i == days.length-1) { - dayCell_1.setCellStyle(styles.get("weekend_left")); - dayCell_2.setCellStyle(styles.get("weekend_right")); - } else { - dayCell_1.setCellStyle(styles.get("workday_left")); - dayCell_2.setCellStyle(styles.get("workday_right")); - } - } else { - dayCell_1.setCellStyle(styles.get("grey_left")); - dayCell_2.setCellStyle(styles.get("grey_right")); - } - cnt++; - } - if(calendar.get(Calendar.MONTH) > month) break; - } - } - - // Write the output to a file - String file = "calendar.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - } - - /** - * cell styles used for formatting calendar sheets - */ - private static Map createStyles(Workbook wb){ - Map styles = new HashMap(); - - short borderColor = IndexedColors.GREY_50_PERCENT.getIndex(); - - CellStyle style; - Font titleFont = wb.createFont(); - titleFont.setFontHeightInPoints((short)48); - titleFont.setColor(IndexedColors.DARK_BLUE.getIndex()); - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - style.setFont(titleFont); - styles.put("title", style); - - Font monthFont = wb.createFont(); - monthFont.setFontHeightInPoints((short)12); - monthFont.setColor(IndexedColors.WHITE.getIndex()); - monthFont.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setFont(monthFont); - styles.put("month", style); - - Font dayFont = wb.createFont(); - dayFont.setFontHeightInPoints((short)14); - dayFont.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_LEFT); - style.setVerticalAlignment(CellStyle.VERTICAL_TOP); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setBorderLeft(CellStyle.BORDER_THIN); - style.setLeftBorderColor(borderColor); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(borderColor); - style.setFont(dayFont); - styles.put("weekend_left", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_TOP); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setBorderRight(CellStyle.BORDER_THIN); - style.setRightBorderColor(borderColor); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(borderColor); - styles.put("weekend_right", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_LEFT); - style.setVerticalAlignment(CellStyle.VERTICAL_TOP); - style.setBorderLeft(CellStyle.BORDER_THIN); - style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setLeftBorderColor(borderColor); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(borderColor); - style.setFont(dayFont); - styles.put("workday_left", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_TOP); - style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setBorderRight(CellStyle.BORDER_THIN); - style.setRightBorderColor(borderColor); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(borderColor); - styles.put("workday_right", style); - - style = wb.createCellStyle(); - style.setBorderLeft(CellStyle.BORDER_THIN); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(borderColor); - styles.put("grey_left", style); - - style = wb.createCellStyle(); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setBorderRight(CellStyle.BORDER_THIN); - style.setRightBorderColor(borderColor); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(borderColor); - styles.put("grey_right", style); - - return styles; - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/CellStyleDetails.java b/src/examples/src/org/apache/poi/ss/examples/CellStyleDetails.java deleted file mode 100644 index 8dab14fa7a..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/CellStyleDetails.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples; - -import java.io.File; - -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFont; - -/** - * Demonstrates how to read excel styles for cells - */ -public class CellStyleDetails { - public static void main(String[] args) throws Exception { - if(args.length == 0) { - throw new IllegalArgumentException("Filename must be given"); - } - - Workbook wb = WorkbookFactory.create(new File(args[0])); - DataFormatter formatter = new DataFormatter(); - - for(int sn=0; sn - * Based on the code snippets from http://www.contextures.com/xlcondformat03.html - *

      - * - * @author Yegor Kozlov - */ -public class ConditionalFormats { - - public static void main(String[] args) throws IOException { - Workbook wb; - - if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); - else wb = new XSSFWorkbook(); - - sameCell(wb.createSheet("Same Cell")); - multiCell(wb.createSheet("MultiCell")); - errors(wb.createSheet("Errors")); - hideDupplicates(wb.createSheet("Hide Dups")); - formatDuplicates(wb.createSheet("Duplicates")); - inList(wb.createSheet("In List")); - expiry(wb.createSheet("Expiry")); - shadeAlt(wb.createSheet("Shade Alt")); - shadeBands(wb.createSheet("Shade Bands")); - - // Write the output to a file - String file = "cf-poi.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - - } - - /** - * Highlight cells based on their values - */ - static void sameCell(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue(84); - sheet.createRow(1).createCell(0).setCellValue(74); - sheet.createRow(2).createCell(0).setCellValue(50); - sheet.createRow(3).createCell(0).setCellValue(51); - sheet.createRow(4).createCell(0).setCellValue(49); - sheet.createRow(5).createCell(0).setCellValue(41); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Cell Value Is greater than 70 (Blue Fill) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.GT, "70"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.BLUE.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - // Condition 2: Cell Value Is less than 50 (Green Fill) - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.LT, "50"); - PatternFormatting fill2 = rule2.createPatternFormatting(); - fill2.setFillBackgroundColor(IndexedColors.GREEN.index); - fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:A6") - }; - - sheetCF.addConditionalFormatting(regions, rule1, rule2); - - sheet.getRow(0).createCell(2).setCellValue("<== Condition 1: Cell Value Is greater than 70 (Blue Fill)"); - sheet.getRow(4).createCell(2).setCellValue("<== Condition 2: Cell Value Is less than 50 (Green Fill)"); - } - - /** - * Highlight multiple cells based on a formula - */ - static void multiCell(Sheet sheet) { - // header row - Row row0 = sheet.createRow(0); - row0.createCell(0).setCellValue("Units"); - row0.createCell(1).setCellValue("Cost"); - row0.createCell(2).setCellValue("Total"); - - Row row1 = sheet.createRow(1); - row1.createCell(0).setCellValue(71); - row1.createCell(1).setCellValue(29); - row1.createCell(2).setCellValue(2059); - - Row row2 = sheet.createRow(2); - row2.createCell(0).setCellValue(85); - row2.createCell(1).setCellValue(29); - row2.createCell(2).setCellValue(2059); - - Row row3 = sheet.createRow(3); - row3.createCell(0).setCellValue(71); - row3.createCell(1).setCellValue(29); - row3.createCell(2).setCellValue(2059); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =$B2>75 (Blue Fill) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("$A2>75"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.BLUE.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:C4") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(2).createCell(4).setCellValue("<== Condition 1: Formula Is =$B2>75 (Blue Fill)"); - } - - /** - * Use Excel conditional formatting to check for errors, - * and change the font colour to match the cell colour. - * In this example, if formula result is #DIV/0! then it will have white font colour. - */ - static void errors(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue(84); - sheet.createRow(1).createCell(0).setCellValue(0); - sheet.createRow(2).createCell(0).setCellFormula("ROUND(A1/A2,0)"); - sheet.createRow(3).createCell(0).setCellValue(0); - sheet.createRow(4).createCell(0).setCellFormula("ROUND(A6/A4,0)"); - sheet.createRow(5).createCell(0).setCellValue(41); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =ISERROR(C2) (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("ISERROR(A1)"); - FontFormatting font = rule1.createFontFormatting(); - font.setFontColorIndex(IndexedColors.WHITE.index); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:A6") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(2).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)"); - sheet.getRow(4).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)"); - } - - /** - * Use Excel conditional formatting to hide the duplicate values, - * and make the list easier to read. In this example, when the table is sorted by Region, - * the second (and subsequent) occurences of each region name will have white font colour. - */ - static void hideDupplicates(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("City"); - sheet.createRow(1).createCell(0).setCellValue("Boston"); - sheet.createRow(2).createCell(0).setCellValue("Boston"); - sheet.createRow(3).createCell(0).setCellValue("Chicago"); - sheet.createRow(4).createCell(0).setCellValue("Chicago"); - sheet.createRow(5).createCell(0).setCellValue("New York"); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("A2=A1"); - FontFormatting font = rule1.createFontFormatting(); - font.setFontColorIndex(IndexedColors.WHITE.index); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:A6") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(1).createCell(1).setCellValue("<== the second (and subsequent) " + - "occurences of each region name will have white font colour. " + - "Condition: Formula Is =A2=A1 (White Font)"); - } - - /** - * Use Excel conditional formatting to highlight duplicate entries in a column. - */ - static void formatDuplicates(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("Code"); - sheet.createRow(1).createCell(0).setCellValue(4); - sheet.createRow(2).createCell(0).setCellValue(3); - sheet.createRow(3).createCell(0).setCellValue(6); - sheet.createRow(4).createCell(0).setCellValue(3); - sheet.createRow(5).createCell(0).setCellValue(5); - sheet.createRow(6).createCell(0).setCellValue(8); - sheet.createRow(7).createCell(0).setCellValue(0); - sheet.createRow(8).createCell(0).setCellValue(2); - sheet.createRow(9).createCell(0).setCellValue(8); - sheet.createRow(10).createCell(0).setCellValue(6); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($A$2:$A$11,A2)>1"); - FontFormatting font = rule1.createFontFormatting(); - font.setFontStyle(false, true); - font.setFontColorIndex(IndexedColors.BLUE.index); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:A11") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(2).createCell(1).setCellValue("<== Duplicates numbers in the column are highlighted. " + - "Condition: Formula Is =COUNTIF($A$2:$A$11,A2)>1 (Blue Font)"); - } - - /** - * Use Excel conditional formatting to highlight items that are in a list on the worksheet. - */ - static void inList(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("Codes"); - sheet.createRow(1).createCell(0).setCellValue("AA"); - sheet.createRow(2).createCell(0).setCellValue("BB"); - sheet.createRow(3).createCell(0).setCellValue("GG"); - sheet.createRow(4).createCell(0).setCellValue("AA"); - sheet.createRow(5).createCell(0).setCellValue("FF"); - sheet.createRow(6).createCell(0).setCellValue("XX"); - sheet.createRow(7).createCell(0).setCellValue("CC"); - - sheet.getRow(0).createCell(2).setCellValue("Valid"); - sheet.getRow(1).createCell(2).setCellValue("AA"); - sheet.getRow(2).createCell(2).setCellValue("BB"); - sheet.getRow(3).createCell(2).setCellValue("CC"); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($C$2:$C$4,A2)"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.LIGHT_BLUE.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:A8") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(2).createCell(3).setCellValue("<== Use Excel conditional formatting to highlight items that are in a list on the worksheet"); - } - - /** - * Use Excel conditional formatting to highlight payments that are due in the next thirty days. - * In this example, Due dates are entered in cells A2:A4. - */ - static void expiry(Sheet sheet) { - CellStyle style = sheet.getWorkbook().createCellStyle(); - style.setDataFormat((short)BuiltinFormats.getBuiltinFormat("d-mmm")); - - sheet.createRow(0).createCell(0).setCellValue("Date"); - sheet.createRow(1).createCell(0).setCellFormula("TODAY()+29"); - sheet.createRow(2).createCell(0).setCellFormula("A2+1"); - sheet.createRow(3).createCell(0).setCellFormula("A3+1"); - - for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("AND(A2-TODAY()>=0,A2-TODAY()<=30)"); - FontFormatting font = rule1.createFontFormatting(); - font.setFontStyle(false, true); - font.setFontColorIndex(IndexedColors.BLUE.index); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:A4") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted"); - } - - /** - * Use Excel conditional formatting to shade alternating rows on the worksheet - */ - static void shadeAlt(Sheet sheet) { - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:Z100") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows"); - sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),2) (Light Green Fill)"); - } - - /** - * You can use Excel conditional formatting to shade bands of rows on the worksheet. - * In this example, 3 rows are shaded light grey, and 3 are left with no shading. - * In the MOD function, the total number of rows in the set of banded rows (6) is entered. - */ - static void shadeBands(Sheet sheet) { - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),6)<3"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:Z100") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.createRow(0).createCell(1).setCellValue("Shade Bands of Rows"); - sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),6)<2 (Light Grey Fill)"); - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java b/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java deleted file mode 100644 index b0efc4f0ce..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java +++ /dev/null @@ -1,228 +0,0 @@ - /* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.examples; -import java.io.*; -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddressList; - -/** - * Demonstrates one technique that may be used to create linked or dependent - * drop down lists. This refers to a situation in which the selection made - * in one drop down list affects the options that are displayed in the second - * or subsequent drop down list(s). In this example, the value the user selects - * from the down list in cell A1 will affect the values displayed in the linked - * drop down list in cell B1. For the sake of simplicity, the data for the drop - * down lists is included on the same worksheet but this does not have to be the - * case; the data could appear on a separate sheet. If this were done, then the - * names for the regions would have to be different, they would have to include - * the name of the sheet. - * - * There are two keys to this technique. The first is the use of named area or - * regions of cells to hold the data for the drop down lists and the second is - * making use of the INDIRECT() function to convert a name into the addresses - * of the cells it refers to. - * - * Note that whilst this class builds just two linked drop down lists, there is - * nothing to prevent more being created. Quite simply, use the value selected - * by the user in one drop down list to determine what is shown in another and the - * value selected in that drop down list to determine what is shown in a third, - * and so on. Also, note that the data for the drop down lists is contained on - * contained on the same sheet as the validations themselves. This is done simply - * for simplicity and there is nothing to prevent a separate sheet being created - * and used to hold the data. If this is done then problems may be encountered - * if the sheet is opened with OpenOffice Calc. To prevent these problems, it is - * better to include the name of the sheet when calling the setRefersToFormula() - * method. - * - * @author Mark Beardsley [msb at apache.org] - * @version 1.00 30th March 2012 - */ -public class LinkedDropDownLists { - - LinkedDropDownLists(String workbookName) { - File file = null; - FileOutputStream fos = null; - Workbook workbook = null; - Sheet sheet = null; - DataValidationHelper dvHelper = null; - DataValidationConstraint dvConstraint = null; - DataValidation validation = null; - CellRangeAddressList addressList = null; - try { - - // Using the ss.usermodel allows this class to support both binary - // and xml based workbooks. The choice of which one to create is - // made by checking the file extension. - if (workbookName.endsWith(".xlsx")) { - workbook = new XSSFWorkbook(); - } else { - workbook = new HSSFWorkbook(); - } - - // Build the sheet that will hold the data for the validations. This - // must be done first as it will create names that are referenced - // later. - sheet = workbook.createSheet("Linked Validations"); - LinkedDropDownLists.buildDataSheet(sheet); - - // Build the first data validation to occupy cell A1. Note - // that it retrieves it's data from the named area or region called - // CHOICES. Further information about this can be found in the - // static buildDataSheet() method below. - addressList = new CellRangeAddressList(0, 0, 0, 0); - dvHelper = sheet.getDataValidationHelper(); - dvConstraint = dvHelper.createFormulaListConstraint("CHOICES"); - validation = dvHelper.createValidation(dvConstraint, addressList); - sheet.addValidationData(validation); - - // Now, build the linked or dependent drop down list that will - // occupy cell B1. The key to the whole process is the use of the - // INDIRECT() function. In the buildDataSheet(0 method, a series of - // named regions are created and the names of three of them mirror - // the options available to the user in the first drop down list - // (in cell A1). Using the INDIRECT() function makes it possible - // to convert the selection the user makes in that first drop down - // into the addresses of a named region of cells and then to use - // those cells to populate the second drop down list. - addressList = new CellRangeAddressList(0, 0, 1, 1); - dvConstraint = dvHelper.createFormulaListConstraint( - "INDIRECT(UPPER($A$1))"); - validation = dvHelper.createValidation(dvConstraint, addressList); - sheet.addValidationData(validation); - - file = new File(workbookName); - fos = new FileOutputStream(file); - workbook.write(fos); - } catch (IOException ioEx) { - System.out.println("Caught a: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follws:....."); - ioEx.printStackTrace(System.out); - } finally { - try { - if (fos != null) { - fos.close(); - fos = null; - } - } catch (IOException ioEx) { - System.out.println("Caught a: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follws:....."); - ioEx.printStackTrace(System.out); - } - } - } - - /** - * Called to populate the named areas/regions. The contents of the cells on - * row one will be used to populate the first drop down list. The contents of - * the cells on rows two, three and four will be used to populate the second - * drop down list, just which row will be determined by the choice the user - * makes in the first drop down list. - * - * In all cases, the approach is to create a row, create and populate cells - * with data and then specify a name that identifies those cells. With the - * exception of the first range, the names that are chosen for each range - * of cells are quite important. In short, each of the options the user - * could select in the first drop down list is used as the name for another - * range of cells. Thus, in this example, the user can select either - * 'Animal', 'Vegetable' or 'Mineral' in the first drop down and so the - * sheet contains ranges named 'ANIMAL', 'VEGETABLE' and 'MINERAL'. - * - * @param dataSheet An instance of a class that implements the Sheet Sheet - * interface (HSSFSheet or XSSFSheet). - */ - private static final void buildDataSheet(Sheet dataSheet) { - Row row = null; - Cell cell = null; - Name name = null; - - // The first row will hold the data for the first validation. - row = dataSheet.createRow(10); - cell = row.createCell(0); - cell.setCellValue("Animal"); - cell = row.createCell(1); - cell.setCellValue("Vegetable"); - cell = row.createCell(2); - cell.setCellValue("Mineral"); - name = dataSheet.getWorkbook().createName(); - name.setRefersToFormula("$A$11:$C$11"); - name.setNameName("CHOICES"); - - // The next three rows will hold the data that will be used to - // populate the second, or linked, drop down list. - row = dataSheet.createRow(11); - cell = row.createCell(0); - cell.setCellValue("Lion"); - cell = row.createCell(1); - cell.setCellValue("Tiger"); - cell = row.createCell(2); - cell.setCellValue("Leopard"); - cell = row.createCell(3); - cell.setCellValue("Elephant"); - cell = row.createCell(4); - cell.setCellValue("Eagle"); - cell = row.createCell(5); - cell.setCellValue("Horse"); - cell = row.createCell(6); - cell.setCellValue("Zebra"); - name = dataSheet.getWorkbook().createName(); - name.setRefersToFormula("$A$12:$G$12"); - name.setNameName("ANIMAL"); - - row = dataSheet.createRow(12); - cell = row.createCell(0); - cell.setCellValue("Cabbage"); - cell = row.createCell(1); - cell.setCellValue("Cauliflower"); - cell = row.createCell(2); - cell.setCellValue("Potato"); - cell = row.createCell(3); - cell.setCellValue("Onion"); - cell = row.createCell(4); - cell.setCellValue("Beetroot"); - cell = row.createCell(5); - cell.setCellValue("Asparagus"); - cell = row.createCell(6); - cell.setCellValue("Spinach"); - cell = row.createCell(7); - cell.setCellValue("Chard"); - name = dataSheet.getWorkbook().createName(); - name.setRefersToFormula("$A$13:$H$13"); - name.setNameName("VEGETABLE"); - - row = dataSheet.createRow(13); - cell = row.createCell(0); - cell.setCellValue("Bauxite"); - cell = row.createCell(1); - cell.setCellValue("Quartz"); - cell = row.createCell(2); - cell.setCellValue("Feldspar"); - cell = row.createCell(3); - cell.setCellValue("Shist"); - cell = row.createCell(4); - cell.setCellValue("Shale"); - cell = row.createCell(5); - cell.setCellValue("Mica"); - name = dataSheet.getWorkbook().createName(); - name.setRefersToFormula("$A$14:$F$14"); - name.setNameName("MINERAL"); - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/LoanCalculator.java b/src/examples/src/org/apache/poi/ss/examples/LoanCalculator.java deleted file mode 100644 index 9598436589..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/LoanCalculator.java +++ /dev/null @@ -1,305 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.util.Map; -import java.util.HashMap; -import java.io.FileOutputStream; - -/** - * Simple Loan Calculator. Demonstrates advance usage of cell formulas and named ranges. - * - * Usage: - * LoanCalculator -xls|xlsx - * - * @author Yegor Kozlov - */ -public class LoanCalculator { - - public static void main(String[] args) throws Exception { - Workbook wb; - - if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); - else wb = new XSSFWorkbook(); - - Map styles = createStyles(wb); - Sheet sheet = wb.createSheet("Loan Calculator"); - sheet.setPrintGridlines(false); - sheet.setDisplayGridlines(false); - - PrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setLandscape(true); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - - sheet.setColumnWidth(0, 3*256); - sheet.setColumnWidth(1, 3*256); - sheet.setColumnWidth(2, 11*256); - sheet.setColumnWidth(3, 14*256); - sheet.setColumnWidth(4, 14*256); - sheet.setColumnWidth(5, 14*256); - sheet.setColumnWidth(6, 14*256); - - createNames(wb); - - Row titleRow = sheet.createRow(0); - titleRow.setHeightInPoints(35); - for (int i = 1; i <= 7; i++) { - titleRow.createCell(i).setCellStyle(styles.get("title")); - } - Cell titleCell = titleRow.getCell(2); - titleCell.setCellValue("Simple Loan Calculator"); - sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1")); - - Row row = sheet.createRow(2); - Cell cell = row.createCell(4); - cell.setCellValue("Enter values"); - cell.setCellStyle(styles.get("item_right")); - - row = sheet.createRow(3); - cell = row.createCell(2); - cell.setCellValue("Loan amount"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellStyle(styles.get("input_$")); - cell.setAsActiveCell(); - - row = sheet.createRow(4); - cell = row.createCell(2); - cell.setCellValue("Annual interest rate"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellStyle(styles.get("input_%")); - - row = sheet.createRow(5); - cell = row.createCell(2); - cell.setCellValue("Loan period in years"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellStyle(styles.get("input_i")); - - row = sheet.createRow(6); - cell = row.createCell(2); - cell.setCellValue("Start date of loan"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellStyle(styles.get("input_d")); - - row = sheet.createRow(8); - cell = row.createCell(2); - cell.setCellValue("Monthly payment"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")"); - cell.setCellStyle(styles.get("formula_$")); - - row = sheet.createRow(9); - cell = row.createCell(2); - cell.setCellValue("Number of payments"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")"); - cell.setCellStyle(styles.get("formula_i")); - - row = sheet.createRow(10); - cell = row.createCell(2); - cell.setCellValue("Total interest"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")"); - cell.setCellStyle(styles.get("formula_$")); - - row = sheet.createRow(11); - cell = row.createCell(2); - cell.setCellValue("Total cost of loan"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")"); - cell.setCellStyle(styles.get("formula_$")); - - - // Write the output to a file - String file = "loan-calculator.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - } - - /** - * cell styles used for formatting calendar sheets - */ - private static Map createStyles(Workbook wb){ - Map styles = new HashMap(); - - CellStyle style; - Font titleFont = wb.createFont(); - titleFont.setFontHeightInPoints((short)14); - titleFont.setFontName("Trebuchet MS"); - style = wb.createCellStyle(); - style.setFont(titleFont); - style.setBorderBottom(CellStyle.BORDER_DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - styles.put("title", style); - - Font itemFont = wb.createFont(); - itemFont.setFontHeightInPoints((short)9); - itemFont.setFontName("Trebuchet MS"); - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_LEFT); - style.setFont(itemFont); - styles.put("item_left", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(itemFont); - styles.put("item_right", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(itemFont); - style.setBorderRight(CellStyle.BORDER_DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(CellStyle.BORDER_DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(CellStyle.BORDER_DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(CellStyle.BORDER_DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)")); - styles.put("input_$", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(itemFont); - style.setBorderRight(CellStyle.BORDER_DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(CellStyle.BORDER_DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(CellStyle.BORDER_DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(CellStyle.BORDER_DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("0.000%")); - styles.put("input_%", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(itemFont); - style.setBorderRight(CellStyle.BORDER_DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(CellStyle.BORDER_DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(CellStyle.BORDER_DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(CellStyle.BORDER_DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("0")); - styles.put("input_i", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setFont(itemFont); - style.setDataFormat(wb.createDataFormat().getFormat("m/d/yy")); - styles.put("input_d", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(itemFont); - style.setBorderRight(CellStyle.BORDER_DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(CellStyle.BORDER_DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(CellStyle.BORDER_DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(CellStyle.BORDER_DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("$##,##0.00")); - style.setBorderBottom(CellStyle.BORDER_DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - styles.put("formula_$", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_RIGHT); - style.setFont(itemFont); - style.setBorderRight(CellStyle.BORDER_DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(CellStyle.BORDER_DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(CellStyle.BORDER_DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(CellStyle.BORDER_DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("0")); - style.setBorderBottom(CellStyle.BORDER_DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - styles.put("formula_i", style); - - return styles; - } - - //define named ranges for the inputs and formulas - public static void createNames(Workbook wb){ - Name name; - - name = wb.createName(); - name.setNameName("Interest_Rate"); - name.setRefersToFormula("'Loan Calculator'!$E$5"); - - name = wb.createName(); - name.setNameName("Loan_Amount"); - name.setRefersToFormula("'Loan Calculator'!$E$4"); - - name = wb.createName(); - name.setNameName("Loan_Start"); - name.setRefersToFormula("'Loan Calculator'!$E$7"); - - name = wb.createName(); - name.setNameName("Loan_Years"); - name.setRefersToFormula("'Loan Calculator'!$E$6"); - - name = wb.createName(); - name.setNameName("Number_of_Payments"); - name.setRefersToFormula("'Loan Calculator'!$E$10"); - - name = wb.createName(); - name.setNameName("Monthly_Payment"); - name.setRefersToFormula("-PMT(Interest_Rate/12,Number_of_Payments,Loan_Amount)"); - - name = wb.createName(); - name.setNameName("Total_Cost"); - name.setRefersToFormula("'Loan Calculator'!$E$12"); - - name = wb.createName(); - name.setNameName("Total_Interest"); - name.setRefersToFormula("'Loan Calculator'!$E$11"); - - name = wb.createName(); - name.setNameName("Values_Entered"); - name.setRefersToFormula("IF(Loan_Amount*Interest_Rate*Loan_Years*Loan_Start>0,1,0)"); - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/SSPerformanceTest.java b/src/examples/src/org/apache/poi/ss/examples/SSPerformanceTest.java deleted file mode 100644 index 4d6dee448b..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/SSPerformanceTest.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.ss.examples; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; - -public class SSPerformanceTest { - public static void main(String[] args) { - if (args.length != 4) usage("need four command arguments"); - - String type = args[0]; - long timeStarted = System.currentTimeMillis(); - Workbook workBook = createWorkbook(type); - boolean isHType = workBook instanceof HSSFWorkbook; - - int rows = parseInt(args[1], "Failed to parse rows value as integer"); - int cols = parseInt(args[2], "Failed to parse cols value as integer"); - boolean saveFile = parseInt(args[3], "Failed to parse saveFile value as integer") != 0; - - Map styles = createStyles(workBook); - - Sheet sheet = workBook.createSheet("Main Sheet"); - - Cell headerCell = sheet.createRow(0).createCell(0); - headerCell.setCellValue("Header text is spanned across multiple cells"); - headerCell.setCellStyle(styles.get("header")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); - - int sheetNo = 0; - int rowIndexInSheet = 1; - double value = 0; - Calendar calendar = Calendar.getInstance(); - for (int rowIndex = 0; rowIndex < rows; rowIndex++) { - if (isHType && sheetNo != rowIndex / 0x10000) { - sheet = workBook.createSheet("Spillover from sheet " + (++sheetNo)); - headerCell.setCellValue("Header text is spanned across multiple cells"); - headerCell.setCellStyle(styles.get("header")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); - rowIndexInSheet = 1; - } - - Row row = sheet.createRow(rowIndexInSheet); - for (int colIndex = 0; colIndex < cols; colIndex++) { - Cell cell = row.createCell(colIndex); - String address = new CellReference(cell).formatAsString(); - switch (colIndex){ - case 0: - // column A: default number format - cell.setCellValue(value++); - break; - case 1: - // column B: #,##0 - cell.setCellValue(value++); - cell.setCellStyle(styles.get("#,##0.00")); - break; - case 2: - // column C: $#,##0.00 - cell.setCellValue(value++); - cell.setCellStyle(styles.get("$#,##0.00")); - break; - case 3: - // column D: red bold text on yellow background - cell.setCellValue(address); - cell.setCellStyle(styles.get("red-bold")); - break; - case 4: - // column E: boolean - // TODO booleans are shown as 1/0 instead of TRUE/FALSE - cell.setCellValue(rowIndex % 2 == 0); - break; - case 5: - // column F: date / time - cell.setCellValue(calendar); - cell.setCellStyle(styles.get("m/d/yyyy")); - calendar.roll(Calendar.DAY_OF_YEAR, -1); - break; - case 6: - // column F: formula - // TODO formulas are not yet supported in SXSSF - //cell.setCellFormula("SUM(A" + (rowIndex+1) + ":E" + (rowIndex+1)+ ")"); - //break; - default: - cell.setCellValue(value++); - break; - } - } - rowIndexInSheet++; - } - if (saveFile) { - String fileName = type + "_" + rows + "_" + cols + "." + getFileSuffix(args[0]); - try { - FileOutputStream out = new FileOutputStream(fileName); - workBook.write(out); - out.close(); - } catch (IOException ioe) { - System.err.println("Error: failed to write to file \"" + fileName + "\", reason=" + ioe.getMessage()); - } - } - long timeFinished = System.currentTimeMillis(); - System.out.println("Elapsed " + (timeFinished-timeStarted)/1000 + " seconds"); - } - - static Map createStyles(Workbook wb) { - Map styles = new HashMap(); - CellStyle style; - - Font headerFont = wb.createFont(); - headerFont.setFontHeightInPoints((short) 14); - headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - style.setFont(headerFont); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - styles.put("header", style); - - Font monthFont = wb.createFont(); - monthFont.setFontHeightInPoints((short)12); - monthFont.setColor(IndexedColors.RED.getIndex()); - monthFont.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - style.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setFont(monthFont); - styles.put("red-bold", style); - - String[] nfmt = {"#,##0.00", "$#,##0.00", "m/d/yyyy"}; - for(String fmt : nfmt){ - style = wb.createCellStyle(); - style.setDataFormat(wb.createDataFormat().getFormat(fmt)); - styles.put(fmt, style); - } - - return styles; - } - - - static void usage(String message) { - System.err.println(message); - System.err.println("usage: java SSPerformanceTest HSSF|XSSF|SXSSF rows cols saveFile (0|1)? "); - System.exit(1); - } - - static Workbook createWorkbook(String type) { - if ("HSSF".equals(type)) - return new HSSFWorkbook(); - else if ("XSSF".equals(type)) - return new XSSFWorkbook(); - else if ("SXSSF".equals(type)) - return new SXSSFWorkbook(); - else - usage("Unknown type \"" + type + "\""); - return null; - } - - static String getFileSuffix(String type) { - if ("HSSF".equals(type)) - return "xls"; - else if ("XSSF".equals(type)) - return "xlsx"; - else if ("SXSSF".equals(type)) - return "xlsx"; - return null; - } - - static int parseInt(String value, String msg) { - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - usage(msg); - } - return 0; - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/TimesheetDemo.java b/src/examples/src/org/apache/poi/ss/examples/TimesheetDemo.java deleted file mode 100644 index 8093f3c7ce..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/TimesheetDemo.java +++ /dev/null @@ -1,220 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.util.Map; -import java.util.HashMap; -import java.io.FileOutputStream; - -/** - * A weekly timesheet created using Apache POI. - * Usage: - * TimesheetDemo -xls|xlsx - * - * @author Yegor Kozlov - */ -public class TimesheetDemo { - private static final String[] titles = { - "Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", - "Total\nHrs", "Overtime\nHrs", "Regular\nHrs" - }; - - private static Object[][] sample_data = { - {"Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0}, - {"Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, null, null, 4.0}, - }; - - public static void main(String[] args) throws Exception { - Workbook wb; - - if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); - else wb = new XSSFWorkbook(); - - Map styles = createStyles(wb); - - Sheet sheet = wb.createSheet("Timesheet"); - PrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setLandscape(true); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - - //title row - Row titleRow = sheet.createRow(0); - titleRow.setHeightInPoints(45); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("Weekly Timesheet"); - titleCell.setCellStyle(styles.get("title")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1")); - - //header row - Row headerRow = sheet.createRow(1); - headerRow.setHeightInPoints(40); - Cell headerCell; - for (int i = 0; i < titles.length; i++) { - headerCell = headerRow.createCell(i); - headerCell.setCellValue(titles[i]); - headerCell.setCellStyle(styles.get("header")); - } - - int rownum = 2; - for (int i = 0; i < 10; i++) { - Row row = sheet.createRow(rownum++); - for (int j = 0; j < titles.length; j++) { - Cell cell = row.createCell(j); - if(j == 9){ - //the 10th cell contains sum over week days, e.g. SUM(C3:I3) - String ref = "C" +rownum+ ":I" + rownum; - cell.setCellFormula("SUM("+ref+")"); - cell.setCellStyle(styles.get("formula")); - } else if (j == 11){ - cell.setCellFormula("J" +rownum+ "-K" + rownum); - cell.setCellStyle(styles.get("formula")); - } else { - cell.setCellStyle(styles.get("cell")); - } - } - } - - //row with totals below - Row sumRow = sheet.createRow(rownum++); - sumRow.setHeightInPoints(35); - Cell cell; - cell = sumRow.createCell(0); - cell.setCellStyle(styles.get("formula")); - cell = sumRow.createCell(1); - cell.setCellValue("Total Hrs:"); - cell.setCellStyle(styles.get("formula")); - - for (int j = 2; j < 12; j++) { - cell = sumRow.createCell(j); - String ref = (char)('A' + j) + "3:" + (char)('A' + j) + "12"; - cell.setCellFormula("SUM(" + ref + ")"); - if(j >= 9) cell.setCellStyle(styles.get("formula_2")); - else cell.setCellStyle(styles.get("formula")); - } - rownum++; - sumRow = sheet.createRow(rownum++); - sumRow.setHeightInPoints(25); - cell = sumRow.createCell(0); - cell.setCellValue("Total Regular Hours"); - cell.setCellStyle(styles.get("formula")); - cell = sumRow.createCell(1); - cell.setCellFormula("L13"); - cell.setCellStyle(styles.get("formula_2")); - sumRow = sheet.createRow(rownum++); - sumRow.setHeightInPoints(25); - cell = sumRow.createCell(0); - cell.setCellValue("Total Overtime Hours"); - cell.setCellStyle(styles.get("formula")); - cell = sumRow.createCell(1); - cell.setCellFormula("K13"); - cell.setCellStyle(styles.get("formula_2")); - - //set sample data - for (int i = 0; i < sample_data.length; i++) { - Row row = sheet.getRow(2 + i); - for (int j = 0; j < sample_data[i].length; j++) { - if(sample_data[i][j] == null) continue; - - if(sample_data[i][j] instanceof String) { - row.getCell(j).setCellValue((String)sample_data[i][j]); - } else { - row.getCell(j).setCellValue((Double)sample_data[i][j]); - } - } - } - - //finally set column widths, the width is measured in units of 1/256th of a character width - sheet.setColumnWidth(0, 30*256); //30 characters wide - for (int i = 2; i < 9; i++) { - sheet.setColumnWidth(i, 6*256); //6 characters wide - } - sheet.setColumnWidth(10, 10*256); //10 characters wide - - // Write the output to a file - String file = "timesheet.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - } - - /** - * Create a library of cell styles - */ - private static Map createStyles(Workbook wb){ - Map styles = new HashMap(); - CellStyle style; - Font titleFont = wb.createFont(); - titleFont.setFontHeightInPoints((short)18); - titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - style.setFont(titleFont); - styles.put("title", style); - - Font monthFont = wb.createFont(); - monthFont.setFontHeightInPoints((short)11); - monthFont.setColor(IndexedColors.WHITE.getIndex()); - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setFont(monthFont); - style.setWrapText(true); - styles.put("header", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setWrapText(true); - style.setBorderRight(CellStyle.BORDER_THIN); - style.setRightBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderLeft(CellStyle.BORDER_THIN); - style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderTop(CellStyle.BORDER_THIN); - style.setTopBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - styles.put("cell", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setDataFormat(wb.createDataFormat().getFormat("0.00")); - styles.put("formula", style); - - style = wb.createCellStyle(); - style.setAlignment(CellStyle.ALIGN_CENTER); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); - style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - style.setDataFormat(wb.createDataFormat().getFormat("0.00")); - styles.put("formula_2", style); - - return styles; - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/ToCSV.java b/src/examples/src/org/apache/poi/ss/examples/ToCSV.java deleted file mode 100644 index 89b4f38c4d..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/ToCSV.java +++ /dev/null @@ -1,770 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.FilenameFilter; -import java.io.IOException; -import java.util.ArrayList; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; - -/** - * Demonstrates one way to convert an Excel spreadsheet into a CSV - * file. This class makes the following assumptions; - * - *
    • 1. Where the Excel workbook contains more that one worksheet, then a single - * CSV file will contain the data from all of the worksheets.
    • - *
    • 2. The data matrix contained in the CSV file will be square. This means that - * the number of fields in each record of the CSV file will match the number - * of cells in the longest row found in the Excel workbook. Any short records - * will be 'padded' with empty fields - an empty field is represented in the - * the CSV file in this way - ,,.
    • - *
    • 3. Empty fields will represent missing cells.
    • - *
    • 4. A record consisting of empty fields will be used to represent an empty row - * in the Excel workbook.
    • - *
      - * Therefore, if the worksheet looked like this; - * - *
      - *  ___________________________________________
      - *     |       |       |       |       |       |
      - *     |   A   |   B   |   C   |   D   |   E   |
      - *  ___|_______|_______|_______|_______|_______|
      - *     |       |       |       |       |       |
      - *   1 |   1   |   2   |   3   |   4   |   5   |
      - *  ___|_______|_______|_______|_______|_______|
      - *     |       |       |       |       |       |
      - *   2 |       |       |       |       |       |
      - *  ___|_______|_______|_______|_______|_______|
      - *     |       |       |       |       |       |
      - *   3 |       |   A   |       |   B   |       |
      - *  ___|_______|_______|_______|_______|_______|
      - *     |       |       |       |       |       |
      - *   4 |       |       |       |       |   Z   |
      - *  ___|_______|_______|_______|_______|_______|
      - *     |       |       |       |       |       |
      - *   5 | 1,400 |       |  250  |       |       |
      - *  ___|_______|_______|_______|_______|_______|
      - *
      - * 
      - * - * Then, the resulting CSV file will contain the following lines (records); - *
      - * 1,2,3,4,5
      - * ,,,,
      - * ,A,,B,
      - * ,,,,Z
      - * "1,400",,250,,
      - * 

      - * Typically, the comma is used to separate each of the fields that, together, - * constitute a single record or line within the CSV file. This is not however - * a hard and fast rule and so this class allows the user to determine which - * character is used as the field separator and assumes the comma if none other - * is specified. - *

      - * If a field contains the separator then it will be escaped. If the file should - * obey Excel's CSV formatting rules, then the field will be surrounded with - * speech marks whilst if it should obey UNIX conventions, each occurrence of - * the separator will be preceded by the backslash character. - *

      - * If a field contains an end of line (EOL) character then it too will be - * escaped. If the file should obey Excel's CSV formatting rules then the field - * will again be surrounded by speech marks. On the other hand, if the file - * should follow UNIX conventions then a single backslash will precede the - * EOL character. There is no single applicable standard for UNIX and some - * appications replace the CR with \r and the LF with \n but this class will - * not do so. - *

      - * If the field contains double quotes then that character will be escaped. It - * seems as though UNIX does not define a standard for this whilst Excel does. - * Should the CSV file have to obey Excel's formmating rules then the speech - * mark character will be escaped with a second set of speech marks. Finally, an - * enclosing set of speah marks will also surround the entire field. Thus, if - * the following line of text appeared in a cell - "Hello" he said - it would - * look like this when converted into a field within a CSV file - """Hello"" he - * said". - *

      - * Finally, it is worth noting that talk of CSV 'standards' is really slightly - * missleading as there is no such thing. It may well be that the code in this - * class has to be modified to produce files to suit a specific application - * or requirement. - *

      - * @author Mark B - * @version 1.00 9th April 2010 - * 1.10 13th April 2010 - Added support for processing all Excel - * workbooks in a folder along with the ability - * to specify a field separator character. - * 2.00 14th April 2010 - Added support for embedded characters; the - * field separator, EOL and double quotes or - * speech marks. In addition, gave the client - * the ability to select how these are handled, - * either obeying Excel's or UNIX formatting - * conventions. - */ -public class ToCSV { - - private Workbook workbook = null; - private ArrayList csvData = null; - private int maxRowWidth = 0; - private int formattingConvention = 0; - private DataFormatter formatter = null; - private FormulaEvaluator evaluator = null; - private String separator = null; - - private static final String CSV_FILE_EXTENSION = ".csv"; - private static final String DEFAULT_SEPARATOR = ","; - - /** - * Identifies that the CSV file should obey Excel's formatting conventions - * with regard to escaping certain embedded characters - the field separator, - * speech mark and end of line (EOL) character - */ - public static final int EXCEL_STYLE_ESCAPING = 0; - - /** - * Identifies that the CSV file should obey UNIX formatting conventions - * with regard to escaping certain embedded characters - the field separator - * and end of line (EOL) character - */ - public static final int UNIX_STYLE_ESCAPING = 1; - - /** - * Process the contents of a folder, convert the contents of each Excel - * workbook into CSV format and save the resulting file to the specified - * folder using the same name as the original workbook with the .xls or - * .xlsx extension replaced by .csv. This method will ensure that the - * CSV file created contains the comma field separator and that embedded - * characters such as the field separator, the EOL and double quotes are - * escaped in accordance with Excel's convention. - * - * @param strSource An instance of the String class that encapsulates the - * name of and path to either a folder containing those Excel - * workbook(s) or the name of and path to an individual Excel workbook - * that is/are to be converted. - * @param strDestination An instance of the String class encapsulating the - * name of and path to a folder that will contain the resulting CSV - * files. - * @throws java.io.FileNotFoundException Thrown if any file cannot be located - * on the filesystem during processing. - * @throws java.io.IOException Thrown if the filesystem encounters any - * problems during processing. - * @throws java.lang.IllegalArgumentException Thrown if the values passed - * to the strSource parameter refers to a file or folder that does not - * exist or if the value passed to the strDestination paramater refers - * to a folder that does not exist or simply does not refer to a - * folder. - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown - * if the xml markup encountered whilst parsing a SpreadsheetML - * file (.xlsx) is invalid. - */ - public void convertExcelToCSV(String strSource, String strDestination) - throws FileNotFoundException, IOException, - IllegalArgumentException, InvalidFormatException { - - // Simply chain the call to the overloaded convertExcelToCSV(String, - // String, String, int) method, pass the default separator and ensure - // that certain embedded characters are escaped in accordance with - // Excel's formatting conventions - this.convertExcelToCSV(strSource, strDestination, - ToCSV.DEFAULT_SEPARATOR, ToCSV.EXCEL_STYLE_ESCAPING); - } - - /** - * Process the contents of a folder, convert the contents of each Excel - * workbook into CSV format and save the resulting file to the specified - * folder using the same name as the original workbook with the .xls or - * .xlsx extension replaced by .csv. This method allows the client to - * define the field separator but will ensure that embedded characters such - * as the field separator, the EOL and double quotes are escaped in - * accordance with Excel's convention. - * - * @param strSource An instance of the String class that encapsulates the - * name of and path to either a folder containing those Excel - * workbook(s) or the name of and path to an individual Excel workbook - * that is/are to be converted. - * @param strDestination An instance of the String class encapsulating the - * name of and path to a folder that will contain the resulting CSV - * files. - * @param separator An instance of the String class that encapsulates the - * character or characters the client wishes to use as the field - * separator. - * @throws java.io.FileNotFoundException Thrown if any file cannot be located - * on the filesystem during processing. - * @throws java.io.IOException Thrown if the filesystem encounters any - * problems during processing. - * @throws java.lang.IllegalArgumentException Thrown if the values passed - * to the strSource parameter refers to a file or folder that does not - * exist or if the value passed to the strDestination paramater refers - * to a folder that does not exist or simply does not refer to a - * folder. - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown - * if the xml markup encounetered whilst parsing a SpreadsheetML - * file (.xlsx) is invalid. - */ - public void convertExcelToCSV(String strSource, String strDestination, - String separator) - throws FileNotFoundException, IOException, - IllegalArgumentException, InvalidFormatException { - - // Simply chain the call to the overloaded convertExcelToCSV(String, - // String, String, int) method and ensure that certain embedded - // characters are escaped in accordance with Excel's formatting - // conventions - this.convertExcelToCSV(strSource, strDestination, - separator, ToCSV.EXCEL_STYLE_ESCAPING); - } - - /** - * Process the contents of a folder, convert the contents of each Excel - * workbook into CSV format and save the resulting file to the specified - * folder using the same name as the original workbook with the .xls or - * .xlsx extension replaced by .csv - * - * @param strSource An instance of the String class that encapsulates the - * name of and path to either a folder containing those Excel - * workbook(s) or the name of and path to an individual Excel workbook - * that is/are to be converted. - * @param strDestination An instance of the String class encapsulating the name - * of and path to a folder that will contain the resulting CSV files. - * @param formattingConvention A primitive int whose value will determine - * whether certain embedded characters should be escaped in accordance - * with Excel's or UNIX formatting conventions. Two constants are - * defined to support this option; ToCSV.EXCEL_STYLE_ESCAPING and - * ToCSV.UNIX_STYLE_ESCAPING - * @param separator An instance of the String class encapsulating the - * characters or characters that should be used to separate items - * on a line within the CSV file. - * @throws java.io.FileNotFoundException Thrown if any file cannot be located - * on the filesystem during processing. - * @throws java.io.IOException Thrown if the filesystem encounters any - * problems during processing. - * @throws java.lang.IllegalArgumentException Thrown if the values passed - * to the strSource parameter refers to a file or folder that does not - * exist, if the value passed to the strDestination paramater refers - * to a folder that does not exist, if the value passed to the - * strDestination parameter does not refer to a folder or if the - * value passed to the formattingConvention parameter is other than - * one of the values defined by the constants ToCSV.EXCEL_STYLE_ESCAPING - * and ToCSV.UNIX_STYLE_ESCAPING. - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown - * if the xml markup encounetered whilst parsing a SpreadsheetML - * file (.xlsx) is invalid. - */ - public void convertExcelToCSV(String strSource, String strDestination, - String separator, int formattingConvention) - throws FileNotFoundException, IOException, - IllegalArgumentException, InvalidFormatException { - File source = new File(strSource); - File destination = new File(strDestination); - File[] filesList = null; - String destinationFilename = null; - - // Check that the source file/folder exists. - if(!source.exists()) { - throw new IllegalArgumentException("The source for the Excel " + - "file(s) cannot be found."); - } - - // Ensure thaat the folder the user has chosen to save the CSV files - // away into firstly exists and secondly is a folder rather than, for - // instance, a data file. - if(!destination.exists()) { - throw new IllegalArgumentException("The folder/directory for the " + - "converted CSV file(s) does not exist."); - } - if(!destination.isDirectory()) { - throw new IllegalArgumentException("The destination for the CSV " + - "file(s) is not a directory/folder."); - } - - // Ensure the value passed to the formattingConvention parameter is - // within range. - if(formattingConvention != ToCSV.EXCEL_STYLE_ESCAPING && - formattingConvention != ToCSV.UNIX_STYLE_ESCAPING) { - throw new IllegalArgumentException("The value passed to the " + - "formattingConvention parameter is out of range."); - } - - // Copy the spearator character and formatting convention into local - // variables for use in other methods. - this.separator = separator; - this.formattingConvention = formattingConvention; - - // Check to see if the sourceFolder variable holds a reference to - // a file or a folder full of files. - if(source.isDirectory()) { - // Get a list of all of the Excel spreadsheet files (workbooks) in - // the source folder/directory - filesList = source.listFiles(new ExcelFilenameFilter()); - } - else { - // Assume that it must be a file handle - although there are other - // options the code should perhaps check - and store the reference - // into the filesList variable. - filesList = new File[]{source}; - } - - // Step through each of the files in the source folder and for each - // open the workbook, convert it's contents to CSV format and then - // save the resulting file away into the folder specified by the - // contents of the destination variable. Note that the name of the - // csv file will be created by taking the name of the Excel file, - // removing the extension and replacing it with .csv. Note that there - // is one drawback with this approach; if the folder holding the files - // contains two workbooks whose names match but one is a binary file - // (.xls) and the other a SpreadsheetML file (.xlsx), then the names - // for both CSV files will be identical and one CSV file will, - // therefore, over-write the other. - for(File excelFile : filesList) { - // Open the workbook - this.openWorkbook(excelFile); - - // Convert it's contents into a CSV file - this.convertToCSV(); - - // Build the name of the csv folder from that of the Excel workbook. - // Simply replace the .xls or .xlsx file extension with .csv - destinationFilename = excelFile.getName(); - destinationFilename = destinationFilename.substring( - 0, destinationFilename.lastIndexOf(".")) + - ToCSV.CSV_FILE_EXTENSION; - - // Save the CSV file away using the newly constricted file name - // and to the specified directory. - this.saveCSVFile(new File(destination, destinationFilename)); - } - } - - /** - * Open an Excel workbook ready for conversion. - * - * @param file An instance of the File class that encapsulates a handle - * to a valid Excel workbook. Note that the workbook can be in - * either binary (.xls) or SpreadsheetML (.xlsx) format. - * @throws java.io.FileNotFoundException Thrown if the file cannot be located. - * @throws java.io.IOException Thrown if a problem occurs in the file system. - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown - * if invalid xml is found whilst parsing an input SpreadsheetML - * file. - */ - private void openWorkbook(File file) throws FileNotFoundException, - IOException, InvalidFormatException { - FileInputStream fis = null; - try { - System.out.println("Opening workbook [" + file.getName() + "]"); - - fis = new FileInputStream(file); - - // Open the workbook and then create the FormulaEvaluator and - // DataFormatter instances that will be needed to, respectively, - // force evaluation of forumlae found in cells and create a - // formatted String encapsulating the cells contents. - this.workbook = WorkbookFactory.create(fis); - this.evaluator = this.workbook.getCreationHelper().createFormulaEvaluator(); - this.formatter = new DataFormatter(true); - } - finally { - if(fis != null) { - fis.close(); - } - } - } - - /** - * Called to convert the contents of the currently opened workbook into - * a CSV file. - */ - private void convertToCSV() { - Sheet sheet = null; - Row row = null; - int lastRowNum = 0; - this.csvData = new ArrayList(); - - System.out.println("Converting files contents to CSV format."); - - // Discover how many sheets there are in the workbook.... - int numSheets = this.workbook.getNumberOfSheets(); - - // and then iterate through them. - for(int i = 0; i < numSheets; i++) { - - // Get a reference to a sheet and check to see if it contains - // any rows. - sheet = this.workbook.getSheetAt(i); - if(sheet.getPhysicalNumberOfRows() > 0) { - - // Note down the index number of the bottom-most row and - // then iterate through all of the rows on the sheet starting - // from the very first row - number 1 - even if it is missing. - // Recover a reference to the row and then call another method - // which will strip the data from the cells and build lines - // for inclusion in the resylting CSV file. - lastRowNum = sheet.getLastRowNum(); - for(int j = 0; j <= lastRowNum; j++) { - row = sheet.getRow(j); - this.rowToCSV(row); - } - } - } - } - - /** - * Called to actually save the data recovered from the Excel workbook - * as a CSV file. - * - * @param file An instance of the File class that encapsulates a handle - * referring to the CSV file. - * @throws java.io.FileNotFoundException Thrown if the file cannot be found. - * @throws java.io.IOException Thrown to indicate and error occurred in the - * underylying file system. - */ - private void saveCSVFile(File file) - throws FileNotFoundException, IOException { - FileWriter fw = null; - BufferedWriter bw = null; - ArrayList line = null; - StringBuffer buffer = null; - String csvLineElement = null; - try { - - System.out.println("Saving the CSV file [" + file.getName() + "]"); - - // Open a writer onto the CSV file. - fw = new FileWriter(file); - bw = new BufferedWriter(fw); - - // Step through the elements of the ArrayList that was used to hold - // all of the data recovered from the Excel workbooks' sheets, rows - // and cells. - for(int i = 0; i < this.csvData.size(); i++) { - buffer = new StringBuffer(); - - // Get an element from the ArrayList that contains the data for - // the workbook. This element will itself be an ArrayList - // containing Strings and each String will hold the data recovered - // from a single cell. The for() loop is used to recover elements - // from this 'row' ArrayList one at a time and to write the Strings - // away to a StringBuffer thus assembling a single line for inclusion - // in the CSV file. If a row was empty or if it was short, then - // the ArrayList that contains it's data will also be shorter than - // some of the others. Therefore, it is necessary to check within - // the for loop to ensure that the ArrayList contains data to be - // processed. If it does, then an element will be recovered and - // appended to the StringBuffer. - line = this.csvData.get(i); - for(int j = 0; j < this.maxRowWidth; j++) { - if(line.size() > j) { - csvLineElement = line.get(j); - if(csvLineElement != null) { - buffer.append(this.escapeEmbeddedCharacters( - csvLineElement)); - } - } - if(j < (this.maxRowWidth - 1)) { - buffer.append(this.separator); - } - } - - // Once the line is built, write it away to the CSV file. - bw.write(buffer.toString().trim()); - - // Condition the inclusion of new line characters so as to - // avoid an additional, superfluous, new line at the end of - // the file. - if(i < (this.csvData.size() - 1)) { - bw.newLine(); - } - } - } - finally { - if(bw != null) { - bw.flush(); - bw.close(); - } - } - } - - /** - * Called to convert a row of cells into a line of data that can later be - * output to the CSV file. - * - * @param row An instance of either the HSSFRow or XSSFRow classes that - * encapsulates information about a row of cells recovered from - * an Excel workbook. - */ - private void rowToCSV(Row row) { - Cell cell = null; - int lastCellNum = 0; - ArrayList csvLine = new ArrayList(); - - // Check to ensure that a row was recovered from the sheet as it is - // possible that one or more rows between other populated rows could be - // missing - blank. If the row does contain cells then... - if(row != null) { - - // Get the index for the right most cell on the row and then - // step along the row from left to right recovering the contents - // of each cell, converting that into a formatted String and - // then storing the String into the csvLine ArrayList. - lastCellNum = row.getLastCellNum(); - for(int i = 0; i <= lastCellNum; i++) { - cell = row.getCell(i); - if(cell == null) { - csvLine.add(""); - } - else { - if(cell.getCellType() != Cell.CELL_TYPE_FORMULA) { - csvLine.add(this.formatter.formatCellValue(cell)); - } - else { - csvLine.add(this.formatter.formatCellValue(cell, this.evaluator)); - } - } - } - // Make a note of the index number of the right most cell. This value - // will later be used to ensure that the matrix of data in the CSV file - // is square. - if(lastCellNum > this.maxRowWidth) { - this.maxRowWidth = lastCellNum; - } - } - this.csvData.add(csvLine); - } - - /** - * Checks to see whether the field - which consists of the formatted - * contents of an Excel worksheet cell encapsulated within a String - contains - * any embedded characters that must be escaped. The method is able to - * comply with either Excel's or UNIX formatting conventions in the - * following manner; - * - * With regard to UNIX conventions, if the field contains any embedded - * field separator or EOL characters they will each be escaped by prefixing - * a leading backspace character. These are the only changes that have yet - * emerged following some research as being required. - * - * Excel has other embedded character escaping requirements, some that emerged - * from empirical testing, other through research. Firstly, with regards to - * any embedded speech marks ("), each occurrence should be escaped with - * another speech mark and the whole field then surrounded with speech marks. - * Thus if a field holds "Hello" he said then it should be modified - * to appear as """Hello"" he said". Furthermore, if the field - * contains either embedded separator or EOL characters, it should also - * be surrounded with speech marks. As a result 1,400 would become - * "1,400" assuming that the comma is the required field separator. - * This has one consequence in, if a field contains embedded speech marks - * and embedded separator characters, checks for both are not required as the - * additional set of speech marks that should be placed around ay field - * containing embedded speech marks will also account for the embedded - * separator. - * - * It is worth making one further note with regard to embedded EOL - * characters. If the data in a worksheet is exported as a CSV file using - * Excel itself, then the field will be surounded with speech marks. If the - * resulting CSV file is then re-imports into another worksheet, the EOL - * character will result in the original simgle field occupying more than - * one cell. This same 'feature' is replicated in this classes behaviour. - * - * @param field An instance of the String class encapsulating the formatted - * contents of a cell on an Excel worksheet. - * @return A String that encapsulates the formatted contents of that - * Excel worksheet cell but with any embedded separator, EOL or - * speech mark characters correctly escaped. - */ - private String escapeEmbeddedCharacters(String field) { - StringBuffer buffer = null; - - // If the fields contents should be formatted to confrom with Excel's - // convention.... - if(this.formattingConvention == ToCSV.EXCEL_STYLE_ESCAPING) { - - // Firstly, check if there are any speech marks (") in the field; - // each occurrence must be escaped with another set of spech marks - // and then the entire field should be enclosed within another - // set of speech marks. Thus, "Yes" he said would become - // """Yes"" he said" - if(field.contains("\"")) { - buffer = new StringBuffer(field.replaceAll("\"", "\\\"\\\"")); - buffer.insert(0, "\""); - buffer.append("\""); - } - else { - // If the field contains either embedded separator or EOL - // characters, then escape the whole field by surrounding it - // with speech marks. - buffer = new StringBuffer(field); - if((buffer.indexOf(this.separator)) > -1 || - (buffer.indexOf("\n")) > -1) { - buffer.insert(0, "\""); - buffer.append("\""); - } - } - return(buffer.toString().trim()); - } - // The only other formatting convention this class obeys is the UNIX one - // where any occurrence of the field separator or EOL character will - // be escaped by preceding it with a backslash. - else { - if(field.contains(this.separator)) { - field = field.replaceAll(this.separator, ("\\\\" + this.separator)); - } - if(field.contains("\n")) { - field = field.replaceAll("\n", "\\\\\n"); - } - return(field); - } - } - - /** - * The main() method contains code that demonstrates how to use the class. - * - * @param args An array containing zero, one or more elements all of type - * String. Each element will encapsulate an argument specified by the - * user when running the program from the command prompt. - */ - public static void main(String[] args) { - // Check the number of arguments passed to the main method. There - // must be two, three or four; the name of and path to either the folder - // containing the Excel files or an individual Excel workbook that is/are - // to be converted, the name of and path to the folder to which the CSV - // files should be written, - optionally - the separator character - // that should be used to separate individual items (fields) on the - // lines (records) of the CSV file and - again optionally - an integer - // that idicates whether the CSV file ought to obey Excel's or UNIX - // convnetions with regard to formatting fields that contain embedded - // separator, Speech mark or EOL character(s). - // - // Note that the names of the CSV files will be derived from those - // of the Excel file(s). Put simply the .xls or .xlsx extension will be - // replaced with .csv. Therefore, if the source folder contains files - // with matching names but different extensions - Test.xls and Test.xlsx - // for example - then the CSV file generated from one will overwrite - // that generated from the other. - ToCSV converter = null; - boolean converted = true; - long startTime = System.currentTimeMillis(); - try { - converter = new ToCSV(); - if(args.length == 2) { - // Just the Source File/Folder and Destination Folder were - // passed to the main method. - converter.convertExcelToCSV(args[0], args[1]); - } - else if(args.length == 3){ - // The Source File/Folder, Destination Folder and Separator - // were passed to the main method. - converter.convertExcelToCSV(args[0], args[1], args[2]); - } - else if(args.length == 4) { - // The Source File/Folder, Destination Folder, Separator and - // Formatting Convnetion were passed to the main method. - converter.convertExcelToCSV(args[0], args[1], - args[2], Integer.parseInt(args[3])); - } - else { - // None or more than four parameters were passed so display - //a Usage message. - System.out.println("Usage: java ToCSV [Source File/Folder] " + - "[Destination Folder] [Separator] [Formatting Convention]\n" + - "\tSource File/Folder\tThis argument should contain the name of and\n" + - "\t\t\t\tpath to either a single Excel workbook or a\n" + - "\t\t\t\tfolder containing one or more Excel workbooks.\n" + - "\tDestination Folder\tThe name of and path to the folder that the\n" + - "\t\t\t\tCSV files should be written out into. The\n" + - "\t\t\t\tfolder must exist before running the ToCSV\n" + - "\t\t\t\tcode as it will not check for or create it.\n" + - "\tSeparator\t\tOptional. The character or characters that\n" + - "\t\t\t\tshould be used to separate fields in the CSV\n" + - "\t\t\t\trecord. If no value is passed then the comma\n" + - "\t\t\t\twill be assumed.\n" + - "\tFormatting Convention\tOptional. This argument can take one of two\n" + - "\t\t\t\tvalues. Passing 0 (zero) will result in a CSV\n" + - "\t\t\t\tfile that obeys Excel's formatting conventions\n" + - "\t\t\t\twhilst passing 1 (one) will result in a file\n" + - "\t\t\t\tthat obeys UNIX formatting conventions. If no\n" + - "\t\t\t\tvalue is passed, then the CSV file produced\n" + - "\t\t\t\twill obey Excel's formatting conventions."); - converted = false; - } - } - // It is not wise to have such a wide catch clause - Exception is very - // close to being at the top of the inheritance hierarchy - though it - // will suffice for this example as it is really not possible to recover - // easilly from an exceptional set of circumstances at this point in the - // program. It should however, ideally be replaced with one or more - // catch clauses optimised to handle more specific problems. - catch(Exception ex) { - System.out.println("Caught an: " + ex.getClass().getName()); - System.out.println("Message: " + ex.getMessage()); - System.out.println("Stacktrace follows:....."); - ex.printStackTrace(System.out); - converted = false; - } - - if (converted) { - System.out.println("Conversion took " + - (int)((System.currentTimeMillis() - startTime)/1000) + " seconds"); - } - } - - /** - * An instance of this class can be used to control the files returned - * be a call to the listFiles() method when made on an instance of the - * File class and that object refers to a folder/directory - */ - class ExcelFilenameFilter implements FilenameFilter { - - /** - * Determine those files that will be returned by a call to the - * listFiles() method. In this case, the name of the file must end with - * either of the following two extension; '.xls' or '.xlsx'. For the - * future, it is very possible to parameterise this and allow the - * containing class to pass, for example, an array of Strings to this - * class on instantiation. Each element in that array could encapsulate - * a valid file extension - '.xls', '.xlsx', '.xlt', '.xlst', etc. These - * could then be used to control which files were returned by the call - * to the listFiles() method. - * - * @param file An instance of the File class that encapsulates a handle - * referring to the folder/directory that contains the file. - * @param name An instance of the String class that encapsulates the - * name of the file. - * @return A boolean value that indicates whether the file should be - * included in the array retirned by the call to the listFiles() - * method. In this case true will be returned if the name of the - * file ends with either '.xls' or '.xlsx' and false will be - * returned in all other instances. - */ - public boolean accept(File file, String name) { - return(name.endsWith(".xls") || name.endsWith(".xlsx")); - } - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/CalculateMortgage.java b/src/examples/src/org/apache/poi/ss/examples/formula/CalculateMortgage.java deleted file mode 100644 index 4b9a325cdf..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/formula/CalculateMortgage.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.formula; - -import org.apache.poi.ss.formula.OperationEvaluationContext ; -import org.apache.poi.ss.formula.eval.ErrorEval ; -import org.apache.poi.ss.formula.eval.EvaluationException ; -import org.apache.poi.ss.formula.eval.NumberEval ; -import org.apache.poi.ss.formula.eval.OperandResolver ; -import org.apache.poi.ss.formula.eval.ValueEval ; -import org.apache.poi.ss.formula.functions.FreeRefFunction ; - -/** - * A simple user-defined function to calculate principal and interest. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class CalculateMortgage implements FreeRefFunction { - - public ValueEval evaluate( ValueEval[] args, OperationEvaluationContext ec ) { - - // verify that we have enough data - if (args.length != 3) { - return ErrorEval.VALUE_INVALID; - } - - // declare doubles for values - double principal, rate, years, result; - try { - // extract values as ValueEval - ValueEval v1 = OperandResolver.getSingleValue( args[0], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - ValueEval v2 = OperandResolver.getSingleValue( args[1], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - ValueEval v3 = OperandResolver.getSingleValue( args[2], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - - // get data as doubles - principal = OperandResolver.coerceValueToDouble( v1 ) ; - rate = OperandResolver.coerceValueToDouble( v2 ) ; - years = OperandResolver.coerceValueToDouble( v3 ) ; - - result = calculateMortgagePayment( principal, rate, years ) ; - System.out.println( "Result = " + result ) ; - - checkValue(result); - - } catch (EvaluationException e) { - return e.getErrorEval(); - } - - return new NumberEval( result ) ; - } - - public double calculateMortgagePayment( double p, double r, double y ) { - double i = r / 12 ; - double n = y * 12 ; - - double principalAndInterest = - p * (( i * Math.pow((1 + i),n ) ) / ( Math.pow((1 + i),n) - 1)) ; - - return principalAndInterest ; - } - /** - * Excel does not support infinities and NaNs, rather, it gives a #NUM! error in these cases - * - * @throws EvaluationException (#NUM!) if result is NaN or Infinity - */ - private void checkValue(double result) throws EvaluationException { - if (Double.isNaN(result) || Double.isInfinite(result)) { - throw new EvaluationException(ErrorEval.NUM_ERROR); - } - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/SettingExternalFunction.java b/src/examples/src/org/apache/poi/ss/examples/formula/SettingExternalFunction.java deleted file mode 100644 index 17f4e0dfa8..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/formula/SettingExternalFunction.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.examples.formula; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * Demonstrates how to use functions provided by third-party add-ins, e.g. Bloomberg Excel Add-in. - * - * There can be situations when you are not interested in formula evaluation, - * you just need to set the formula and the workbook will be evaluation by the client. - * - * @author Yegor Kozlov - */ -public class SettingExternalFunction { - - /** - * wrap external functions in a plugin - */ - public static class BloombergAddIn implements UDFFinder { - private final Map _functionsByName; - - public BloombergAddIn() { - // dummy function that returns NA - // don't care about the implementation, we are not interested in evaluation - // and this method will never be called - FreeRefFunction NA = new FreeRefFunction() { - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - return ErrorEval.NA; - } - }; - _functionsByName = new HashMap(); - _functionsByName.put("BDP", NA); - _functionsByName.put("BDH", NA); - _functionsByName.put("BDS", NA); - } - - public FreeRefFunction findFunction(String name) { - return _functionsByName.get(name.toUpperCase()); - } - - } - - public static void main( String[] args ) throws IOException { - - Workbook wb = new XSSFWorkbook(); // or new HSSFWorkbook() - - // register the add-in - wb.addToolPack(new BloombergAddIn()); - - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100"); - row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") "); - row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") "); - - FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx"); - wb.write(out); - out.close(); - - } - -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/UserDefinedFunctionExample.java b/src/examples/src/org/apache/poi/ss/examples/formula/UserDefinedFunctionExample.java deleted file mode 100644 index 74dca7d1b6..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/formula/UserDefinedFunctionExample.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.formula; - -import java.io.File ; -import java.io.FileInputStream ; -import java.io.FileNotFoundException ; -import java.io.IOException ; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException ; -import org.apache.poi.ss.formula.functions.FreeRefFunction ; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder ; -import org.apache.poi.ss.formula.udf.UDFFinder ; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellReference ; - - -/** - * An example class of how to invoke a User Defined Function for a given - * XLS instance using POI's UDFFinder implementation. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class UserDefinedFunctionExample { - - public static void main( String[] args ) { - - if( args.length != 2 ) { - System.out.println( "usage: UserDefinedFunctionExample fileName cellId" ) ; - return; - } - - System.out.println( "fileName: " + args[0] ) ; - System.out.println( "cell: " + args[1] ) ; - - File workbookFile = new File( args[0] ) ; - - try { - FileInputStream fis = new FileInputStream(workbookFile); - Workbook workbook = WorkbookFactory.create(fis); - fis.close(); - - String[] functionNames = { "calculatePayment" } ; - FreeRefFunction[] functionImpls = { new CalculateMortgage() } ; - - UDFFinder udfToolpack = new DefaultUDFFinder( functionNames, functionImpls ) ; - - // register the user-defined function in the workbook - workbook.addToolPack(udfToolpack); - - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - - CellReference cr = new CellReference( args[1] ) ; - String sheetName = cr.getSheetName() ; - Sheet sheet = workbook.getSheet( sheetName ) ; - int rowIdx = cr.getRow() ; - int colIdx = cr.getCol() ; - Row row = sheet.getRow( rowIdx ) ; - Cell cell = row.getCell( colIdx ) ; - - CellValue value = evaluator.evaluate( cell ) ; - - System.out.println("returns value: " + value ) ; - - } catch( FileNotFoundException e ) { - e.printStackTrace(); - } catch( InvalidFormatException e ) { - e.printStackTrace(); - } catch( IOException e ) { - e.printStackTrace(); - } - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/mortgage-calculation.xls b/src/examples/src/org/apache/poi/ss/examples/formula/mortgage-calculation.xls deleted file mode 100644 index 4e71ba8e65..0000000000 Binary files a/src/examples/src/org/apache/poi/ss/examples/formula/mortgage-calculation.xls and /dev/null differ diff --git a/src/examples/src/org/apache/poi/ss/examples/html/HSSFHtmlHelper.java b/src/examples/src/org/apache/poi/ss/examples/html/HSSFHtmlHelper.java deleted file mode 100644 index 1e235f929e..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/HSSFHtmlHelper.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.html; - -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFPalette; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.CellStyle; - -import java.util.Formatter; - -/** - * Implementation of {@link HtmlHelper} for HSSF files. - * - * @author Ken Arnold, Industrious Media LLC - */ -public class HSSFHtmlHelper implements HtmlHelper { - private final HSSFWorkbook wb; - private final HSSFPalette colors; - - private static final HSSFColor HSSF_AUTO = new HSSFColor.AUTOMATIC(); - - public HSSFHtmlHelper(HSSFWorkbook wb) { - this.wb = wb; - // If there is no custom palette, then this creates a new one that is - // a copy of the default - colors = wb.getCustomPalette(); - } - - public void colorStyles(CellStyle style, Formatter out) { - HSSFCellStyle cs = (HSSFCellStyle) style; - out.format(" /* fill pattern = %d */%n", cs.getFillPattern()); - styleColor(out, "background-color", cs.getFillForegroundColor()); - styleColor(out, "color", cs.getFont(wb).getColor()); - styleColor(out, "border-left-color", cs.getLeftBorderColor()); - styleColor(out, "border-right-color", cs.getRightBorderColor()); - styleColor(out, "border-top-color", cs.getTopBorderColor()); - styleColor(out, "border-bottom-color", cs.getBottomBorderColor()); - } - - private void styleColor(Formatter out, String attr, short index) { - HSSFColor color = colors.getColor(index); - if (index == HSSF_AUTO.getIndex() || color == null) { - out.format(" /* %s: index = %d */%n", attr, index); - } else { - short[] rgb = color.getTriplet(); - out.format(" %s: #%02x%02x%02x; /* index = %d */%n", attr, rgb[0], - rgb[1], rgb[2], index); - } - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/html/HtmlHelper.java b/src/examples/src/org/apache/poi/ss/examples/html/HtmlHelper.java deleted file mode 100644 index 2cb1a91734..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/HtmlHelper.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples.html; - -import org.apache.poi.ss.usermodel.CellStyle; - -import java.util.Formatter; - -/** - * This interface is used where code wants to be independent of the workbook - * formats. If you are writing such code, you can add a method to this - * interface, and then implement it for both HSSF and XSSF workbooks, letting - * the driving code stay independent of format. - * - * @author Ken Arnold, Industrious Media LLC - */ -public interface HtmlHelper { - /** - * Outputs the appropriate CSS style for the given cell style. - * - * @param style The cell style. - * @param out The place to write the output. - */ - void colorStyles(CellStyle style, Formatter out); -} diff --git a/src/examples/src/org/apache/poi/ss/examples/html/ToHtml.java b/src/examples/src/org/apache/poi/ss/examples/html/ToHtml.java deleted file mode 100644 index b5480cf59e..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/ToHtml.java +++ /dev/null @@ -1,443 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.html; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.format.CellFormat; -import org.apache.poi.ss.format.CellFormatResult; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.io.BufferedReader; -import java.io.Closeable; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.util.Formatter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import static org.apache.poi.ss.usermodel.CellStyle.*; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; - -/** - * This example shows how to display a spreadsheet in HTML using the classes for - * spreadsheet display. - * - * @author Ken Arnold, Industrious Media LLC - */ -public class ToHtml { - private final Workbook wb; - private final Appendable output; - private boolean completeHTML; - private Formatter out; - private boolean gotBounds; - private int firstColumn; - private int endColumn; - private HtmlHelper helper; - - private static final String DEFAULTS_CLASS = "excelDefaults"; - private static final String COL_HEAD_CLASS = "colHeader"; - private static final String ROW_HEAD_CLASS = "rowHeader"; - - private static final Map ALIGN = mapFor(ALIGN_LEFT, "left", - ALIGN_CENTER, "center", ALIGN_RIGHT, "right", ALIGN_FILL, "left", - ALIGN_JUSTIFY, "left", ALIGN_CENTER_SELECTION, "center"); - - private static final Map VERTICAL_ALIGN = mapFor( - VERTICAL_BOTTOM, "bottom", VERTICAL_CENTER, "middle", VERTICAL_TOP, - "top"); - - private static final Map BORDER = mapFor(BORDER_DASH_DOT, - "dashed 1pt", BORDER_DASH_DOT_DOT, "dashed 1pt", BORDER_DASHED, - "dashed 1pt", BORDER_DOTTED, "dotted 1pt", BORDER_DOUBLE, - "double 3pt", BORDER_HAIR, "solid 1px", BORDER_MEDIUM, "solid 2pt", - BORDER_MEDIUM_DASH_DOT, "dashed 2pt", BORDER_MEDIUM_DASH_DOT_DOT, - "dashed 2pt", BORDER_MEDIUM_DASHED, "dashed 2pt", BORDER_NONE, - "none", BORDER_SLANTED_DASH_DOT, "dashed 2pt", BORDER_THICK, - "solid 3pt", BORDER_THIN, "dashed 1pt"); - - @SuppressWarnings({"unchecked"}) - private static Map mapFor(Object... mapping) { - Map map = new HashMap(); - for (int i = 0; i < mapping.length; i += 2) { - map.put((K) mapping[i], (V) mapping[i + 1]); - } - return map; - } - - /** - * Creates a new converter to HTML for the given workbook. - * - * @param wb The workbook. - * @param output Where the HTML output will be written. - * - * @return An object for converting the workbook to HTML. - */ - public static ToHtml create(Workbook wb, Appendable output) { - return new ToHtml(wb, output); - } - - /** - * Creates a new converter to HTML for the given workbook. If the path ends - * with ".xlsx" an {@link XSSFWorkbook} will be used; otherwise - * this will use an {@link HSSFWorkbook}. - * - * @param path The file that has the workbook. - * @param output Where the HTML output will be written. - * - * @return An object for converting the workbook to HTML. - */ - public static ToHtml create(String path, Appendable output) - throws IOException { - return create(new FileInputStream(path), output); - } - - /** - * Creates a new converter to HTML for the given workbook. This attempts to - * detect whether the input is XML (so it should create an {@link - * XSSFWorkbook} or not (so it should create an {@link HSSFWorkbook}). - * - * @param in The input stream that has the workbook. - * @param output Where the HTML output will be written. - * - * @return An object for converting the workbook to HTML. - */ - public static ToHtml create(InputStream in, Appendable output) - throws IOException { - try { - Workbook wb = WorkbookFactory.create(in); - return create(wb, output); - } catch (InvalidFormatException e){ - throw new IllegalArgumentException("Cannot create workbook from stream", e); - } - } - - private ToHtml(Workbook wb, Appendable output) { - if (wb == null) - throw new NullPointerException("wb"); - if (output == null) - throw new NullPointerException("output"); - this.wb = wb; - this.output = output; - setupColorMap(); - } - - private void setupColorMap() { - if (wb instanceof HSSFWorkbook) - helper = new HSSFHtmlHelper((HSSFWorkbook) wb); - else if (wb instanceof XSSFWorkbook) - helper = new XSSFHtmlHelper((XSSFWorkbook) wb); - else - throw new IllegalArgumentException( - "unknown workbook type: " + wb.getClass().getSimpleName()); - } - - /** - * Run this class as a program - * - * @param args The command line arguments. - * - * @throws Exception Exception we don't recover from. - */ - public static void main(String[] args) throws Exception { - if(args.length < 2){ - System.err.println("usage: ToHtml inputWorkbook outputHtmlFile"); - return; - } - - ToHtml toHtml = create(args[0], new PrintWriter(new FileWriter(args[1]))); - toHtml.setCompleteHTML(true); - toHtml.printPage(); - } - - public void setCompleteHTML(boolean completeHTML) { - this.completeHTML = completeHTML; - } - - public void printPage() throws IOException { - try { - ensureOut(); - if (completeHTML) { - out.format( - "%n"); - out.format("%n"); - out.format("%n"); - out.format("%n"); - out.format("%n"); - } - - print(); - - if (completeHTML) { - out.format("%n"); - out.format("%n"); - } - } finally { - if (out != null) - out.close(); - if (output instanceof Closeable) { - Closeable closeable = (Closeable) output; - closeable.close(); - } - } - } - - public void print() { - printInlineStyle(); - printSheets(); - } - - private void printInlineStyle() { - //out.format("%n"); - out.format("%n"); - } - - private void ensureOut() { - if (out == null) - out = new Formatter(output); - } - - public void printStyles() { - ensureOut(); - - // First, copy the base css - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader( - getClass().getResourceAsStream("excelStyle.css"))); - String line; - while ((line = in.readLine()) != null) { - out.format("%s%n", line); - } - } catch (IOException e) { - throw new IllegalStateException("Reading standard css", e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - //noinspection ThrowFromFinallyBlock - throw new IllegalStateException("Reading standard css", e); - } - } - } - - // now add css for each used style - Set seen = new HashSet(); - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet sheet = wb.getSheetAt(i); - Iterator rows = sheet.rowIterator(); - while (rows.hasNext()) { - Row row = rows.next(); - for (Cell cell : row) { - CellStyle style = cell.getCellStyle(); - if (!seen.contains(style)) { - printStyle(style); - seen.add(style); - } - } - } - } - } - - private void printStyle(CellStyle style) { - out.format(".%s .%s {%n", DEFAULTS_CLASS, styleName(style)); - styleContents(style); - out.format("}%n"); - } - - private void styleContents(CellStyle style) { - styleOut("text-align", style.getAlignment(), ALIGN); - styleOut("vertical-align", style.getAlignment(), VERTICAL_ALIGN); - fontStyle(style); - borderStyles(style); - helper.colorStyles(style, out); - } - - private void borderStyles(CellStyle style) { - styleOut("border-left", style.getBorderLeft(), BORDER); - styleOut("border-right", style.getBorderRight(), BORDER); - styleOut("border-top", style.getBorderTop(), BORDER); - styleOut("border-bottom", style.getBorderBottom(), BORDER); - } - - private void fontStyle(CellStyle style) { - Font font = wb.getFontAt(style.getFontIndex()); - - if (font.getBoldweight() >= HSSFFont.BOLDWEIGHT_NORMAL) - out.format(" font-weight: bold;%n"); - if (font.getItalic()) - out.format(" font-style: italic;%n"); - - int fontheight = font.getFontHeightInPoints(); - if (fontheight == 9) { - //fix for stupid ol Windows - fontheight = 10; - } - out.format(" font-size: %dpt;%n", fontheight); - - // Font color is handled with the other colors - } - - private String styleName(CellStyle style) { - if (style == null) - style = wb.getCellStyleAt((short) 0); - StringBuilder sb = new StringBuilder(); - Formatter fmt = new Formatter(sb); - fmt.format("style_%02x", style.getIndex()); - return fmt.toString(); - } - - private void styleOut(String attr, K key, Map mapping) { - String value = mapping.get(key); - if (value != null) { - out.format(" %s: %s;%n", attr, value); - } - } - - private static int ultimateCellType(Cell c) { - int type = c.getCellType(); - if (type == Cell.CELL_TYPE_FORMULA) - type = c.getCachedFormulaResultType(); - return type; - } - - private void printSheets() { - ensureOut(); - Sheet sheet = wb.getSheetAt(0); - printSheet(sheet); - } - - public void printSheet(Sheet sheet) { - ensureOut(); - out.format("%n", DEFAULTS_CLASS); - printCols(sheet); - printSheetContent(sheet); - out.format("
      %n"); - } - - private void printCols(Sheet sheet) { - out.format("%n"); - ensureColumnBounds(sheet); - for (int i = firstColumn; i < endColumn; i++) { - out.format("%n"); - } - } - - private void ensureColumnBounds(Sheet sheet) { - if (gotBounds) - return; - - Iterator iter = sheet.rowIterator(); - firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0); - endColumn = 0; - while (iter.hasNext()) { - Row row = iter.next(); - short firstCell = row.getFirstCellNum(); - if (firstCell >= 0) { - firstColumn = Math.min(firstColumn, firstCell); - endColumn = Math.max(endColumn, row.getLastCellNum()); - } - } - gotBounds = true; - } - - private void printColumnHeads() { - out.format("%n"); - out.format(" %n", COL_HEAD_CLASS); - out.format(" ◊%n", COL_HEAD_CLASS); - //noinspection UnusedDeclaration - StringBuilder colName = new StringBuilder(); - for (int i = firstColumn; i < endColumn; i++) { - colName.setLength(0); - int cnum = i; - do { - colName.insert(0, (char) ('A' + cnum % 26)); - cnum /= 26; - } while (cnum > 0); - out.format(" %s%n", COL_HEAD_CLASS, colName); - } - out.format(" %n"); - out.format("%n"); - } - - private void printSheetContent(Sheet sheet) { - printColumnHeads(); - - out.format("%n"); - Iterator rows = sheet.rowIterator(); - while (rows.hasNext()) { - Row row = rows.next(); - - out.format(" %n"); - out.format(" %d%n", ROW_HEAD_CLASS, - row.getRowNum() + 1); - for (int i = firstColumn; i < endColumn; i++) { - String content = " "; - String attrs = ""; - CellStyle style = null; - if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) { - Cell cell = row.getCell(i); - if (cell != null) { - style = cell.getCellStyle(); - attrs = tagStyle(cell, style); - //Set the value that is rendered for the cell - //also applies the format - CellFormat cf = CellFormat.getInstance( - style.getDataFormatString()); - CellFormatResult result = cf.apply(cell); - content = result.text; - if (content.equals("")) - content = " "; - } - } - out.format(" %s%n", styleName(style), - attrs, content); - } - out.format(" %n"); - } - out.format("%n"); - } - - private String tagStyle(Cell cell, CellStyle style) { - if (style.getAlignment() == ALIGN_GENERAL) { - switch (ultimateCellType(cell)) { - case HSSFCell.CELL_TYPE_STRING: - return "style=\"text-align: left;\""; - case HSSFCell.CELL_TYPE_BOOLEAN: - case HSSFCell.CELL_TYPE_ERROR: - return "style=\"text-align: center;\""; - case HSSFCell.CELL_TYPE_NUMERIC: - default: - // "right" is the default - break; - } - } - return ""; - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/html/XSSFHtmlHelper.java b/src/examples/src/org/apache/poi/ss/examples/html/XSSFHtmlHelper.java deleted file mode 100644 index 0fe76d17be..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/XSSFHtmlHelper.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.html; - -import java.util.Formatter; -import java.util.Map; - -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Implementation of {@link HtmlHelper} for XSSF files. - * - * @author Ken Arnold, Industrious Media LLC - */ -public class XSSFHtmlHelper implements HtmlHelper { - private final XSSFWorkbook wb; - - private static final Map colors = HSSFColor.getIndexHash(); - - public XSSFHtmlHelper(XSSFWorkbook wb) { - this.wb = wb; - } - - public void colorStyles(CellStyle style, Formatter out) { - XSSFCellStyle cs = (XSSFCellStyle) style; - styleColor(out, "background-color", cs.getFillForegroundXSSFColor()); - styleColor(out, "text-color", cs.getFont().getXSSFColor()); - } - - private void styleColor(Formatter out, String attr, XSSFColor color) { - if (color == null || color.isAuto()) - return; - - byte[] rgb = color.getRgb(); - if (rgb == null) { - return; - } - - // This is done twice -- rgba is new with CSS 3, and browser that don't - // support it will ignore the rgba specification and stick with the - // solid color, which is declared first - out.format(" %s: #%02x%02x%02x;%n", attr, rgb[0], rgb[1], rgb[2]); - byte[] argb = color.getARgb(); - if (argb == null) { - return; - } - out.format(" %s: rgba(0x%02x, 0x%02x, 0x%02x, 0x%02x);%n", attr, - argb[3], argb[0], argb[1], argb[2]); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/html/excelStyle.css b/src/examples/src/org/apache/poi/ss/examples/html/excelStyle.css deleted file mode 100644 index 1083b637a3..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/excelStyle.css +++ /dev/null @@ -1,72 +0,0 @@ -/* - ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== - */ -/* - * This is the default style sheet for html generated by ToHtml - * - * @author Ken Arnold, Industrious Media LLC - */ -.excelDefaults { - background-color: white; - color: black; - text-decoration: none; - direction: ltr; - text-transform: none; - text-indent: 0; - letter-spacing: 0; - word-spacing: 0; - white-space: normal; - unicode-bidi: normal; - vertical-align: 0; - background-image: none; - text-shadow: none; - list-style-image: none; - list-style-type: none; - padding: 0; - margin: 0; - border-collapse: collapse; - white-space: pre; - vertical-align: bottom; - font-style: normal; - font-family: sans-serif; - font-variant: normal; - font-weight: normal; - font-size: 10pt; - text-align: right; -} - -.excelDefaults td { - padding: 1px 5px; - border: 1px solid silver; -} - -.excelDefaults .colHeader { - background-color: silver; - font-weight: bold; - border: 1px solid black; - text-align: center; - padding: 1px 5px; -} - -.excelDefaults .rowHeader { - background-color: silver; - font-weight: bold; - border: 1px solid black; - text-align: right; - padding: 1px 5px; -} diff --git a/src/examples/src/org/apache/poi/ss/examples/html/package.html b/src/examples/src/org/apache/poi/ss/examples/html/package.html deleted file mode 100644 index 1c8e6af5c4..0000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/package.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - -This package contains an example that uses POI to convert a workbook into -an HTML representation of the data. It can use both XSSF and HSSF workbooks. - - diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/DataExtraction.java b/src/examples/src/org/apache/poi/xslf/usermodel/DataExtraction.java deleted file mode 100644 index b7e08fc6f1..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/DataExtraction.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.openxml4j.opc.PackagePart; - -import java.awt.*; -import java.awt.geom.Rectangle2D; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.List; - -/** - * Demonstrates how you can extract data from a .pptx file - * - * @author Yegor Kozlov - */ -public final class DataExtraction { - - public static void main(String args[]) throws Exception { - - if (args.length == 0) { - System.out.println("Input file is required"); - return; - } - - FileInputStream is = new FileInputStream(args[0]); - XMLSlideShow ppt = new XMLSlideShow(is); - is.close(); - - // Get the document's embedded files. - List embeds = ppt.getAllEmbedds(); - for (PackagePart p : embeds) { - String type = p.getContentType(); - String name = p.getPartName().getName(); //typically file name - - InputStream pIs = p.getInputStream(); - // make sense of the part data - pIs.close(); - - } - - // Get the document's embedded files. - List images = ppt.getAllPictures(); - for (XSLFPictureData data : images) { - PackagePart p = data.getPackagePart(); - - String type = p.getContentType(); - String name = data.getFileName(); - - InputStream pIs = p.getInputStream(); - // make sense of the image data - pIs.close(); - - - - } - - Dimension pageSize = ppt.getPageSize(); // size of the canvas in points - for(XSLFSlide slide : ppt.getSlides()) { - for(XSLFShape shape : slide){ - Rectangle2D anchor = shape.getAnchor(); // position on the canvas - if(shape instanceof XSLFTextShape) { - XSLFTextShape txShape = (XSLFTextShape)shape; - System.out.println(txShape.getText()); - } else if (shape instanceof XSLFPictureShape){ - XSLFPictureShape pShape = (XSLFPictureShape)shape; - XSLFPictureData pData = pShape.getPictureData(); - System.out.println(pData.getFileName()); - } else { - System.out.println("Process me: " + shape.getClass()); - } - } - } - } - -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/MergePresentations.java b/src/examples/src/org/apache/poi/xslf/usermodel/MergePresentations.java deleted file mode 100644 index 994f94c259..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/MergePresentations.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.io.FileInputStream; -import java.io.FileOutputStream; - -/** - * Merge multiple pptx presentations together - * - * @author Yegor Kozlov - */ -public final class MergePresentations { - - public static void main(String args[]) throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - - for(String arg : args){ - FileInputStream is = new FileInputStream(arg); - XMLSlideShow src = new XMLSlideShow(is); - is.close(); - - for(XSLFSlide srcSlide : src.getSlides()){ - ppt.createSlide().importContent(srcSlide); - } - } - - FileOutputStream out = new FileOutputStream("merged.pptx"); - ppt.write(out); - out.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/PPTX2SVG.txt b/src/examples/src/org/apache/poi/xslf/usermodel/PPTX2SVG.txt deleted file mode 100644 index dbe089ac30..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/PPTX2SVG.txt +++ /dev/null @@ -1,176 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.batik.dom.svg.SVGDOMImplementation; -import org.apache.batik.svggen.SVGGraphics2D; -import org.apache.batik.transcoder.wmf.tosvg.WMFPainter; -import org.apache.batik.transcoder.wmf.tosvg.WMFRecordStore; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; - -import javax.imageio.ImageIO; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.DataInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; - -/** - * Convert each slide of a .pptx presentation into SVG - * - * @author Yegor Kozlov - */ -public class PPTX2SVG { - - static void usage() { - System.out.println("Usage: PPTX2SVG "); - } - - public static void main(String[] args) throws Exception { - if (args.length == 0) { - usage(); - return; - } - - String file = args[0]; - - System.out.println("Processing " + file); - - // read the .pptx file - XMLSlideShow ppt = new XMLSlideShow(OPCPackage.open(file)); - - Dimension pgsize = ppt.getPageSize(); - - // convert each slide into a .svg file - XSLFSlide[] slide = ppt.getSlides(); - for (int i = 0; i < slide.length; i++) { - // Create initial SVG DOM - DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation(); - Document doc = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null); - //Use Batik SVG Graphics2D driver - SVGGraphics2D graphics = new SVGGraphics2D(doc); - graphics.setRenderingHint(XSLFRenderingHint.IMAGE_RENDERER, new WMFImageRender()); - graphics.setSVGCanvasSize(pgsize); - - String title = slide[i].getTitle(); - System.out.println("Rendering slide " + (i + 1) + (title == null ? "" : ": " + title)); - - // draw stuff. All the heavy-lifting happens here - slide[i].draw(graphics); - - // save the result. - int sep = file.lastIndexOf("."); - String fname = file.substring(0, sep == -1 ? file.length() : sep) + "-" + (i + 1) + ".svg"; - OutputStreamWriter out = - new OutputStreamWriter(new FileOutputStream(fname), "UTF-8"); - DOMSource domSource = new DOMSource(graphics.getRoot()); - StreamResult streamResult = new StreamResult(out); - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer serializer = tf.newTransformer(); - serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - serializer.setOutputProperty(OutputKeys.INDENT, "yes"); - serializer.transform(domSource, streamResult); - out.flush(); - out.close(); - } - System.out.println("Done"); - } - - /** - * Image renderer with support for .wmf images - */ - static class WMFImageRender extends XSLFImageRendener { - - /** - * Use Apache Batik to render WMF, - * delegate all other types of images to the javax.imageio framework - */ - @Override - public boolean drawImage(Graphics2D graphics, XSLFPictureData data, - Rectangle2D anchor) { - try { - // see what type of image we are - PackagePart part = data.getPackagePart(); - String contentType = part.getContentType(); - if (contentType.equals("image/x-wmf")) { - WMFRecordStore currentStore = new WMFRecordStore(); - currentStore.read(new DataInputStream(part.getInputStream())); - int wmfwidth = currentStore.getWidthPixels(); - float conv = (float) anchor.getWidth() / wmfwidth; - - // Build a painter for the RecordStore - WMFPainter painter = new WMFPainter(currentStore, - (int) anchor.getX(), (int) anchor.getY(), conv); - painter.paint(graphics); - } else { - BufferedImage img = ImageIO.read(data.getPackagePart().getInputStream()); - graphics.drawImage(img, - (int) anchor.getX(), (int) anchor.getY(), - (int) anchor.getWidth(), (int) anchor.getHeight(), null); - } - } catch (Exception e) { - return false; - } - return true; - } - - /** - * Convert data form the supplied package part into a BufferedImage. - * This method is used to create texture paint. - */ - @Override - public BufferedImage readImage(PackagePart packagePart) throws IOException { - String contentType = packagePart.getContentType(); - if (contentType.equals("image/x-wmf")) { - try { - WMFRecordStore currentStore = new WMFRecordStore(); - currentStore.read(new DataInputStream(packagePart.getInputStream())); - int wmfwidth = currentStore.getWidthPixels(); - int wmfheight = currentStore.getHeightPixels(); - - BufferedImage img = new BufferedImage(wmfwidth, wmfheight, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = img.createGraphics(); - - // Build a painter for the RecordStore - WMFPainter painter = new WMFPainter(currentStore, 0, 0, 1.0f); - painter.paint(graphics); - - return img; - } catch (IOException e) { - return null; - } - } else { - return ImageIO.read(packagePart.getInputStream()); - } - } - - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/PieChartDemo.java b/src/examples/src/org/apache/poi/xslf/usermodel/PieChartDemo.java deleted file mode 100644 index f6e6a847d6..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/PieChartDemo.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieSer; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.OutputStream; - -/** - * Build a pie chart from a template pptx - * - * @author Yegor Kozlov - */ -public class PieChartDemo { - private static void usage(){ - System.out.println("Usage: PieChartDemo "); - System.out.println(" pie-chart-template.pptx template with a pie chart"); - System.out.println(" pie-chart-data.txt the model to set. First line is chart title, " + - "then go pairs {axis-label value}"); - } - - public static void main(String[] args) throws Exception { - if(args.length < 2) { - usage(); - return; - } - - BufferedReader modelReader = new BufferedReader(new FileReader(args[1])); - - String chartTitle = modelReader.readLine(); // first line is chart title - - XMLSlideShow pptx = new XMLSlideShow(new FileInputStream(args[0])); - XSLFSlide slide = pptx.getSlides()[0]; - - // find chart in the slide - XSLFChart chart = null; - for(POIXMLDocumentPart part : slide.getRelations()){ - if(part instanceof XSLFChart){ - chart = (XSLFChart) part; - break; - } - } - - if(chart == null) throw new IllegalStateException("chart not found in the template"); - - // embedded Excel workbook that holds the chart data - POIXMLDocumentPart xlsPart = chart.getRelations().get(0); - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - CTChart ctChart = chart.getCTChart(); - CTPlotArea plotArea = ctChart.getPlotArea(); - - CTPieChart pieChart = plotArea.getPieChartArray(0); - //Pie Chart Series - CTPieSer ser = pieChart.getSerArray(0); - - // Series Text - CTSerTx tx = ser.getTx(); - tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle); - sheet.createRow(0).createCell(1).setCellValue(chartTitle); - String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString(); - tx.getStrRef().setF(titleRef); - - - // Category Axis Data - CTAxDataSource cat = ser.getCat(); - CTStrData strData = cat.getStrRef().getStrCache(); - - // Values - CTNumDataSource val = ser.getVal(); - CTNumData numData = val.getNumRef().getNumCache(); - - strData.setPtArray(null); // unset old axis text - numData.setPtArray(null); // unset old values - - - // set model - int idx = 0; - int rownum = 1; - String ln; - while((ln = modelReader.readLine()) != null){ - String[] vals = ln.split("\\s+"); - CTNumVal numVal = numData.addNewPt(); - numVal.setIdx(idx); - numVal.setV(vals[1]); - - CTStrVal sVal = strData.addNewPt(); - sVal.setIdx(idx); - sVal.setV(vals[0]); - - idx++; - XSSFRow row = sheet.createRow(rownum++); - row.createCell(0).setCellValue(vals[0]); - row.createCell(1).setCellValue(Double.valueOf(vals[1])); - } - numData.getPtCount().setVal(idx); - strData.getPtCount().setVal(idx); - - String numDataRange = new CellRangeAddress(1, rownum-1, 1, 1).formatAsString(sheet.getSheetName(), true); - val.getNumRef().setF(numDataRange); - String axisDataRange = new CellRangeAddress(1, rownum-1, 0, 0).formatAsString(sheet.getSheetName(), true); - cat.getStrRef().setF(axisDataRange); - - // updated the embedded workbook with the data - OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream(); - wb.write(xlsOut); - xlsOut.close(); - - // save the result - FileOutputStream out = new FileOutputStream("pie-chart-demo-output.pptx"); - pptx.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial1.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial1.java deleted file mode 100644 index 726013d82c..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial1.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Demonstrates how to create slides with predefined layout - * and fill the placeholder shapes - * - * @author Yegor Kozlov - */ -public class Tutorial1 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - // XSLFSlide#createSlide() with no arguments creates a blank slide - XSLFSlide blankSlide = ppt.createSlide(); - - - XSLFSlideMaster master = ppt.getSlideMasters()[0]; - - XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE); - XSLFSlide slide1 = ppt.createSlide(layout1) ; - XSLFTextShape[] ph1 = slide1.getPlaceholders(); - XSLFTextShape titlePlaceholder1 = ph1[0]; - titlePlaceholder1.setText("This is a title"); - XSLFTextShape subtitlePlaceholder1 = ph1[1]; - subtitlePlaceholder1.setText("this is a subtitle"); - - XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT); - XSLFSlide slide2 = ppt.createSlide(layout2) ; - XSLFTextShape[] ph2 = slide2.getPlaceholders(); - XSLFTextShape titlePlaceholder2 = ph2[0]; - titlePlaceholder2.setText("This is a title"); - XSLFTextShape bodyPlaceholder = ph2[1]; - // we are going to add text by paragraphs. Clear the default placehoder text before that - bodyPlaceholder.clearText(); - XSLFTextParagraph p1 = bodyPlaceholder.addNewTextParagraph(); - p1.setLevel(0); - p1.addNewTextRun().setText("Level1 text"); - XSLFTextParagraph p2 = bodyPlaceholder.addNewTextParagraph(); - p2.setLevel(1); - p2.addNewTextRun().setText("Level2 text"); - XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph(); - p3.setLevel(3); - p3.addNewTextRun().setText("Level3 text"); - - FileOutputStream out = new FileOutputStream("slides.pptx"); - ppt.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial2.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial2.java deleted file mode 100644 index 373f01f33f..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial2.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.*; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Basic paragraph and text formatting - * - * @author Yegor Kozlov - */ -public class Tutorial2 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide1 = ppt.createSlide(); - XSLFTextBox shape1 = slide1.createTextBox(); - // initial height of the text box is 100 pt but - Rectangle anchor = new Rectangle(10, 100, 300, 100); - shape1.setAnchor(anchor); - - XSLFTextParagraph p1 = shape1.addNewTextParagraph(); - XSLFTextRun r1 = p1.addNewTextRun(); - r1.setText("Paragraph Formatting"); - r1.setFontSize(24); - r1.setFontColor(new Color(85, 142, 213)); - - XSLFTextParagraph p2 = shape1.addNewTextParagraph(); - // If spaceBefore >= 0, then space is a percentage of normal line height. - // If spaceBefore < 0, the absolute value of linespacing is the spacing in points - p2.setSpaceBefore(-20); // 20 pt from the previous paragraph - p2.setSpaceAfter(300); // 3 lines after the paragraph - XSLFTextRun r2 = p2.addNewTextRun(); - r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph."); - r2.setFontSize(16); - - XSLFTextParagraph p3 = shape1.addNewTextParagraph(); - - XSLFTextRun r3 = p3.addNewTextRun(); - r3.setText("Run Formatting"); - r3.setFontSize(24); - r3.setFontColor(new Color(85, 142, 213)); - - XSLFTextParagraph p4 = shape1.addNewTextParagraph(); - p4.setSpaceBefore(-20); // 20 pt from the previous paragraph - p4.setSpaceAfter(300); // 3 lines after the paragraph - XSLFTextRun r4 = p4.addNewTextRun(); - r4.setFontSize(16); - r4.setText( - "Run level formatting is the most granular property level and allows " + - "for the specifying of all low level text properties. The text run is " + - "what all paragraphs are derived from and thus specifying various " + - "properties per run will allow for a diversely formatted text paragraph."); - - // resize the shape to fit text - shape1.resizeToFitText(); - - FileOutputStream out = new FileOutputStream("text.pptx"); - ppt.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial3.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial3.java deleted file mode 100644 index a5e01387da..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial3.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.*; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * How to set slide title - * - * @author Yegor Kozlov - */ -public class Tutorial3 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide = ppt.createSlide(); - - XSLFTextShape titleShape = slide.createTextBox(); - titleShape.setPlaceholder(Placeholder.TITLE); - titleShape.setText("This is a slide title"); - titleShape.setAnchor(new Rectangle(50, 50, 400, 100)); - - FileOutputStream out = new FileOutputStream("title.pptx"); - ppt.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial4.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial4.java deleted file mode 100644 index ea4fba320c..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial4.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.*; -import java.awt.geom.Rectangle2D; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * PPTX Tables - * - * @author Yegor Kozlov - */ -public class Tutorial4 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - // XSLFSlide#createSlide() with no arguments creates a blank slide - XSLFSlide slide = ppt.createSlide(); - - XSLFTable tbl = slide.createTable(); - tbl.setAnchor(new Rectangle2D.Double(50, 50, 450, 300)); - - int numColumns = 3; - int numRows = 5; - XSLFTableRow headerRow = tbl.addRow(); - headerRow.setHeight(50); - // header - for(int i = 0; i < numColumns; i++) { - XSLFTableCell th = headerRow.addCell(); - XSLFTextParagraph p = th.addNewTextParagraph(); - p.setTextAlign(TextAlign.CENTER); - XSLFTextRun r = p.addNewTextRun(); - r.setText("Header " + (i+1)); - r.setBold(true); - r.setFontColor(Color.white); - th.setFillColor(new Color(79, 129, 189)); - th.setBorderBottom(2); - th.setBorderBottomColor(Color.white); - - tbl.setColumnWidth(i, 150); // all columns are equally sized - } - - // rows - - for(int rownum = 0; rownum < numRows; rownum ++){ - XSLFTableRow tr = tbl.addRow(); - tr.setHeight(50); - // header - for(int i = 0; i < numColumns; i++) { - XSLFTableCell cell = tr.addCell(); - XSLFTextParagraph p = cell.addNewTextParagraph(); - XSLFTextRun r = p.addNewTextRun(); - - r.setText("Cell " + (i+1)); - if(rownum % 2 == 0) - cell.setFillColor(new Color(208, 216, 232)); - else - cell.setFillColor(new Color(233, 247, 244)); - - } - - } - - - FileOutputStream out = new FileOutputStream("table.pptx"); - ppt.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial5.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial5.java deleted file mode 100644 index 607248a753..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial5.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.util.IOUtils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Images - * - * @author Yegor Kozlov - */ -public class Tutorial5 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide = ppt.createSlide(); - File img = new File(System.getProperty("POI.testdata.path"), "slideshow/clock.jpg"); - byte[] data = IOUtils.toByteArray(new FileInputStream(img)); - int pictureIndex = ppt.addPicture(data, XSLFPictureData.PICTURE_TYPE_PNG); - - XSLFPictureShape shape = slide.createPicture(pictureIndex); - - FileOutputStream out = new FileOutputStream("images.pptx"); - ppt.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial6.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial6.java deleted file mode 100644 index fc278cbe90..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial6.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.*; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Hyperlinks - * - * @author Yegor Kozlov - */ -public class Tutorial6 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide1 = ppt.createSlide(); - XSLFSlide slide2 = ppt.createSlide(); - - XSLFTextBox shape1 = slide1.createTextBox(); - shape1.setAnchor(new Rectangle(50, 50, 200, 50)); - XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun(); - XSLFHyperlink link1 = r1.createHyperlink(); - r1.setText("http://poi.apache.org"); // visible text - link1.setAddress("http://poi.apache.org"); // link address - - XSLFTextBox shape2 = slide1.createTextBox(); - shape2.setAnchor(new Rectangle(300, 50, 200, 50)); - XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun(); - XSLFHyperlink link2 = r2.createHyperlink(); - r2.setText("Go to the second slide"); // visible text - link2.setAddress(slide2); // link address - - - - FileOutputStream out = new FileOutputStream("hyperlinks.pptx"); - ppt.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial7.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial7.java deleted file mode 100644 index a80f23cad7..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial7.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.*; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Bullets and numbering - * - * @author Yegor Kozlov - */ -public class Tutorial7 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide = ppt.createSlide(); - XSLFTextBox shape = slide.createTextBox(); - shape.setAnchor(new Rectangle(50, 50, 400, 200)); - - XSLFTextParagraph p1 = shape.addNewTextParagraph(); - p1.setLevel(0); - p1.setBullet(true); - XSLFTextRun r1 = p1.addNewTextRun(); - r1.setText("Bullet1"); - - XSLFTextParagraph p2 = shape.addNewTextParagraph(); - // indentation before text - p2.setLeftMargin(60); - // the bullet is set 40 pt before the text - p2.setIndent(-40); - p2.setBullet(true); - // customize bullets - p2.setBulletFontColor(Color.red); - p2.setBulletFont("Wingdings"); - p2.setBulletCharacter("\u0075"); - p2.setLevel(1); - XSLFTextRun r2 = p2.addNewTextRun(); - r2.setText("Bullet2"); - - // the next three paragraphs form an auto-numbered list - XSLFTextParagraph p3 = shape.addNewTextParagraph(); - p3.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 1); - p3.setLevel(2); - XSLFTextRun r3 = p3.addNewTextRun(); - r3.setText("Numbered List Item - 1"); - - XSLFTextParagraph p4 = shape.addNewTextParagraph(); - p4.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 2); - p4.setLevel(2); - XSLFTextRun r4 = p4.addNewTextRun(); - r4.setText("Numbered List Item - 2"); - - XSLFTextParagraph p5 = shape.addNewTextParagraph(); - p5.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 3); - p5.setLevel(2); - XSLFTextRun r5 = p5.addNewTextRun(); - r5.setText("Numbered List Item - 3"); - - shape.resizeToFitText(); - - FileOutputStream out = new FileOutputStream("list.pptx"); - ppt.write(out); - out.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-data.txt b/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-data.txt deleted file mode 100644 index 40b6959c2c..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-data.txt +++ /dev/null @@ -1,4 +0,0 @@ -My Chart -First 1.0 -Second 3.0 -Third 4.0 \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-template.pptx b/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-template.pptx deleted file mode 100644 index 33d28e154c..0000000000 Binary files a/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-template.pptx and /dev/null differ diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step1.java b/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step1.java deleted file mode 100644 index a83a17e4b8..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step1.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel.tutorial; - -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFShape; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFTextParagraph; -import org.apache.poi.xslf.usermodel.XSLFTextRun; -import org.apache.poi.xslf.usermodel.XSLFTextShape; - -import java.io.FileInputStream; - -/** - * Reading a .pptx presentation and printing basic shape properties - * - * @author Yegor Kozlov - */ -public class Step1 { - - public static void main(String[] args) throws Exception { - if(args.length == 0) { - System.out.println("Input file is required"); - return; - } - - XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(args[0])); - - for(XSLFSlide slide : ppt.getSlides()){ - System.out.println("Title: " + slide.getTitle()); - - for(XSLFShape shape : slide.getShapes()){ - if(shape instanceof XSLFTextShape) { - XSLFTextShape tsh = (XSLFTextShape)shape; - for(XSLFTextParagraph p : tsh){ - System.out.println("Paragraph level: " + p.getLevel()); - for(XSLFTextRun r : p){ - System.out.println(r.getText()); - System.out.println(" bold: " + r.isBold()); - System.out.println(" italic: " + r.isItalic()); - System.out.println(" underline: " + r.isUnderline()); - System.out.println(" font.family: " + r.getFontFamily()); - System.out.println(" font.size: " + r.getFontSize()); - System.out.println(" font.color: " + r.getFontColor()); - } - } - } - } - } - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step2.java b/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step2.java deleted file mode 100644 index 16b155d3f2..0000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step2.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel.tutorial; - -import org.apache.poi.xslf.usermodel.SlideLayout; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFSlideLayout; -import org.apache.poi.xslf.usermodel.XSLFSlideMaster; -import org.apache.poi.xslf.usermodel.XSLFTextShape; - -import java.io.FileOutputStream; - -/** - * Create slides from pre-defined slide layouts - * - * @author Yegor Kozlov - */ -public class Step2 { - public static void main(String[] args) throws Exception{ - XMLSlideShow ppt = new XMLSlideShow(); - - - // first see what slide layouts are available by default - System.out.println("Available slide layouts:"); - for(XSLFSlideMaster master : ppt.getSlideMasters()){ - for(XSLFSlideLayout layout : master.getSlideLayouts()){ - System.out.println(layout.getType()); - } - } - - // blank slide - XSLFSlide blankSlide = ppt.createSlide(); - - XSLFSlideMaster defaultMaster = ppt.getSlideMasters()[0]; - - // title slide - XSLFSlideLayout titleLayout = defaultMaster.getLayout(SlideLayout.TITLE); - XSLFSlide slide1 = ppt.createSlide(titleLayout); - XSLFTextShape title1 = slide1.getPlaceholder(0); - title1.setText("First Title"); - - // title and content - XSLFSlideLayout titleBodyLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); - XSLFSlide slide2 = ppt.createSlide(titleBodyLayout); - - XSLFTextShape title2 = slide2.getPlaceholder(0); - title2.setText("Second Title"); - - XSLFTextShape body2 = slide2.getPlaceholder(1); - body2.clearText(); // unset any existing text - body2.addNewTextParagraph().addNewTextRun().setText("First paragraph"); - body2.addNewTextParagraph().addNewTextRun().setText("Second paragraph"); - body2.addNewTextParagraph().addNewTextRun().setText("Third paragraph"); - - - - FileOutputStream out = new FileOutputStream("step2.pptx"); - ppt.write(out); - out.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java b/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java deleted file mode 100644 index 892c3bb2bc..0000000000 --- a/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java +++ /dev/null @@ -1,424 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.eventusermodel; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; - -/** - * A rudimentary XLSX -> CSV processor modeled on the - * POI sample program XLS2CSVmra by Nick Burch from the - * package org.apache.poi.hssf.eventusermodel.examples. - * Unlike the HSSF version, this one completely ignores - * missing rows. - *

      - * Data sheets are read using a SAX parser to keep the - * memory footprint relatively small, so this should be - * able to read enormous workbooks. The styles table and - * the shared-string table must be kept in memory. The - * standard POI styles table class is used, but a custom - * (read-only) class is used for the shared string table - * because the standard POI SharedStringsTable grows very - * quickly with the number of unique strings. - *

      - * Thanks to Eric Smith for a patch that fixes a problem - * triggered by cells with multiple "t" elements, which is - * how Excel represents different formats (e.g., one word - * plain and one word bold). - * - * @author Chris Lott - */ -public class XLSX2CSV { - - /** - * The type of the data value is indicated by an attribute on the cell. - * The value is usually in a "v" element within the cell. - */ - enum xssfDataType { - BOOL, - ERROR, - FORMULA, - INLINESTR, - SSTINDEX, - NUMBER, - } - - - /** - * Derived from http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api - *

      - * Also see Standard ECMA-376, 1st edition, part 4, pages 1928ff, at - * http://www.ecma-international.org/publications/standards/Ecma-376.htm - *

      - * A web-friendly version is http://openiso.org/Ecma/376/Part4 - */ - class MyXSSFSheetHandler extends DefaultHandler { - - /** - * Table with styles - */ - private StylesTable stylesTable; - - /** - * Table with unique strings - */ - private ReadOnlySharedStringsTable sharedStringsTable; - - /** - * Destination for data - */ - private final PrintStream output; - - /** - * Number of columns to read starting with leftmost - */ - private final int minColumnCount; - - // Set when V start element is seen - private boolean vIsOpen; - - // Set when cell start element is seen; - // used when cell close element is seen. - private xssfDataType nextDataType; - - // Used to format numeric cell values. - private short formatIndex; - private String formatString; - private final DataFormatter formatter; - - private int thisColumn = -1; - // The last column printed to the output stream - private int lastColumnNumber = -1; - - // Gathers characters as they are seen. - private StringBuffer value; - - /** - * Accepts objects needed while parsing. - * - * @param styles Table of styles - * @param strings Table of shared strings - * @param cols Minimum number of columns to show - * @param target Sink for output - */ - public MyXSSFSheetHandler( - StylesTable styles, - ReadOnlySharedStringsTable strings, - int cols, - PrintStream target) { - this.stylesTable = styles; - this.sharedStringsTable = strings; - this.minColumnCount = cols; - this.output = target; - this.value = new StringBuffer(); - this.nextDataType = xssfDataType.NUMBER; - this.formatter = new DataFormatter(); - } - - /* - * (non-Javadoc) - * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) - */ - public void startElement(String uri, String localName, String name, - Attributes attributes) throws SAXException { - - if ("inlineStr".equals(name) || "v".equals(name)) { - vIsOpen = true; - // Clear contents cache - value.setLength(0); - } - // c => cell - else if ("c".equals(name)) { - // Get the cell reference - String r = attributes.getValue("r"); - int firstDigit = -1; - for (int c = 0; c < r.length(); ++c) { - if (Character.isDigit(r.charAt(c))) { - firstDigit = c; - break; - } - } - thisColumn = nameToColumn(r.substring(0, firstDigit)); - - // Set up defaults. - this.nextDataType = xssfDataType.NUMBER; - this.formatIndex = -1; - this.formatString = null; - String cellType = attributes.getValue("t"); - String cellStyleStr = attributes.getValue("s"); - if ("b".equals(cellType)) - nextDataType = xssfDataType.BOOL; - else if ("e".equals(cellType)) - nextDataType = xssfDataType.ERROR; - else if ("inlineStr".equals(cellType)) - nextDataType = xssfDataType.INLINESTR; - else if ("s".equals(cellType)) - nextDataType = xssfDataType.SSTINDEX; - else if ("str".equals(cellType)) - nextDataType = xssfDataType.FORMULA; - else if (cellStyleStr != null) { - // It's a number, but almost certainly one - // with a special style or format - int styleIndex = Integer.parseInt(cellStyleStr); - XSSFCellStyle style = stylesTable.getStyleAt(styleIndex); - this.formatIndex = style.getDataFormat(); - this.formatString = style.getDataFormatString(); - if (this.formatString == null) - this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex); - } - } - - } - - /* - * (non-Javadoc) - * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) - */ - public void endElement(String uri, String localName, String name) - throws SAXException { - - String thisStr = null; - - // v => contents of a cell - if ("v".equals(name)) { - // Process the value contents as required. - // Do now, as characters() may be called more than once - switch (nextDataType) { - - case BOOL: - char first = value.charAt(0); - thisStr = first == '0' ? "FALSE" : "TRUE"; - break; - - case ERROR: - thisStr = "\"ERROR:" + value.toString() + '"'; - break; - - case FORMULA: - // A formula could result in a string value, - // so always add double-quote characters. - thisStr = '"' + value.toString() + '"'; - break; - - case INLINESTR: - // TODO: have seen an example of this, so it's untested. - XSSFRichTextString rtsi = new XSSFRichTextString(value.toString()); - thisStr = '"' + rtsi.toString() + '"'; - break; - - case SSTINDEX: - String sstIndex = value.toString(); - try { - int idx = Integer.parseInt(sstIndex); - XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); - thisStr = '"' + rtss.toString() + '"'; - } - catch (NumberFormatException ex) { - output.println("Failed to parse SST index '" + sstIndex + "': " + ex.toString()); - } - break; - - case NUMBER: - String n = value.toString(); - if (this.formatString != null) - thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString); - else - thisStr = n; - break; - - default: - thisStr = "(TODO: Unexpected type: " + nextDataType + ")"; - break; - } - - // Output after we've seen the string contents - // Emit commas for any fields that were missing on this row - if (lastColumnNumber == -1) { - lastColumnNumber = 0; - } - for (int i = lastColumnNumber; i < thisColumn; ++i) - output.print(','); - - // Might be the empty string. - output.print(thisStr); - - // Update column - if (thisColumn > -1) - lastColumnNumber = thisColumn; - - } else if ("row".equals(name)) { - - // Print out any missing commas if needed - if (minColumns > 0) { - // Columns are 0 based - if (lastColumnNumber == -1) { - lastColumnNumber = 0; - } - for (int i = lastColumnNumber; i < (this.minColumnCount); i++) { - output.print(','); - } - } - - // We're onto a new row - output.println(); - lastColumnNumber = -1; - } - - } - - /** - * Captures characters only if a suitable element is open. - * Originally was just "v"; extended for inlineStr also. - */ - public void characters(char[] ch, int start, int length) - throws SAXException { - if (vIsOpen) - value.append(ch, start, length); - } - - /** - * Converts an Excel column name like "C" to a zero-based index. - * - * @param name - * @return Index corresponding to the specified name - */ - private int nameToColumn(String name) { - int column = -1; - for (int i = 0; i < name.length(); ++i) { - int c = name.charAt(i); - column = (column + 1) * 26 + c - 'A'; - } - return column; - } - - } - - /////////////////////////////////////// - - private OPCPackage xlsxPackage; - private int minColumns; - private PrintStream output; - - /** - * Creates a new XLSX -> CSV converter - * - * @param pkg The XLSX package to process - * @param output The PrintStream to output the CSV to - * @param minColumns The minimum number of columns to output, or -1 for no minimum - */ - public XLSX2CSV(OPCPackage pkg, PrintStream output, int minColumns) { - this.xlsxPackage = pkg; - this.output = output; - this.minColumns = minColumns; - } - - /** - * Parses and shows the content of one sheet - * using the specified styles and shared-strings tables. - * - * @param styles - * @param strings - * @param sheetInputStream - */ - public void processSheet( - StylesTable styles, - ReadOnlySharedStringsTable strings, - InputStream sheetInputStream) - throws IOException, ParserConfigurationException, SAXException { - - InputSource sheetSource = new InputSource(sheetInputStream); - SAXParserFactory saxFactory = SAXParserFactory.newInstance(); - SAXParser saxParser = saxFactory.newSAXParser(); - XMLReader sheetParser = saxParser.getXMLReader(); - ContentHandler handler = new MyXSSFSheetHandler(styles, strings, this.minColumns, this.output); - sheetParser.setContentHandler(handler); - sheetParser.parse(sheetSource); - } - - /** - * Initiates the processing of the XLS workbook file to CSV. - * - * @throws IOException - * @throws OpenXML4JException - * @throws ParserConfigurationException - * @throws SAXException - */ - public void process() - throws IOException, OpenXML4JException, ParserConfigurationException, SAXException { - - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage); - XSSFReader xssfReader = new XSSFReader(this.xlsxPackage); - StylesTable styles = xssfReader.getStylesTable(); - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); - int index = 0; - while (iter.hasNext()) { - InputStream stream = iter.next(); - String sheetName = iter.getSheetName(); - this.output.println(); - this.output.println(sheetName + " [index=" + index + "]:"); - processSheet(styles, strings, stream); - stream.close(); - ++index; - } - } - - public static void main(String[] args) throws Exception { - if (args.length < 1) { - System.err.println("Use:"); - System.err.println(" XLSX2CSV [min columns]"); - return; - } - - File xlsxFile = new File(args[0]); - if (!xlsxFile.exists()) { - System.err.println("Not found or not a file: " + xlsxFile.getPath()); - return; - } - - int minColumns = -1; - if (args.length >= 2) - minColumns = Integer.parseInt(args[1]); - - // The package open is instantaneous, as it should be. - OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ); - XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns); - xlsx2csv.process(); - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/FromHowTo.java b/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/FromHowTo.java deleted file mode 100644 index fc6604c649..0000000000 --- a/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/FromHowTo.java +++ /dev/null @@ -1,138 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.eventusermodel.examples; - -import java.io.InputStream; -import java.util.Iterator; - -import org.apache.poi.xssf.eventusermodel.XSSFReader; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * XSSF and SAX (Event API) - */ -public class FromHowTo { - public void processOneSheet(String filename) throws Exception { - OPCPackage pkg = OPCPackage.open(filename); - XSSFReader r = new XSSFReader( pkg ); - SharedStringsTable sst = r.getSharedStringsTable(); - - XMLReader parser = fetchSheetParser(sst); - - // rId2 found by processing the Workbook - // Seems to either be rId# or rSheet# - InputStream sheet2 = r.getSheet("rId2"); - InputSource sheetSource = new InputSource(sheet2); - parser.parse(sheetSource); - sheet2.close(); - } - - public void processAllSheets(String filename) throws Exception { - OPCPackage pkg = OPCPackage.open(filename); - XSSFReader r = new XSSFReader( pkg ); - SharedStringsTable sst = r.getSharedStringsTable(); - - XMLReader parser = fetchSheetParser(sst); - - Iterator sheets = r.getSheetsData(); - while(sheets.hasNext()) { - System.out.println("Processing new sheet:\n"); - InputStream sheet = sheets.next(); - InputSource sheetSource = new InputSource(sheet); - parser.parse(sheetSource); - sheet.close(); - System.out.println(""); - } - } - - public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException { - XMLReader parser = - XMLReaderFactory.createXMLReader( - "org.apache.xerces.parsers.SAXParser" - ); - ContentHandler handler = new SheetHandler(sst); - parser.setContentHandler(handler); - return parser; - } - - /** - * See org.xml.sax.helpers.DefaultHandler javadocs - */ - private static class SheetHandler extends DefaultHandler { - private SharedStringsTable sst; - private String lastContents; - private boolean nextIsString; - - private SheetHandler(SharedStringsTable sst) { - this.sst = sst; - } - - public void startElement(String uri, String localName, String name, - Attributes attributes) throws SAXException { - // c => cell - if(name.equals("c")) { - // Print the cell reference - System.out.print(attributes.getValue("r") + " - "); - // Figure out if the value is an index in the SST - String cellType = attributes.getValue("t"); - if(cellType != null && cellType.equals("s")) { - nextIsString = true; - } else { - nextIsString = false; - } - } - // Clear contents cache - lastContents = ""; - } - - public void endElement(String uri, String localName, String name) - throws SAXException { - // Process the last contents as required. - // Do now, as characters() may be called more than once - if(nextIsString) { - int idx = Integer.parseInt(lastContents); - lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); - } - - // v => contents of a cell - // Output after we've seen the string contents - if(name.equals("v")) { - System.out.println(lastContents); - } - } - - public void characters(char[] ch, int start, int length) - throws SAXException { - lastContents += new String(ch, start, length); - } - } - - public static void main(String[] args) throws Exception { - FromHowTo howto = new FromHowTo(); - howto.processOneSheet(args[0]); - howto.processAllSheets(args[0]); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/streaming/examples/Outlining.java b/src/examples/src/org/apache/poi/xssf/streaming/examples/Outlining.java deleted file mode 100644 index 03af09ddda..0000000000 --- a/src/examples/src/org/apache/poi/xssf/streaming/examples/Outlining.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; - -public class Outlining { - - public static void main(String[] args) throws Exception { - Outlining o = new Outlining(); - o.collapseRow(); - } - - private void collapseRow() throws Exception { - SXSSFWorkbook wb2 = new SXSSFWorkbook(100); - SXSSFSheet sheet2 = (SXSSFSheet) wb2.createSheet("new sheet"); - - int rowCount = 20; - for (int i = 0; i < rowCount; i++) { - sheet2.createRow(i); - } - - sheet2.groupRow(4, 9); - sheet2.groupRow(11, 19); - - sheet2.setRowGroupCollapsed(4, true); - - FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx"); - wb2.write(fileOut); - fileOut.close(); - wb2.dispose(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/AligningCells.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/AligningCells.java deleted file mode 100644 index 6ed76081b1..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/AligningCells.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.*; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl; - -/** - * Shows how various alignment options work. - * - * Modified by Cristian Petrula, Romania on May 26, 2010 - * New method was added centerAcrossSelection to center a column content over - * one selection using ALIGN_CENTER_SELECTION - * To create this method example was change for XSSF only and the previous - * AligningCells.java example has been moved into the SS examples folder. - */ -public class AligningCells { - - public static void main(String[] args) throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow((short) 2); - row.setHeightInPoints(30); - for (int i = 0; i < 8; i++) { - //column width is set in units of 1/256th of a character width - sheet.setColumnWidth(i, 256 * 15); - } - - createCell(wb, row, (short) 0, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_BOTTOM); - createCell(wb, row, (short) 1, XSSFCellStyle.ALIGN_CENTER_SELECTION, XSSFCellStyle.VERTICAL_BOTTOM); - createCell(wb, row, (short) 2, XSSFCellStyle.ALIGN_FILL, XSSFCellStyle.VERTICAL_CENTER); - createCell(wb, row, (short) 3, XSSFCellStyle.ALIGN_GENERAL, XSSFCellStyle.VERTICAL_CENTER); - createCell(wb, row, (short) 4, XSSFCellStyle.ALIGN_JUSTIFY, XSSFCellStyle.VERTICAL_JUSTIFY); - createCell(wb, row, (short) 5, XSSFCellStyle.ALIGN_LEFT, XSSFCellStyle.VERTICAL_TOP); - createCell(wb, row, (short) 6, XSSFCellStyle.ALIGN_RIGHT, XSSFCellStyle.VERTICAL_TOP); - - //center text over B4, C4, D4 - row = sheet.createRow((short) 3); - centerAcrossSelection(wb, row, (short) 1, (short) 3, XSSFCellStyle.VERTICAL_CENTER); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("xssf-align.xlsx"); - wb.write(fileOut); - fileOut.close(); - } - - /** - * Creates a cell and aligns it a certain way. - * - * @param wb the workbook - * @param row the row to create the cell in - * @param column the column number to create the cell in - * @param halign the horizontal alignment for the cell. - */ - private static void createCell(XSSFWorkbook wb, XSSFRow row, short column, - short halign, short valign) { - XSSFCell cell = row.createCell(column); - cell.setCellValue(new XSSFRichTextString("Align It")); - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setAlignment(halign); - cellStyle.setVerticalAlignment(valign); - cell.setCellStyle(cellStyle); - } - - /** - * Center a text over multiple columns using ALIGN_CENTER_SELECTION - * - * @param wb the workbook - * @param row the row to create the cell in - * @param start_column the column number to create the cell in and where the selection starts - * @param end_column the column number where the selection ends - * @param valign the horizontal alignment for the cell. - * - * @author Cristian Petrula, Romania - */ - private static void centerAcrossSelection(XSSFWorkbook wb, XSSFRow row, - short start_column, short end_column, short valign) { - - // Create cell style with ALIGN_CENTER_SELECTION - XSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION); - cellStyle.setVerticalAlignment(valign); - - // Create cells over the selected area - for (int i = start_column; i <= end_column; i++) { - XSSFCell cell = row.createCell(i); - cell.setCellStyle(cellStyle); - } - - // Set value to the first cell - XSSFCell cell = row.getCell(start_column); - cell.setCellValue(new XSSFRichTextString("Align It")); - - // Make the selection - CTRowImpl ctRow = (CTRowImpl) row.getCTRow(); - List spanList = new ArrayList(); - - // Add object with format start_coll:end_coll. For example 1:3 will span from - // cell 1 to cell 3, where the column index starts with 0 - // - // You can add multiple spans for one row - Object span = start_column + ":" + end_column; - spanList.add(span); - - //add spns to the row - ctRow.setSpans(spanList); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java deleted file mode 100644 index 00c5342746..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java +++ /dev/null @@ -1,269 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.*; -import java.util.*; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; - -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.*; - -/** - * Demonstrates a workaround you can use to generate large workbooks and avoid OutOfMemory exception. - * - * The trick is as follows: - * 1. create a template workbook, create sheets and global objects such as cell styles, number formats, etc. - * 2. create an application that streams data in a text file - * 3. Substitute the sheet in the template with the generated data - * - *

      - * Since 3.8-beta3 POI provides a low-memory footprint SXSSF API which implementing the "BigGridDemo" strategy. - * XSSF is an API-compatible streaming extension of XSSF to be used when - * very large spreadsheets have to be produced, and heap space is limited. - * SXSSF achieves its low memory footprint by limiting access to the rows that - * are within a sliding window, while XSSF gives access to all rows in the - * document. Older rows that are no longer in the window become inaccessible, - * as they are written to the disk. - *

      - * See - * http://poi.apache.org/spreadsheet/how-to.html#sxssf. - - * - * @author Yegor Kozlov - */ -public class BigGridDemo { - private static final String XML_ENCODING = "UTF-8"; - - public static void main(String[] args) throws Exception { - - // Step 1. Create a template file. Setup sheets and workbook-level objects such as - // cell styles, number formats, etc. - - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Big Grid"); - - Map styles = createStyles(wb); - //name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml - String sheetRef = sheet.getPackagePart().getPartName().getName(); - - //save the template - FileOutputStream os = new FileOutputStream("template.xlsx"); - wb.write(os); - os.close(); - - //Step 2. Generate XML file. - File tmp = File.createTempFile("sheet", ".xml"); - Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING); - generate(fw, styles); - fw.close(); - - //Step 3. Substitute the template entry with the generated data - FileOutputStream out = new FileOutputStream("big-grid.xlsx"); - substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out); - out.close(); - } - - /** - * Create a library of cell styles. - */ - private static Map createStyles(XSSFWorkbook wb){ - Map styles = new HashMap(); - XSSFDataFormat fmt = wb.createDataFormat(); - - XSSFCellStyle style1 = wb.createCellStyle(); - style1.setAlignment(XSSFCellStyle.ALIGN_RIGHT); - style1.setDataFormat(fmt.getFormat("0.0%")); - styles.put("percent", style1); - - XSSFCellStyle style2 = wb.createCellStyle(); - style2.setAlignment(XSSFCellStyle.ALIGN_CENTER); - style2.setDataFormat(fmt.getFormat("0.0X")); - styles.put("coeff", style2); - - XSSFCellStyle style3 = wb.createCellStyle(); - style3.setAlignment(XSSFCellStyle.ALIGN_RIGHT); - style3.setDataFormat(fmt.getFormat("$#,##0.00")); - styles.put("currency", style3); - - XSSFCellStyle style4 = wb.createCellStyle(); - style4.setAlignment(XSSFCellStyle.ALIGN_RIGHT); - style4.setDataFormat(fmt.getFormat("mmm dd")); - styles.put("date", style4); - - XSSFCellStyle style5 = wb.createCellStyle(); - XSSFFont headerFont = wb.createFont(); - headerFont.setBold(true); - style5.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style5.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); - style5.setFont(headerFont); - styles.put("header", style5); - - return styles; - } - - private static void generate(Writer out, Map styles) throws Exception { - - Random rnd = new Random(); - Calendar calendar = Calendar.getInstance(); - - SpreadsheetWriter sw = new SpreadsheetWriter(out); - sw.beginSheet(); - - //insert header row - sw.insertRow(0); - int styleIndex = styles.get("header").getIndex(); - sw.createCell(0, "Title", styleIndex); - sw.createCell(1, "% Change", styleIndex); - sw.createCell(2, "Ratio", styleIndex); - sw.createCell(3, "Expenses", styleIndex); - sw.createCell(4, "Date", styleIndex); - - sw.endRow(); - - //write data rows - for (int rownum = 1; rownum < 100000; rownum++) { - sw.insertRow(rownum); - - sw.createCell(0, "Hello, " + rownum + "!"); - sw.createCell(1, (double)rnd.nextInt(100)/100, styles.get("percent").getIndex()); - sw.createCell(2, (double)rnd.nextInt(10)/10, styles.get("coeff").getIndex()); - sw.createCell(3, rnd.nextInt(10000), styles.get("currency").getIndex()); - sw.createCell(4, calendar, styles.get("date").getIndex()); - - sw.endRow(); - - calendar.roll(Calendar.DAY_OF_YEAR, 1); - } - sw.endSheet(); - } - - /** - * - * @param zipfile the template file - * @param tmpfile the XML file with the sheet data - * @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml - * @param out the stream to write the result to - */ - private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException { - ZipFile zip = new ZipFile(zipfile); - - ZipOutputStream zos = new ZipOutputStream(out); - - @SuppressWarnings("unchecked") - Enumeration en = (Enumeration) zip.entries(); - while (en.hasMoreElements()) { - ZipEntry ze = en.nextElement(); - if(!ze.getName().equals(entry)){ - zos.putNextEntry(new ZipEntry(ze.getName())); - InputStream is = zip.getInputStream(ze); - copyStream(is, zos); - is.close(); - } - } - zos.putNextEntry(new ZipEntry(entry)); - InputStream is = new FileInputStream(tmpfile); - copyStream(is, zos); - is.close(); - - zos.close(); - } - - private static void copyStream(InputStream in, OutputStream out) throws IOException { - byte[] chunk = new byte[1024]; - int count; - while ((count = in.read(chunk)) >=0 ) { - out.write(chunk,0,count); - } - } - - /** - * Writes spreadsheet data in a Writer. - * (YK: in future it may evolve in a full-featured API for streaming data in Excel) - */ - public static class SpreadsheetWriter { - private final Writer _out; - private int _rownum; - - public SpreadsheetWriter(Writer out){ - _out = out; - } - - public void beginSheet() throws IOException { - _out.write("" + - "" ); - _out.write("\n"); - } - - public void endSheet() throws IOException { - _out.write(""); - _out.write(""); - } - - /** - * Insert a new row - * - * @param rownum 0-based row number - */ - public void insertRow(int rownum) throws IOException { - _out.write("\n"); - this._rownum = rownum; - } - - /** - * Insert row end marker - */ - public void endRow() throws IOException { - _out.write("\n"); - } - - public void createCell(int columnIndex, String value, int styleIndex) throws IOException { - String ref = new CellReference(_rownum, columnIndex).formatAsString(); - _out.write(""); - _out.write(""+value+""); - _out.write(""); - } - - public void createCell(int columnIndex, String value) throws IOException { - createCell(columnIndex, value, -1); - } - - public void createCell(int columnIndex, double value, int styleIndex) throws IOException { - String ref = new CellReference(_rownum, columnIndex).formatAsString(); - _out.write(""); - _out.write(""+value+""); - _out.write(""); - } - - public void createCell(int columnIndex, double value) throws IOException { - createCell(columnIndex, value, -1); - } - - public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException { - createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex); - } - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CalendarDemo.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CalendarDemo.java deleted file mode 100644 index d8baaceda5..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CalendarDemo.java +++ /dev/null @@ -1,228 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.usermodel.*; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Map; -import java.util.HashMap; - -/** - * A monthly calendar created using Apache POI. Each month is on a separate sheet. - * This is a version of org.apache.poi.ss.examples.CalendarDemo that demonstrates - * some XSSF features not avaiable when using common HSSF-XSSF interfaces. - * - *
      - * Usage:
      - * CalendarDemo 
      - * 
      - * - * @author Yegor Kozlov - */ -public class CalendarDemo { - - private static final String[] days = { - "Sunday", "Monday", "Tuesday", - "Wednesday", "Thursday", "Friday", "Saturday"}; - - private static final String[] months = { - "January", "February", "March","April", "May", "June","July", "August", - "September","October", "November", "December"}; - - public static void main(String[] args) throws Exception { - - Calendar calendar = Calendar.getInstance(); - if(args.length > 0) calendar.set(Calendar.YEAR, Integer.parseInt(args[0])); - - int year = calendar.get(Calendar.YEAR); - - XSSFWorkbook wb = new XSSFWorkbook(); - Map styles = createStyles(wb); - - for (int month = 0; month < 12; month++) { - calendar.set(Calendar.MONTH, month); - calendar.set(Calendar.DAY_OF_MONTH, 1); - //create a sheet for each month - XSSFSheet sheet = wb.createSheet(months[month]); - - //turn off gridlines - sheet.setDisplayGridlines(false); - sheet.setPrintGridlines(false); - XSSFPrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setOrientation(PrintOrientation.LANDSCAPE); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - - //the header row: centered text in 48pt font - XSSFRow headerRow = sheet.createRow(0); - headerRow.setHeightInPoints(80); - XSSFCell titleCell = headerRow.createCell(0); - titleCell.setCellValue(months[month] + " " + year); - titleCell.setCellStyle(styles.get("title")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1")); - - //header with month titles - XSSFRow monthRow = sheet.createRow(1); - for (int i = 0; i < days.length; i++) { - //for compatibility with HSSF we have to set column width in units of 1/256th of a character width - sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide - sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide - sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1)); - XSSFCell monthCell = monthRow.createCell(i*2); - monthCell.setCellValue(days[i]); - monthCell.setCellStyle(styles.get("month")); - } - - int cnt = 1, day=1; - int rownum = 2; - for (int j = 0; j < 6; j++) { - XSSFRow row = sheet.createRow(rownum++); - row.setHeightInPoints(100); - for (int i = 0; i < days.length; i++) { - XSSFCell dayCell_1 = row.createCell(i*2); - XSSFCell dayCell_2 = row.createCell(i*2 + 1); - - int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); - if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) { - dayCell_1.setCellValue(day); - calendar.set(Calendar.DAY_OF_MONTH, ++day); - - if(i == 0 || i == days.length-1) { - dayCell_1.setCellStyle(styles.get("weekend_left")); - dayCell_2.setCellStyle(styles.get("weekend_right")); - } else { - dayCell_1.setCellStyle(styles.get("workday_left")); - dayCell_2.setCellStyle(styles.get("workday_right")); - } - } else { - dayCell_1.setCellStyle(styles.get("grey_left")); - dayCell_2.setCellStyle(styles.get("grey_right")); - } - cnt++; - } - if(calendar.get(Calendar.MONTH) > month) break; - } - } - - // Write the output to a file - FileOutputStream out = new FileOutputStream("calendar-"+year+".xlsx"); - wb.write(out); - out.close(); - } - - /** - * cell styles used for formatting calendar sheets - */ - private static Map createStyles(XSSFWorkbook wb){ - Map styles = new HashMap(); - - XSSFCellStyle style; - XSSFFont titleFont = wb.createFont(); - titleFont.setFontHeightInPoints((short)48); - titleFont.setColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFont(titleFont); - styles.put("title", style); - - XSSFFont monthFont = wb.createFont(); - monthFont.setFontHeightInPoints((short)12); - monthFont.setColor(new XSSFColor(new java.awt.Color(255, 255, 255))); - monthFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setFont(monthFont); - styles.put("month", style); - - XSSFFont dayFont = wb.createFont(); - dayFont.setFontHeightInPoints((short)14); - dayFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.LEFT); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(228, 232, 243))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderLeft(BorderStyle.THIN); - style.setLeftBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setFont(dayFont); - styles.put("weekend_left", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(228, 232, 243))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - styles.put("weekend_right", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.LEFT); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setBorderLeft(BorderStyle.THIN); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setLeftBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setFont(dayFont); - styles.put("workday_left", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - styles.put("workday_right", style); - - style = wb.createCellStyle(); - style.setBorderLeft(BorderStyle.THIN); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - styles.put("grey_left", style); - - style = wb.createCellStyle(); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - styles.put("grey_right", style); - - return styles; - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CellComments.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CellComments.java deleted file mode 100644 index 4eaa33d92d..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CellComments.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.io.IOException; -import java.io.FileOutputStream; - -/** - * Demonstrates how to work with excel cell comments. - * - *

      - * Excel comment is a kind of a text shape, - * so inserting a comment is very similar to placing a text box in a worksheet - *

      - * - * @author Yegor Kozlov - */ -public class CellComments { - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); - - CreationHelper factory = wb.getCreationHelper(); - - Sheet sheet = wb.createSheet(); - - Cell cell1 = sheet.createRow(3).createCell(5); - cell1.setCellValue("F4"); - - Drawing drawing = sheet.createDrawingPatriarch(); - - ClientAnchor anchor = factory.createClientAnchor(); - - Comment comment1 = drawing.createCellComment(anchor); - RichTextString str1 = factory.createRichTextString("Hello, World!"); - comment1.setString(str1); - comment1.setAuthor("Apache POI"); - cell1.setCellComment(comment1); - - Cell cell2 = sheet.createRow(2).createCell(2); - cell2.setCellValue("C3"); - - Comment comment2 = drawing.createCellComment(anchor); - RichTextString str2 = factory.createRichTextString("XSSF can set cell comments"); - //apply custom font to the text in the comment - Font font = wb.createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short)14); - font.setBoldweight(Font.BOLDWEIGHT_BOLD); - font.setColor(IndexedColors.RED.getIndex()); - str2.applyFont(font); - - comment2.setString(str2); - comment2.setAuthor("Apache POI"); - comment2.setColumn(2); - comment2.setRow(2); - - String fname = "comments.xlsx"; - FileOutputStream out = new FileOutputStream(fname); - wb.write(out); - out.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateCell.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateCell.java deleted file mode 100644 index 3e6736014c..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateCell.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.util.Date; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Illustrates how to create cell and set values of different types. - */ -public class CreateCell { - - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - CreationHelper creationHelper = wb.getCreationHelper(); - Sheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - Row row = sheet.createRow((short)0); - // Create a cell and put a value in it. - Cell cell = row.createCell((short)0); - cell.setCellValue(1); - - //numeric value - row.createCell(1).setCellValue(1.2); - - //plain string value - row.createCell(2).setCellValue("This is a string cell"); - - //rich text string - RichTextString str = creationHelper.createRichTextString("Apache"); - Font font = wb.createFont(); - font.setItalic(true); - font.setUnderline(Font.U_SINGLE); - str.applyFont(font); - row.createCell(3).setCellValue(str); - - //boolean value - row.createCell(4).setCellValue(true); - - //formula - row.createCell(5).setCellFormula("SUM(A1:B1)"); - - //date - CellStyle style = wb.createCellStyle(); - style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm")); - cell = row.createCell(6); - cell.setCellValue(new Date()); - cell.setCellStyle(style); - - //hyperlink - row.createCell(7).setCellFormula("SUM(A1:B1)"); - cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")"); - - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java deleted file mode 100644 index 2c37ea08d2..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * How to set user-defined date formats - */ -public class CreateUserDefinedDataFormats { - - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("format sheet"); - CellStyle style; - DataFormat format = wb.createDataFormat(); - Row row; - Cell cell; - short rowNum = 0; - short colNum = 0; - - row = sheet.createRow(rowNum++); - cell = row.createCell(colNum); - cell.setCellValue(11111.25); - style = wb.createCellStyle(); - style.setDataFormat(format.getFormat("0.0")); - cell.setCellStyle(style); - - row = sheet.createRow(rowNum++); - cell = row.createCell(colNum); - cell.setCellValue(11111.25); - style = wb.createCellStyle(); - style.setDataFormat(format.getFormat("#,##0.0000")); - cell.setCellStyle(style); - - FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx"); - wb.write(fileOut); - fileOut.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CustomXMLMapping.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CustomXMLMapping.java deleted file mode 100644 index 1add0d2fb3..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CustomXMLMapping.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xssf.extractor.XSSFExportToXml; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFMap; - -import java.io.ByteArrayOutputStream; - -/** - * Print all custom XML mappings registered in the given workbook - */ -public class CustomXMLMapping { - - public static void main(String[] args) throws Exception { - OPCPackage pkg = OPCPackage.open(args[0]); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - for (XSSFMap map : wb.getCustomXMLMappings()) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); - System.out.println(xml); - } - pkg.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java deleted file mode 100644 index b50e959460..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.hslf.HSLFSlideShow; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.xslf.XSLFSlideShow; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.io.InputStream; - -/** - * Demonstrates how you can extract embedded data from a .xlsx file - */ -public class EmbeddedObjects { - public static void main(String[] args) throws Exception { - OPCPackage pkg = OPCPackage.open(args[0]); - XSSFWorkbook workbook = new XSSFWorkbook(pkg); - for (PackagePart pPart : workbook.getAllEmbedds()) { - String contentType = pPart.getContentType(); - // Excel Workbook - either binary or OpenXML - if (contentType.equals("application/vnd.ms-excel")) { - HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream()); - } - // Excel Workbook - OpenXML file format - else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { - XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream()); - } - // Word Document - binary (OLE2CDF) file format - else if (contentType.equals("application/msword")) { - HWPFDocument document = new HWPFDocument(pPart.getInputStream()); - } - // Word Document - OpenXML file format - else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) { - XWPFDocument document = new XWPFDocument(pPart.getInputStream()); - } - // PowerPoint Document - binary file format - else if (contentType.equals("application/vnd.ms-powerpoint")) { - HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream()); - } - // PowerPoint Document - OpenXML file format - else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) { - OPCPackage docPackage = OPCPackage.open(pPart.getInputStream()); - XSLFSlideShow slideShow = new XSLFSlideShow(docPackage); - } - // Any other type of embedded object. - else { - System.out.println("Unknown Embedded Document: " + contentType); - InputStream inputStream = pPart.getInputStream(); - } - } - pkg.close(); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/FillsAndColors.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/FillsAndColors.java deleted file mode 100644 index 019e14d1ce..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/FillsAndColors.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Fills and Colors - */ -public class FillsAndColors { - public static void main(String[] args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - Row row = sheet.createRow((short) 1); - - // Aqua background - CellStyle style = wb.createCellStyle(); - style.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); - style.setFillPattern(CellStyle.BIG_SPOTS); - Cell cell = row.createCell((short) 1); - cell.setCellValue(new XSSFRichTextString("X")); - cell.setCellStyle(style); - - // Orange "foreground", foreground being the fill foreground not the font color. - style = wb.createCellStyle(); - style.setFillForegroundColor(IndexedColors.ORANGE.getIndex()); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - cell = row.createCell((short) 2); - cell.setCellValue(new XSSFRichTextString("X")); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx"); - wb.write(fileOut); - fileOut.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/FitSheetToOnePage.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/FitSheetToOnePage.java deleted file mode 100644 index a781688c39..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/FitSheetToOnePage.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.PrintSetup; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class FitSheetToOnePage { - - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("format sheet"); - PrintSetup ps = sheet.getPrintSetup(); - - sheet.setAutobreaks(true); - - ps.setFitHeight((short) 1); - ps.setFitWidth((short) 1); - - // Create various cells and rows for spreadsheet. - - FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx"); - wb.write(fileOut); - fileOut.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/HeadersAndFooters.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/HeadersAndFooters.java deleted file mode 100644 index 8b95fe63c2..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/HeadersAndFooters.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.Footer; -import org.apache.poi.ss.usermodel.Header; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class HeadersAndFooters { - - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("first-header - format sheet"); - sheet.createRow(0).createCell(0).setCellValue(123); - - //set page numbers in the footer - Footer footer = sheet.getFooter(); - //&P == current page number - //&N == page numbers - footer.setRight("Page &P of &N"); - - - Header firstHeader=((XSSFSheet)sheet).getFirstHeader(); - //&F == workbook file name - firstHeader.setLeft("&F ......... first header"); - - for(int i=0;i<100;i=i+10){ - sheet.createRow(i).createCell(0).setCellValue(123); - } - - - XSSFSheet sheet2 = (XSSFSheet)wb.createSheet("odd header-even footer"); - Header oddHeader=sheet2.getOddHeader(); - //&B == bold - //&E == double underline - //&D == date - oddHeader.setCenter("&B &E oddHeader &D "); - - Footer evenFooter=sheet2.getEvenFooter(); - evenFooter.setRight("even footer &P"); - sheet2.createRow(10).createCell(0).setCellValue("Second sheet with an oddHeader and an evenFooter"); - - for(int i=0;i<200;i=i+10){ - sheet2.createRow(i).createCell(0).setCellValue(123); - } - - XSSFSheet sheet3 = (XSSFSheet)wb.createSheet("odd header- odd footer"); - sheet3.createRow(10).createCell(0).setCellValue("Third sheet with oddHeader and oddFooter"); - Header oddH=sheet3.getOddHeader(); - //&C == centered - oddH.setCenter("centered oddHeader"); - oddH.setLeft("left "); - oddH.setRight("right "); - - Footer oddF=sheet3.getOddFooter(); - oddF.setLeft("Page &P"); - oddF.setRight("Pages &N "); - - FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx"); - wb.write(fileOut); - fileOut.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/HyperlinkExample.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/HyperlinkExample.java deleted file mode 100644 index 005bdc756d..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/HyperlinkExample.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.ss.usermodel.IndexedColors; - -/** - * Demonstrates how to create hyperlinks. - */ -public class HyperlinkExample { - - - public static void main(String[]args) throws Exception{ - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - CreationHelper createHelper = wb.getCreationHelper(); - - //cell style for hyperlinks - //by default hyperlinks are blue and underlined - CellStyle hlink_style = wb.createCellStyle(); - Font hlink_font = wb.createFont(); - hlink_font.setUnderline(Font.U_SINGLE); - hlink_font.setColor(IndexedColors.BLUE.getIndex()); - hlink_style.setFont(hlink_font); - - Cell cell; - Sheet sheet = wb.createSheet("Hyperlinks"); - //URL - cell = sheet.createRow(0).createCell((short)0); - cell.setCellValue("URL Link"); - - Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL); - link.setAddress("http://poi.apache.org/"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //link to a file in the current directory - cell = sheet.createRow(1).createCell((short)0); - cell.setCellValue("File Link"); - link = createHelper.createHyperlink(Hyperlink.LINK_FILE); - link.setAddress("link1.xls"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //e-mail link - cell = sheet.createRow(2).createCell((short)0); - cell.setCellValue("Email Link"); - link = createHelper.createHyperlink(Hyperlink.LINK_EMAIL); - //note, if subject contains white spaces, make sure they are url-encoded - link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //link to a place in this workbook - - //create a target sheet and cell - Sheet sheet2 = wb.createSheet("Target Sheet"); - sheet2.createRow(0).createCell((short)0).setCellValue("Target Cell"); - - cell = sheet.createRow(3).createCell((short)0); - cell.setCellValue("Worksheet Link"); - Hyperlink link2 = createHelper.createHyperlink(Hyperlink.LINK_DOCUMENT); - link2.setAddress("'Target Sheet'!A1"); - cell.setHyperlink(link2); - cell.setCellStyle(hlink_style); - - FileOutputStream out = new FileOutputStream("hyperinks.xlsx"); - wb.write(out); - out.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java deleted file mode 100644 index 99d1cacf61..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; - -import java.io.FileInputStream; - -/** - * Iterate over rows and cells - */ -public class IterateCells { - - public static void main(String[] args) throws Exception { - Workbook wb = new XSSFWorkbook(new FileInputStream(args[0])); - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet sheet = wb.getSheetAt(i); - System.out.println(wb.getSheetName(i)); - for (Row row : sheet) { - System.out.println("rownum: " + row.getRowNum()); - for (Cell cell : row) { - System.out.println(cell.toString()); - } - } - } - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java deleted file mode 100644 index 9fc24ac0d7..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.usermodel.charts.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.io.FileOutputStream; - -/** - * Line chart example. - * - * @author Martin Andersson - */ -public class LineChart { - - public static void main(String[] args) throws Exception { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("linechart"); - final int NUM_OF_ROWS = 3; - final int NUM_OF_COLUMNS = 10; - - // Create a row and put some cells in it. Rows are 0 based. - Row row; - Cell cell; - for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { - row = sheet.createRow((short) rowIndex); - for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { - cell = row.createCell((short) colIndex); - cell.setCellValue(colIndex * (rowIndex + 1)); - } - } - - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); - - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - legend.setPosition(LegendPosition.TOP_RIGHT); - - LineChartData data = chart.getChartDataFactory().createLineChartData(); - - // Use a category axis for the bottom axis. - ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); - ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); - leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); - - ChartDataSource xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); - - - data.addSerie(xs, ys1); - data.addSerie(xs, ys2); - - chart.plot(data, bottomAxis, leftAxis); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/MergingCells.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/MergingCells.java deleted file mode 100644 index 9d63268fc3..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/MergingCells.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; - -import java.io.FileOutputStream; - -/** - * An example of how to merge regions of cells. - */ -public class MergingCells { - public static void main(String[] args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("new sheet"); - - Row row = sheet.createRow((short) 1); - Cell cell = row.createCell((short) 1); - cell.setCellValue(new XSSFRichTextString("This is a test of merging")); - - sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2)); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/NewLinesInCells.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/NewLinesInCells.java deleted file mode 100644 index eb179357d5..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/NewLinesInCells.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * How to use newlines in cells - */ -public class NewLinesInCells { - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(2); - Cell cell = row.createCell(2); - cell.setCellValue("Use \n with word wrap on to create a new line"); - - //to enable newlines you need set a cell styles with wrap=true - CellStyle cs = wb.createCellStyle(); - cs.setWrapText(true); - cell.setCellStyle(cs); - - //increase row height to accomodate two lines of text - row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints())); - - //adjust column width to fit the content - sheet.autoSizeColumn(2); - - FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx"); - wb.write(fileOut); - fileOut.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/Outlining.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/Outlining.java deleted file mode 100644 index 71d63b1f55..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/Outlining.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class Outlining { - - public static void main(String[]args) throws Exception{ - Outlining o=new Outlining(); - o.groupRowColumn(); - o.collapseExpandRowColumn(); - } - - - private void groupRowColumn() throws Exception{ - Workbook wb = new XSSFWorkbook(); - Sheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow( 5, 14 ); - sheet1.groupRow( 7, 14 ); - sheet1.groupRow( 16, 19 ); - - sheet1.groupColumn( (short)4, (short)7 ); - sheet1.groupColumn( (short)9, (short)12 ); - sheet1.groupColumn( (short)10, (short)11 ); - - FileOutputStream fileOut = new FileOutputStream("outlining.xlsx"); - wb.write(fileOut); - fileOut.close(); - - } - - private void collapseExpandRowColumn()throws Exception{ - Workbook wb2 = new XSSFWorkbook(); - Sheet sheet2 = wb2.createSheet("new sheet"); - sheet2.groupRow( 5, 14 ); - sheet2.groupRow( 7, 14 ); - sheet2.groupRow( 16, 19 ); - - sheet2.groupColumn( (short)4, (short)7 ); - sheet2.groupColumn( (short)9, (short)12 ); - sheet2.groupColumn( (short)10, (short)11 ); - - - sheet2.setRowGroupCollapsed( 7, true ); - //sheet1.setRowGroupCollapsed(7,false); - - sheet2.setColumnGroupCollapsed( (short)4, true ); - sheet2.setColumnGroupCollapsed( (short)4, false ); - - FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx"); - wb2.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/ScatterChart.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/ScatterChart.java deleted file mode 100644 index f0a94777f0..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/ScatterChart.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.*; -import org.apache.poi.ss.usermodel.charts.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Illustrates how to create a simple scatter chart. - * - * @author Roman Kashitsyn - */ -public class ScatterChart { - - public static void main(String[] args) throws Exception { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("Sheet 1"); - final int NUM_OF_ROWS = 3; - final int NUM_OF_COLUMNS = 10; - - // Create a row and put some cells in it. Rows are 0 based. - Row row; - Cell cell; - for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { - row = sheet.createRow((short) rowIndex); - for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { - cell = row.createCell((short) colIndex); - cell.setCellValue(colIndex * (rowIndex + 1)); - } - } - - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); - - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - legend.setPosition(LegendPosition.TOP_RIGHT); - - ScatterChartData data = chart.getChartDataFactory().createScatterChartData(); - - ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM); - ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); - leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); - - ChartDataSource xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); - - - data.addSerie(xs, ys1); - data.addSerie(xs, ys2); - - chart.plot(data, bottomAxis, leftAxis); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/SelectedSheet.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/SelectedSheet.java deleted file mode 100644 index 45bee91d6f..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/SelectedSheet.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class SelectedSheet { - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - - Sheet sheet = wb.createSheet("row sheet"); - Sheet sheet2 = wb.createSheet("another sheet"); - Sheet sheet3 = wb.createSheet(" sheet 3 "); - sheet3.setSelected(true); - wb.setActiveSheet(2); - - // Create various cells and rows for spreadsheet. - - FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx"); - wb.write(fileOut); - fileOut.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/ShiftRows.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/ShiftRows.java deleted file mode 100644 index ec4bb21398..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/ShiftRows.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * How to shift rows up or down - */ -public class ShiftRows { - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - - Row row1 = sheet.createRow(1); - row1.createCell(0).setCellValue(1); - - Row row2 = sheet.createRow(4); - row2.createCell(1).setCellValue(2); - - Row row3 = sheet.createRow(5); - row3.createCell(2).setCellValue(3); - - Row row4 = sheet.createRow(6); - row4.createCell(3).setCellValue(4); - - Row row5 = sheet.createRow(9); - row5.createCell(4).setCellValue(5); - - // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5) - sheet.shiftRows(5, 10, -4); - - FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx"); - wb.write(fileOut); - fileOut.close(); - - } - - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/SplitAndFreezePanes.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/SplitAndFreezePanes.java deleted file mode 100644 index 937086b85d..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/SplitAndFreezePanes.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.io.FileOutputStream; - -/** - * How to set spklit and freeze panes - */ -public class SplitAndFreezePanes { - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); - Sheet sheet1 = wb.createSheet("new sheet"); - Sheet sheet2 = wb.createSheet("second sheet"); - Sheet sheet3 = wb.createSheet("third sheet"); - Sheet sheet4 = wb.createSheet("fourth sheet"); - - // Freeze just one row - sheet1.createFreezePane(0, 1, 0, 1); - // Freeze just one column - sheet2.createFreezePane(1, 0, 1, 0); - // Freeze the columns and rows (forget about scrolling position of the lower right quadrant). - sheet3.createFreezePane(2, 2); - // Create a split with the lower left side being the active quadrant - sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT); - - FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkbookProperties.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkbookProperties.java deleted file mode 100644 index 3a8fd56d00..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkbookProperties.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.POIXMLProperties; - -/** - * How to set extended and custom properties - * - * @author Yegor Kozlov - */ -public class WorkbookProperties { - - public static void main(String[]args) throws Exception { - - XSSFWorkbook workbook = new XSSFWorkbook(); - workbook.createSheet("Workbook Properties"); - - POIXMLProperties props = workbook.getProperties(); - - /** - * Extended properties are a predefined set of metadata properties - * that are specifically applicable to Office Open XML documents. - * Extended properties consist of 24 simple properties and 3 complex properties stored in the - * part targeted by the relationship of type - */ - POIXMLProperties.ExtendedProperties ext = props.getExtendedProperties(); - ext.getUnderlyingProperties().setCompany("Apache Software Foundation"); - ext.getUnderlyingProperties().setTemplate("XSSF"); - - /** - * Custom properties enable users to define custom metadata properties. - */ - - POIXMLProperties.CustomProperties cust = props.getCustomProperties(); - cust.addProperty("Author", "John Smith"); - cust.addProperty("Year", 2009); - cust.addProperty("Price", 45.50); - cust.addProperty("Available", true); - - FileOutputStream out = new FileOutputStream("workbook.xlsx"); - workbook.write(out); - out.close(); - - } - - -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithBorders.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithBorders.java deleted file mode 100644 index 6e12fffe74..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithBorders.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.*; - -import java.io.FileOutputStream; - -/** - * Working with borders - */ -public class WorkingWithBorders { - public static void main(String[] args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("borders"); - - // Create a row and put some cells in it. Rows are 0 based. - Row row = sheet.createRow((short) 1); - - // Create a cell and put a value in it. - Cell cell = row.createCell((short) 1); - cell.setCellValue(4); - - // Style the cell with borders all around. - CellStyle style = wb.createCellStyle(); - style.setBorderBottom(CellStyle.BORDER_THIN); - style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderLeft(CellStyle.BORDER_THIN); - style.setLeftBorderColor(IndexedColors.GREEN.getIndex()); - style.setBorderRight(CellStyle.BORDER_THIN); - style.setRightBorderColor(IndexedColors.BLUE.getIndex()); - style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED); - style.setTopBorderColor(IndexedColors.BLACK.getIndex()); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithFonts.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithFonts.java deleted file mode 100644 index 3d4393ba1f..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithFonts.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.ss.usermodel.IndexedColors; - -import java.io.FileOutputStream; - -/** - * Working with Fonts - */ -public class WorkingWithFonts { - public static void main(String[] args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("Fonts"); - - Font font0 = wb.createFont(); - font0.setColor(IndexedColors.BROWN.getIndex()); - CellStyle style0 = wb.createCellStyle(); - style0.setFont(font0); - - Font font1 = wb.createFont(); - font1.setFontHeightInPoints((short)14); - font1.setFontName("Courier New"); - font1.setColor(IndexedColors.RED.getIndex()); - CellStyle style1 = wb.createCellStyle(); - style1.setFont(font1); - - Font font2 = wb.createFont(); - font2.setFontHeightInPoints((short)16); - font2.setFontName("Arial"); - font2.setColor(IndexedColors.GREEN.getIndex()); - CellStyle style2 = wb.createCellStyle(); - style2.setFont(font2); - - Font font3 = wb.createFont(); - font3.setFontHeightInPoints((short)18); - font3.setFontName("Times New Roman"); - font3.setColor(IndexedColors.LAVENDER.getIndex()); - CellStyle style3 = wb.createCellStyle(); - style3.setFont(font3); - - Font font4 = wb.createFont(); - font4.setFontHeightInPoints((short)18); - font4.setFontName("Wingdings"); - font4.setColor(IndexedColors.GOLD.getIndex()); - CellStyle style4 = wb.createCellStyle(); - style4.setFont(font4); - - Font font5 = wb.createFont(); - font5.setFontName("Symbol"); - CellStyle style5 = wb.createCellStyle(); - style5.setFont(font5); - - Cell cell0 = sheet.createRow(0).createCell(1); - cell0.setCellValue("Default"); - cell0.setCellStyle(style0); - - Cell cell1 = sheet.createRow(1).createCell(1); - cell1.setCellValue("Courier"); - cell1.setCellStyle(style1); - - Cell cell2 = sheet.createRow(2).createCell(1); - cell2.setCellValue("Arial"); - cell2.setCellStyle(style2); - - Cell cell3 = sheet.createRow(3).createCell(1); - cell3.setCellValue("Times New Roman"); - cell3.setCellStyle(style3); - - Cell cell4 = sheet.createRow(4).createCell(1); - cell4.setCellValue("Wingdings"); - cell4.setCellStyle(style4); - - Cell cell5 = sheet.createRow(5).createCell(1); - cell5.setCellValue("Symbol"); - cell5.setCellStyle(style5); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPageSetup.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPageSetup.java deleted file mode 100644 index d1be7af174..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPageSetup.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Demonstrates various settings avaiable in the Page Setup dialog - */ -public class WorkingWithPageSetup { - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - - /** - * It's possible to set up repeating rows and columns in your printouts by using the setRepeatingRowsAndColumns() function in the Workbook object. - * - * This function Contains 5 parameters: - * The first parameter is the index to the sheet (0 = first sheet). - * The second and third parameters specify the range for the columns to repreat. - * To stop the columns from repeating pass in -1 as the start and end column. - * The fourth and fifth parameters specify the range for the rows to repeat. - * To stop the columns from repeating pass in -1 as the start and end rows. - */ - Sheet sheet1 = wb.createSheet("new sheet"); - Sheet sheet2 = wb.createSheet("second sheet"); - - // Set the columns to repeat from column 0 to 2 on the first sheet - Row row1 = sheet1.createRow(0); - row1.createCell(0).setCellValue(1); - row1.createCell(1).setCellValue(2); - row1.createCell(2).setCellValue(3); - Row row2 = sheet1.createRow(1); - row2.createCell(1).setCellValue(4); - row2.createCell(2).setCellValue(5); - - - Row row3 = sheet2.createRow(1); - row3.createCell(0).setCellValue(2.1); - row3.createCell(4).setCellValue(2.2); - row3.createCell(5).setCellValue(2.3); - Row row4 = sheet2.createRow(2); - row4.createCell(4).setCellValue(2.4); - row4.createCell(5).setCellValue(2.5); - - // Set the columns to repeat from column 0 to 2 on the first sheet - wb.setRepeatingRowsAndColumns(0,0,2,-1,-1); - // Set the the repeating rows and columns on the second sheet. - wb.setRepeatingRowsAndColumns(1,4,5,1,2); - - //set the print area for the first sheet - wb.setPrintArea(0, 1, 2, 0, 3); - - - FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPictures.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPictures.java deleted file mode 100644 index a2a914335e..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPictures.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.util.IOUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; - -/** - * Demonstrates how to insert pictures in a SpreadsheetML document - * - * @author Yegor Kozlov - */ -public class WorkingWithPictures { - public static void main(String[] args) throws IOException { - - //create a new workbook - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - CreationHelper helper = wb.getCreationHelper(); - - //add a picture in this workbook. - InputStream is = new FileInputStream(args[0]); - byte[] bytes = IOUtils.toByteArray(is); - is.close(); - int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG); - - //create sheet - Sheet sheet = wb.createSheet(); - - //create drawing - Drawing drawing = sheet.createDrawingPatriarch(); - - //add a picture shape - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setCol1(1); - anchor.setRow1(1); - Picture pict = drawing.createPicture(anchor, pictureIdx); - - //auto-size picture - pict.resize(2); - - //save workbook - String file = "picture.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream fileOut = new FileOutputStream(file); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithRichText.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithRichText.java deleted file mode 100644 index d019ab8d8b..0000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithRichText.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.xssf.usermodel.*; - -import java.io.FileOutputStream; - -/** - * Demonstrates how to work with rich text - */ -public class WorkingWithRichText { - - public static void main(String[] args) throws Exception { - - XSSFWorkbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow((short) 2); - - XSSFCell cell = row.createCell(1); - XSSFRichTextString rt = new XSSFRichTextString("The quick brown fox"); - - XSSFFont font1 = wb.createFont(); - font1.setBold(true); - font1.setColor(new XSSFColor(new java.awt.Color(255, 0, 0))); - rt.applyFont(0, 10, font1); - - XSSFFont font2 = wb.createFont(); - font2.setItalic(true); - font2.setUnderline(XSSFFont.U_DOUBLE); - font2.setColor(new XSSFColor(new java.awt.Color(0, 255, 0))); - rt.applyFont(10, 19, font2); - - XSSFFont font3 = wb.createFont(); - font3.setColor(new XSSFColor(new java.awt.Color(0, 0, 255))); - rt.append(" Jumped over the lazy dog", font3); - - cell.setCellValue(rt); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx"); - wb.write(fileOut); - fileOut.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocument.java b/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocument.java deleted file mode 100644 index b7e4da2d4e..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocument.java +++ /dev/null @@ -1,120 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.FileOutputStream; - -/** - * A simple WOrdprocessingML document created by POI XWPF API - * - * @author Yegor Kozlov - */ -public class SimpleDocument { - - public static void main(String[] args) throws Exception { - XWPFDocument doc = new XWPFDocument(); - - XWPFParagraph p1 = doc.createParagraph(); - p1.setAlignment(ParagraphAlignment.CENTER); - p1.setBorderBottom(Borders.DOUBLE); - p1.setBorderTop(Borders.DOUBLE); - - p1.setBorderRight(Borders.DOUBLE); - p1.setBorderLeft(Borders.DOUBLE); - p1.setBorderBetween(Borders.SINGLE); - - p1.setVerticalAlignment(TextAlignment.TOP); - - XWPFRun r1 = p1.createRun(); - r1.setBold(true); - r1.setText("The quick brown fox"); - r1.setBold(true); - r1.setFontFamily("Courier"); - r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); - r1.setTextPosition(100); - - XWPFParagraph p2 = doc.createParagraph(); - p2.setAlignment(ParagraphAlignment.RIGHT); - - //BORDERS - p2.setBorderBottom(Borders.DOUBLE); - p2.setBorderTop(Borders.DOUBLE); - p2.setBorderRight(Borders.DOUBLE); - p2.setBorderLeft(Borders.DOUBLE); - p2.setBorderBetween(Borders.SINGLE); - - XWPFRun r2 = p2.createRun(); - r2.setText("jumped over the lazy dog"); - r2.setStrike(true); - r2.setFontSize(20); - - XWPFRun r3 = p2.createRun(); - r3.setText("and went away"); - r3.setStrike(true); - r3.setFontSize(20); - r3.setSubscript(VerticalAlign.SUPERSCRIPT); - - - XWPFParagraph p3 = doc.createParagraph(); - p3.setWordWrap(true); - p3.setPageBreak(true); - - //p3.setAlignment(ParagraphAlignment.DISTRIBUTE); - p3.setAlignment(ParagraphAlignment.BOTH); - p3.setSpacingLineRule(LineSpacingRule.EXACT); - - p3.setIndentationFirstLine(600); - - - XWPFRun r4 = p3.createRun(); - r4.setTextPosition(20); - r4.setText("To be, or not to be: that is the question: " - + "Whether 'tis nobler in the mind to suffer " - + "The slings and arrows of outrageous fortune, " - + "Or to take arms against a sea of troubles, " - + "And by opposing end them? To die: to sleep; "); - r4.addBreak(BreakType.PAGE); - r4.setText("No more; and by a sleep to say we end " - + "The heart-ache and the thousand natural shocks " - + "That flesh is heir to, 'tis a consummation " - + "Devoutly to be wish'd. To die, to sleep; " - + "To sleep: perchance to dream: ay, there's the rub; " - + "......."); - r4.setItalic(true); -//This would imply that this break shall be treated as a simple line break, and break the line after that word: - - XWPFRun r5 = p3.createRun(); - r5.setTextPosition(-10); - r5.setText("For in that sleep of death what dreams may come"); - r5.addCarriageReturn(); - r5.setText("When we have shuffled off this mortal coil," - + "Must give us pause: there's the respect" - + "That makes calamity of so long life;"); - r5.addBreak(); - r5.setText("For who would bear the whips and scorns of time," - + "The oppressor's wrong, the proud man's contumely,"); - - r5.addBreak(BreakClear.ALL); - r5.setText("The pangs of despised love, the law's delay," - + "The insolence of office and the spurns" + "......."); - - FileOutputStream out = new FileOutputStream("simple.docx"); - doc.write(out); - out.close(); - - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleImages.java b/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleImages.java deleted file mode 100644 index 10e48d1aed..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleImages.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.util.Units; - -import java.io.FileInputStream; -import java.io.FileOutputStream; - -/** - * Demonstrates how to add pictures in a .docx document - * - * @author Yegor Kozlov - */ -public class SimpleImages { - - public static void main(String[] args) throws Exception { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - XWPFRun r = p.createRun(); - - for(String imgFile : args) { - int format; - - if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF; - else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF; - else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT; - else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG; - else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG; - else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB; - else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF; - else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF; - else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS; - else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP; - else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG; - else { - System.err.println("Unsupported picture: " + imgFile + - ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg"); - continue; - } - - r.setText(imgFile); - r.addBreak(); - r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels - r.addBreak(BreakType.PAGE); - } - - FileOutputStream out = new FileOutputStream("images.docx"); - doc.write(out); - out.close(); - } - - -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleTable.java b/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleTable.java deleted file mode 100644 index 5f049ba0ac..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleTable.java +++ /dev/null @@ -1,199 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.FileOutputStream; -import java.math.BigInteger; -import java.util.List; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc; - -/** - * This program creates a simple WordprocessingML table using POI XWPF API, and - * a more complex, styled table using both XWPF and ooxml-schema. It's possible - * that not all referenced wordprocessingml classes are defined in - * poi-ooxml-schemas-3.8-beta4. If this is the case, you'll need to use the full - * ooxml-schemas.jar library. - * - * @author gisella bronzetti (original) - * @author Gregg Morris (styled table) - */ -public class SimpleTable { - - public static void main(String[] args) throws Exception { - try { - createSimpleTable(); - } - catch(Exception e) { - System.out.println("Error trying to create simple table."); - throw(e); - } - try { - createStyledTable(); - } - catch(Exception e) { - System.out.println("Error trying to create styled table."); - throw(e); - } - } - - public static void createSimpleTable() throws Exception { - XWPFDocument doc = new XWPFDocument(); - - XWPFTable table = doc.createTable(3, 3); - - table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE"); - - // table cells have a list of paragraphs; there is an initial - // paragraph created when the cell is created. If you create a - // paragraph in the document to put in the cell, it will also - // appear in the document following the table, which is probably - // not the desired result. - XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0); - - XWPFRun r1 = p1.createRun(); - r1.setBold(true); - r1.setText("The quick brown fox"); - r1.setItalic(true); - r1.setFontFamily("Courier"); - r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); - r1.setTextPosition(100); - - table.getRow(2).getCell(2).setText("only text"); - - FileOutputStream out = new FileOutputStream("simpleTable.docx"); - doc.write(out); - out.close(); - } - - /** - * Create a table with some row and column styling. I "manually" add the - * style name to the table, but don't check to see if the style actually - * exists in the document. Since I'm creating it from scratch, it obviously - * won't exist. When opened in MS Word, the table style becomes "Normal". - * I manually set alternating row colors. This could be done using Themes, - * but that's left as an exercise for the reader. The cells in the last - * column of the table have 10pt. "Courier" font. - * I make no claims that this is the "right" way to do it, but it worked - * for me. Given the scarcity of XWPF examples, I thought this may prove - * instructive and give you ideas for your own solutions. - - * @throws Exception - */ - public static void createStyledTable() throws Exception { - // Create a new document from scratch - XWPFDocument doc = new XWPFDocument(); - // -- OR -- - // open an existing empty document with styles already defined - //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx")); - - // Create a new table with 6 rows and 3 columns - int nRows = 6; - int nCols = 3; - XWPFTable table = doc.createTable(nRows, nCols); - - // Set the table style. If the style is not defined, the table style - // will become "Normal". - CTTblPr tblPr = table.getCTTbl().getTblPr(); - CTString styleStr = tblPr.addNewTblStyle(); - styleStr.setVal("StyledTable"); - - // Get a list of the rows in the table - List rows = table.getRows(); - int rowCt = 0; - int colCt = 0; - for (XWPFTableRow row : rows) { - // get table row properties (trPr) - CTTrPr trPr = row.getCtRow().addNewTrPr(); - // set row height; units = twentieth of a point, 360 = 0.25" - CTHeight ht = trPr.addNewTrHeight(); - ht.setVal(BigInteger.valueOf(360)); - - // get the cells in this row - List cells = row.getTableCells(); - // add content to each cell - for (XWPFTableCell cell : cells) { - // get a table cell properties element (tcPr) - CTTcPr tcpr = cell.getCTTc().addNewTcPr(); - // set vertical alignment to "center" - CTVerticalJc va = tcpr.addNewVAlign(); - va.setVal(STVerticalJc.CENTER); - - // create cell color element - CTShd ctshd = tcpr.addNewShd(); - ctshd.setColor("auto"); - ctshd.setVal(STShd.CLEAR); - if (rowCt == 0) { - // header row - ctshd.setFill("A7BFDE"); - } - else if (rowCt % 2 == 0) { - // even row - ctshd.setFill("D3DFEE"); - } - else { - // odd row - ctshd.setFill("EDF2F8"); - } - - // get 1st paragraph in cell's paragraph list - XWPFParagraph para = cell.getParagraphs().get(0); - // create a run to contain the content - XWPFRun rh = para.createRun(); - // style cell as desired - if (colCt == nCols - 1) { - // last column is 10pt Courier - rh.setFontSize(10); - rh.setFontFamily("Courier"); - } - if (rowCt == 0) { - // header row - rh.setText("header row, col " + colCt); - rh.setBold(true); - para.setAlignment(ParagraphAlignment.CENTER); - } - else if (rowCt % 2 == 0) { - // even row - rh.setText("row " + rowCt + ", col " + colCt); - para.setAlignment(ParagraphAlignment.LEFT); - } - else { - // odd row - rh.setText("row " + rowCt + ", col " + colCt); - para.setAlignment(ParagraphAlignment.LEFT); - } - colCt++; - } // for cell - colCt = 0; - rowCt++; - } // for row - - // write the file - FileOutputStream out = new FileOutputStream("styledTable.docx"); - doc.write(out); - out.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/UpdateEmbeddedDoc.java b/src/examples/src/org/apache/poi/xwpf/usermodel/UpdateEmbeddedDoc.java deleted file mode 100644 index ffdb7e2049..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/UpdateEmbeddedDoc.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xwpf.usermodel; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.List; -import java.util.Iterator; - -import junit.framework.Assert; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Cell; - -/** - * Tests whether it is possible to successfully update an Excel workbook that is - * embedded into a WordprocessingML document. Note that the test has currently - * only been conducted with a binary Excel workbook and NOT yet with a - * SpreadsheetML workbook embedded into the document. - * - *

      - * This code was successfully tested with the following file from the POI test collection: - * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx - *

      - * - * @author Mark B - */ -public class UpdateEmbeddedDoc { - - private XWPFDocument doc = null; - private File docFile = null; - - private static final int SHEET_NUM = 0; - private static final int ROW_NUM = 0; - private static final int CELL_NUM = 0; - private static final double NEW_VALUE = 100.98D; - private static final String BINARY_EXTENSION = "xls"; - private static final String OPENXML_EXTENSION = "xlsx"; - - /** - * Create a new instance of the UpdateEmbeddedDoc class using the following - * parameters; - * - * @param filename An instance of the String class that encapsulates the name - * of and path to a WordprocessingML Word document that contains an - * embedded binary Excel workbook. - * @throws java.io.FileNotFoundException Thrown if the file cannot be found - * on the underlying file system. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public UpdateEmbeddedDoc(String filename) throws FileNotFoundException, IOException { - this.docFile = new File(filename); - FileInputStream fis = null; - if (!this.docFile.exists()) { - throw new FileNotFoundException("The Word dcoument " + - filename + - " does not exist."); - } - try { - - // Open the Word document file and instantiate the XWPFDocument - // class. - fis = new FileInputStream(this.docFile); - this.doc = new XWPFDocument(fis); - } finally { - if (fis != null) { - try { - fis.close(); - fis = null; - } catch (IOException ioEx) { - System.out.println("IOException caught trying to close " + - "FileInputStream in the constructor of " + - "UpdateEmbeddedDoc."); - } - } - } - } - - /** - * Called to update the embedded Excel workbook. As the format and structire - * of the workbook are known in advance, all this code attempts to do is - * write a new value into the first cell on the first row of the first - * worksheet. Prior to executing this method, that cell will contain the - * value 1. - * - * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException - * Rather - * than use the specific classes (HSSF/XSSF) to handle the embedded - * workbook this method uses those defeined in the SS stream. As - * a result, it might be the case that a SpreadsheetML file is - * opened for processing, throwing this exception if that file is - * invalid. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public void updateEmbeddedDoc() throws OpenXML4JException, IOException { - Workbook workbook = null; - Sheet sheet = null; - Row row = null; - Cell cell = null; - PackagePart pPart = null; - Iterator pIter = null; - List embeddedDocs = this.doc.getAllEmbedds(); - if (embeddedDocs != null && !embeddedDocs.isEmpty()) { - pIter = embeddedDocs.iterator(); - while (pIter.hasNext()) { - pPart = pIter.next(); - if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || - pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { - - // Get an InputStream from the pacage part and pass that - // to the create method of the WorkbookFactory class. Update - // the resulting Workbook and then stream that out again - // using an OutputStream obtained from the same PackagePart. - workbook = WorkbookFactory.create(pPart.getInputStream()); - sheet = workbook.getSheetAt(SHEET_NUM); - row = sheet.getRow(ROW_NUM); - cell = row.getCell(CELL_NUM); - cell.setCellValue(NEW_VALUE); - workbook.write(pPart.getOutputStream()); - } - } - - // Finally, write the newly modified Word document out to file. - this.doc.write(new FileOutputStream(this.docFile)); - } - } - - /** - * Called to test whether or not the embedded workbook was correctly - * updated. This method simply recovers the first cell from the first row - * of the first workbook and tests the value it contains. - *

      - * Note that execution will not continue up to the assertion as the - * embedded workbook is now corrupted and causes an IllegalArgumentException - * with the following message - *

      - * java.lang.IllegalArgumentException: Your InputStream was neither an - * OLE2 stream, nor an OOXML stream - *

      - * to be thrown when the WorkbookFactory.createWorkbook(InputStream) method - * is executed. - * - * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException - * Rather - * than use the specific classes (HSSF/XSSF) to handle the embedded - * workbook this method uses those defeined in the SS stream. As - * a result, it might be the case that a SpreadsheetML file is - * opened for processing, throwing this exception if that file is - * invalid. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public void checkUpdatedDoc() throws OpenXML4JException, IOException { - Workbook workbook = null; - Sheet sheet = null; - Row row = null; - Cell cell = null; - PackagePart pPart = null; - Iterator pIter = null; - List embeddedDocs = this.doc.getAllEmbedds(); - if (embeddedDocs != null && !embeddedDocs.isEmpty()) { - pIter = embeddedDocs.iterator(); - while (pIter.hasNext()) { - pPart = pIter.next(); - if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || - pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { - workbook = WorkbookFactory.create(pPart.getInputStream()); - sheet = workbook.getSheetAt(SHEET_NUM); - row = sheet.getRow(ROW_NUM); - cell = row.getCell(CELL_NUM); - Assert.assertEquals(cell.getNumericCellValue(), NEW_VALUE); - } - } - } - } - - /** - * Code to test updating of the embedded Excel workbook. - * - * @param args - */ - public static void main(String[] args) { - try { - UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]); - ued.updateEmbeddedDoc(); - ued.checkUpdatedDoc(); - } catch (Exception ex) { - System.out.println(ex.getClass().getName()); - System.out.println(ex.getMessage()); - ex.printStackTrace(System.out); - } - } -}