<url>http://poi.apache.org/</url>
<description>Apache POI Examples</description>
-
- <build>
- <plugins>
- <!-- copy sources, resources and tests in place as otherwise Sonar does not pick them up correctly! -->
- <plugin>
- <artifactId>maven-resources-plugin</artifactId>
- <version>2.6</version>
- <executions>
- <execution>
- <id>copy-sources</id>
- <!-- here the phase you need -->
- <phase>generate-sources</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <configuration>
- <outputDirectory>${basedir}/src/main/java</outputDirectory>
- <resources>
- <resource>
- <directory>../../src/examples/src</directory>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <!-- clean copied sources afterwards -->
- <plugin>
- <artifactId>maven-clean-plugin</artifactId>
- <version>2.5</version>
- <configuration>
- <filesets>
- <fileset>
- <directory>src</directory>
- <followSymlinks>false</followSymlinks>
- </fileset>
- </filesets>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>This class copies a POI file system to a new file and compares the copy
+ * with the original.</p>
+ *
+ * <p>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.</p>
+ *
+ * <p>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.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class CopyCompare
+{
+ /**
+ * <p>Runs the example program. The application expects one or two
+ * arguments:</p>
+ *
+ * <ol>
+ *
+ * <li><p>The first argument is the disk file name of the POI filesystem to
+ * copy.</p></li>
+ *
+ * <li><p>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.</p></li>
+ *
+ * </ol>
+ *
+ * @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());
+ }
+
+
+
+ /**
+ * <p>Compares two {@link DirectoryEntry} instances of a POI file system.
+ * The directories must contain the same streams with the same names and
+ * contents.</p>
+ *
+ * @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 <code>true</code> if the directories are equal, else
+ * <code>false</code>.
+ * @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;
+ }
+
+
+
+ /**
+ * <p>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.</p>
+ *
+ * @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 <code>true</code> if the documents are equal, else
+ * <code>false</code>.
+ * @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;
+ }
+
+
+
+ /**
+ * <p>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.</p>
+ */
+ static class CopyFile implements POIFSReaderListener
+ {
+ String dstName;
+ OutputStream out;
+ POIFSFileSystem poiFs;
+
+
+ /**
+ * <p>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.</p>
+ *
+ * @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();
+ }
+
+
+ /**
+ * <p>The method is called by POI's eventing API for each file in the
+ * origin POIFS.</p>
+ */
+ 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));
+ }
+ }
+
+
+
+ /**
+ * <p>Writes a {@link PropertySet} to a POI filesystem.</p>
+ *
+ * @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());
+ }
+
+
+
+ /**
+ * <p>Copies the bytes from a {@link DocumentInputStream} to a new
+ * stream in a POI filesystem.</p>
+ *
+ * @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);
+ }
+
+
+ /**
+ * <p>Writes the POI file system to a disk file.</p>
+ *
+ * @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();
+
+
+
+ /**
+ * <p>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.</p>
+ *
+ * <p>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.</p>
+ *
+ * @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);
+ }
+ }
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>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:</p>
+ *
+ * <ul>
+ *
+ * <li><p>Open the POI filesystem.</p></li>
+ *
+ * <li><p>Read the summary information.</p></li>
+ *
+ * <li><p>Read and print the "author" property.</p></li>
+ *
+ * <li><p>Change the author to "Rainer Klute".</p></li>
+ *
+ * <li><p>Read the document summary information.</p></li>
+ *
+ * <li><p>Read and print the "category" property.</p></li>
+ *
+ * <li><p>Change the category to "POI example".</p></li>
+ *
+ * <li><p>Read the custom properties (if available).</p></li>
+ *
+ * <li><p>Insert a new custom property.</p></li>
+ *
+ * <li><p>Write the custom properties back to the document summary
+ * information.</p></li>
+ *
+ * <li><p>Write the summary information to the POI filesystem.</p></li>
+ *
+ * <li><p>Write the document summary information to the POI filesystem.</p></li>
+ *
+ * <li><p>Write the POI filesystem back to the original file.</p></li>
+ *
+ * </ol>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de">klute@rainer-klute.de</a>
+ */
+public class ModifyDocumentSummaryInformation {
+
+ /**
+ * <p>Main method - see class description.</p>
+ *
+ * @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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>Sample application showing how to read a document's custom property set.
+ * Call it with the document's file name as command-line parameter.</p>
+ *
+ * <p>Explanations can be found in the HPSF HOW-TO.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class ReadCustomPropertySets
+{
+
+ /**
+ * <p>Runs the example program.</p>
+ *
+ * @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);
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>Sample application showing how to read a OLE 2 document's
+ * title. Call it with the document's file name as command line
+ * parameter.</p>
+ *
+ * <p>Explanations can be found in the HPSF HOW-TO.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class ReadTitle
+{
+ /**
+ * <p>Runs the example program.</p>
+ *
+ * @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.");
+ }
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>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:</p>
+ *
+ * <ul>
+ *
+ * <li><p>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.</p></li>
+ *
+ * <li><p>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.</p></li>
+ *
+ * </ul>
+ *
+ * <p>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.</p>
+ *
+ * <p>Further explanations can be found in the HPSF HOW-TO.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class WriteAuthorAndTitle
+{
+ /**
+ * <p>Runs the example program.</p>
+ *
+ * @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();
+ }
+
+
+
+ /**
+ * <p>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.</p>
+ */
+ static class ModifySICopyTheRest implements POIFSReaderListener
+ {
+ String dstName;
+ OutputStream out;
+ POIFSFileSystem poiFs;
+
+
+ /**
+ * <p>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.</p>
+ *
+ * @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();
+ }
+
+
+ /**
+ * <p>The method is called by POI's eventing API for each file in the
+ * origin POIFS.</p>
+ */
+ 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));
+ }
+ }
+
+
+ /**
+ * <p>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.</p>
+ *
+ * @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);
+ }
+
+
+ /**
+ * <p>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.</p>
+ *
+ * @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());
+ }
+
+
+
+ /**
+ * <p>Copies the bytes from a {@link DocumentInputStream} to a new
+ * stream in a POI filesystem.</p>
+ *
+ * @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);
+ }
+
+
+ /**
+ * <p>Writes the POI file system to a disk file.</p>
+ *
+ * @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();
+
+
+
+ /**
+ * <p>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.</p>
+ *
+ * <p>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.</p>
+ *
+ * @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);
+ }
+ }
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>This class is a simple sample application showing how to create a property
+ * set and write it to disk.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class WriteTitle
+{
+ /**
+ * <p>Runs the example program.</p>
+ *
+ * @param args Command-line arguments. The first and only command-line
+ * argument is the name of the POI file system to create.
+ * @throws 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));
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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);
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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");
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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);
+ }
+ }
+ }
+
+ }
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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 <scale> -slide <num>] ppt");
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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);
+ }
+ }
+ }
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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 <xls file> [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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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);
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.
+ *
+ * <p>
+ * Excel comment is a kind of a text shape,
+ * so inserting a comment is very similar to placing a text box in a worksheet
+ * </p>
+ *
+ * @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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.hssf.usermodel.examples;\r
+\r
+import org.apache.poi.hssf.usermodel.*;\r
+import org.apache.poi.poifs.filesystem.DirectoryNode;\r
+import org.apache.poi.poifs.filesystem.Entry;\r
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;\r
+import org.apache.poi.hwpf.HWPFDocument;\r
+import org.apache.poi.hslf.HSLFSlideShow;\r
+import org.apache.poi.hslf.usermodel.SlideShow;\r
+\r
+import java.io.FileInputStream;\r
+import java.util.Iterator;\r
+\r
+/**\r
+ * Demonstrates how you can extract embedded data from a .xls file\r
+ */\r
+public class EmeddedObjects {\r
+ public static void main(String[] args) throws Exception {\r
+ POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));\r
+ HSSFWorkbook workbook = new HSSFWorkbook(fs);\r
+ for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {\r
+ //the OLE2 Class Name of the object\r
+ String oleName = obj.getOLE2ClassName();\r
+ if (oleName.equals("Worksheet")) {\r
+ DirectoryNode dn = (DirectoryNode) obj.getDirectory();\r
+ HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, fs, false);\r
+ //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets());\r
+ } else if (oleName.equals("Document")) {\r
+ DirectoryNode dn = (DirectoryNode) obj.getDirectory();\r
+ HWPFDocument embeddedWordDocument = new HWPFDocument(dn);\r
+ //System.out.println(entry.getName() + ": " + embeddedWordDocument.getRange().text());\r
+ } else if (oleName.equals("Presentation")) {\r
+ DirectoryNode dn = (DirectoryNode) obj.getDirectory();\r
+ SlideShow embeddedPowerPointDocument = new SlideShow(new HSLFSlideShow(dn));\r
+ //System.out.println(entry.getName() + ": " + embeddedPowerPointDocument.getSlides().length);\r
+ } else {\r
+ if(obj.hasDirectoryEntry()){\r
+ // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is\r
+ DirectoryNode dn = (DirectoryNode) obj.getDirectory();\r
+ for (Iterator entries = dn.getEntries(); entries.hasNext();) {\r
+ Entry entry = (Entry) entries.next();\r
+ //System.out.println(oleName + "." + entry.getName());\r
+ }\r
+ } else {\r
+ // There is no DirectoryEntry\r
+ // Recover the object's data from the HSSFObjectData instance.\r
+ byte[] objectData = obj.getObjectData();\r
+ }\r
+ }\r
+ }\r
+ }\r
+}\r
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.");
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.<br/>
+ *
+ * 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)}.<br/>
+ *
+ * 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.<br/>
+ *
+ * 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();
+ }
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+\r
+\r
+package org.apache.poi.hssf.usermodel.examples;\r
+\r
+import java.io.File;\r
+import java.io.FileOutputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.hssf.usermodel.HSSFSheet;\r
+import org.apache.poi.hssf.usermodel.HSSFRow;\r
+import org.apache.poi.hssf.usermodel.HSSFCell;\r
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;\r
+import org.apache.poi.hssf.usermodel.HSSFDataFormat;\r
+import org.apache.poi.hssf.usermodel.HSSFRichTextString;\r
+\r
+/**\r
+ * This class contains code that demonstrates how to insert plain, numbered\r
+ * and bulleted lists into an Excel spreadsheet cell.\r
+ *\r
+ * Look at the code contained in the demonstrateMethodCalls() method. It calls\r
+ * other methods that create plain, numbered and bulleted single and\r
+ * multi-level lists. The demonstrateMethodCalls() method appears at the top\r
+ * of the class definition.\r
+ *\r
+ * Though different methods are provided to construct single and multi-level\r
+ * plain, numbered and bulleted lists, close examination will reveal that they\r
+ * are not strictly necessary. If the inputs to the listInCell() and\r
+ * multilLevelListInCell() methods are constructed to include the bullet\r
+ * character or the item numbers then these methods alone may be sufficient.\r
+ *\r
+ * @author Mark Beardsley [msb at apache.org]\r
+ */\r
+public class InCellLists {\r
+\r
+ // This character looks like a solid, black, loser case letter 'o'\r
+ // positioned up from the base line of the text.\r
+ private static final char BULLET_CHARACTER = '\u2022';\r
+\r
+ // The tab character - \t - cannot be used to create a tab space\r
+ // within a cell as it is rendered as a square. Therefore, four\r
+ // spaces are used to simulate that character.\r
+ private static final String TAB = " ";\r
+\r
+ /**\r
+ * Call each of the list creation methods.\r
+ *\r
+ * @param outputFilename A String that encapsulates the name of and path to\r
+ * the Excel spreadsheet file this code will create.\r
+ */\r
+ public void demonstrateMethodCalls(String outputFilename) {\r
+ HSSFWorkbook workbook = null;\r
+ HSSFSheet sheet = null;\r
+ HSSFRow row = null;\r
+ HSSFCell cell = null;\r
+ File outputFile = null;\r
+ FileOutputStream fos = null;\r
+ ArrayList<MultiLevelListItem> multiLevelListItems = null;\r
+ ArrayList<String> listItems = null;\r
+ String listItem = null;\r
+ try {\r
+ workbook = new HSSFWorkbook();\r
+ sheet = workbook.createSheet("In Cell Lists");\r
+ row = sheet.createRow(0);\r
+\r
+ // Create a cell at A1 and insert a single, bulleted, item into\r
+ // that cell.\r
+ cell = row.createCell(0);\r
+ this.bulletedItemInCell(workbook, "List Item", cell);\r
+\r
+ // Create a cell at A2 and insert a plain list - that is one\r
+ // whose items are neither bulleted or numbered - into that cell.\r
+ row = sheet.createRow(1);\r
+ cell = row.createCell(0);\r
+ listItems = new ArrayList<String>();\r
+ listItems.add("List Item One.");\r
+ listItems.add("List Item Two.");\r
+ listItems.add("List Item Three.");\r
+ listItems.add("List Item Four.");\r
+ this.listInCell(workbook, listItems, cell);\r
+ // The row height and cell width are set here to ensure that the\r
+ // list may be seen.\r
+ row.setHeight((short)1100);\r
+ sheet.setColumnWidth(0, 9500);\r
+\r
+ // Create a cell at A3 and insert a numbered list into that cell.\r
+ // Note that a couple of items have been added to the listItems\r
+ // ArrayList\r
+ row = sheet.createRow(2);\r
+ cell = row.createCell(0);\r
+ listItems.add("List Item Five.");\r
+ listItems.add("List Item Six.");\r
+ this.numberedListInCell(workbook, listItems, cell, 1, 2);\r
+ row.setHeight((short)1550);\r
+\r
+ // Create a cell at A4 and insert a numbered list into that cell.\r
+ // Note that a couple of items have been added to the listItems\r
+ // ArrayList\r
+ row = sheet.createRow(3);\r
+ cell = row.createCell(0);\r
+ listItems.add("List Item Seven.");\r
+ listItems.add("List Item Eight.");\r
+ listItems.add("List Item Nine.");\r
+ listItems.add("List Item Ten.");\r
+ this.bulletedListInCell(workbook, listItems, cell);\r
+ row.setHeight((short)2550);\r
+\r
+ // Insert a plain, multi-level list into cell A5. Note that\r
+ // the major difference here is that the list items are passed as\r
+ // an ArrayList of MultiLevelListItems. Note that an ArrayList\r
+ // of instances of an inner class was used here in preference to\r
+ // a Hashtable or HashMap as the ArrayList will preserve the\r
+ // ordering of the items added to it; the first item added will\r
+ // be the first item recovered and the last item added, the last\r
+ // item recovered.\r
+ row = sheet.createRow(4);\r
+ cell = row.createCell(0);\r
+ multiLevelListItems = new ArrayList<MultiLevelListItem>();\r
+ listItems = new ArrayList<String>();\r
+ listItems.add("ML List Item One - Sub Item One.");\r
+ listItems.add("ML List Item One - Sub Item Two.");\r
+ listItems.add("ML List Item One - Sub Item Three.");\r
+ listItems.add("ML List Item One - Sub Item Four.");\r
+ multiLevelListItems.add(new MultiLevelListItem("List Item One.", listItems));\r
+ // Passing either null or an empty ArrayList will signal that\r
+ // there are no lower level items associated with the top level\r
+ // item\r
+ multiLevelListItems.add(new MultiLevelListItem("List Item Two.", null));\r
+ multiLevelListItems.add(new MultiLevelListItem("List Item Three.", null));\r
+ listItems = new ArrayList<String>();\r
+ listItems.add("ML List Item Four - Sub Item One.");\r
+ listItems.add("ML List Item Four - Sub Item Two.");\r
+ listItems.add("ML List Item Four - Sub Item Three.");\r
+ multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems));\r
+ this.multiLevelListInCell(workbook, multiLevelListItems, cell);\r
+ row.setHeight((short)2800);\r
+\r
+ // Insert a numbered multi-level list into cell A6. Note that the\r
+ // same ArrayList as constructed for the above plain multi-level\r
+ // list example will be re-used\r
+ row = sheet.createRow(5);\r
+ cell = row.createCell(0);\r
+ this.multiLevelNumberedListInCell(workbook, multiLevelListItems,\r
+ cell, 1, 1, 1, 2);\r
+ row.setHeight((short)2800);\r
+\r
+ // Insert a numbered multi-level list into cell A7. Note that the\r
+ // same ArrayList as constructed for the plain multi-level list\r
+ // example will be re-used\r
+ row = sheet.createRow(6);\r
+ cell = row.createCell(0);\r
+ this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell);\r
+ row.setHeight((short)2800);\r
+\r
+ // Save the completed workbook\r
+ outputFile = new File(outputFilename);\r
+ fos = new FileOutputStream(outputFile);\r
+ workbook.write(fos);\r
+ }\r
+ catch(FileNotFoundException fnfEx) {\r
+ System.out.println("Caught a: " + fnfEx.getClass().getName());\r
+ System.out.println("Message: " + fnfEx.getMessage());\r
+ System.out.println("Stacktrace follows...........");\r
+ fnfEx.printStackTrace(System.out);\r
+ }\r
+ catch(IOException ioEx) {\r
+ System.out.println("Caught a: " + ioEx.getClass().getName());\r
+ System.out.println("Message: " + ioEx.getMessage());\r
+ System.out.println("Stacktrace follows...........");\r
+ ioEx.printStackTrace(System.out);\r
+ }\r
+ finally {\r
+ if(fos != null) {\r
+ try {\r
+ fos.close();\r
+ }\r
+ catch(IOException ioEx) {\r
+\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Inserts a single bulleted item into a cell.\r
+ *\r
+ * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
+ * cell.\r
+ * @param listItem An instance of the String class encapsulating the\r
+ * items text.\r
+ * @param cell An instance of the HSSFCell class that encapsulates a\r
+ * reference to the spreadsheet cell into which the list item\r
+ * will be written.\r
+ */\r
+ public void bulletedItemInCell(HSSFWorkbook workbook, String listItem, HSSFCell cell) {\r
+ // A format String must be built to ensure that the contents of the\r
+ // cell appear as a bulleted item.\r
+ HSSFDataFormat format = workbook.createDataFormat();\r
+ String formatString = InCellLists.BULLET_CHARACTER + " @";\r
+ int formatIndex = format.getFormat(formatString);\r
+\r
+ // Construct an HSSFCellStyle and set it's data formt to use the\r
+ // object created above.\r
+ HSSFCellStyle bulletStyle = workbook.createCellStyle();\r
+ bulletStyle.setDataFormat((short)formatIndex);\r
+\r
+ // Set the cells contents and style.\r
+ cell.setCellValue(new HSSFRichTextString(listItem));\r
+ cell.setCellStyle(bulletStyle);\r
+ }\r
+\r
+ /**\r
+ * Inserts a list of plain items - that is items that are neither\r
+ * numbered or bulleted - into a single cell.\r
+ *\r
+ * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
+ * cell.\r
+ * @param listItems An ArrayList whose elements encapsulate the text for\r
+ * the list's items.\r
+ * @param cell An instance of the HSSFCell class that encapsulates a\r
+ * reference to the spreadsheet cell into which the list\r
+ * will be written.\r
+ */\r
+ public void listInCell(HSSFWorkbook workbook, ArrayList<String> listItems, HSSFCell cell) {\r
+ StringBuffer buffer = new StringBuffer();\r
+ HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
+ wrapStyle.setWrapText(true);\r
+ for(String listItem : listItems) {\r
+ buffer.append(listItem);\r
+ buffer.append("\n");\r
+ }\r
+ // The StringBuffer's contents are the source for the contents\r
+ // of the cell.\r
+ cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
+ cell.setCellStyle(wrapStyle);\r
+ }\r
+\r
+ /**\r
+ * Inserts a numbered list into a single cell.\r
+ *\r
+ * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
+ * cell.\r
+ * @param listItems An ArrayList whose elements encapsulate the text for\r
+ * the lists items.\r
+ * @param cell An instance of the HSSFCell class that encapsulates a\r
+ * reference to the spreadsheet cell into which the list\r
+ * will be written.\r
+ * @param startingValue A primitive int containing the number for the first\r
+ * item in the list.\r
+ * @param increment A primitive int containing the value that should be used\r
+ * to calculate subsequent item numbers.\r
+ */\r
+ public void numberedListInCell(HSSFWorkbook workbook,\r
+ ArrayList<String> listItems,\r
+ HSSFCell cell,\r
+ int startingValue,\r
+ int increment) {\r
+ StringBuffer buffer = new StringBuffer();\r
+ int itemNumber = startingValue;\r
+ // Note that again, an HSSFCellStye object is required and that\r
+ // it's wrap text property should be set to 'true'\r
+ HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
+ wrapStyle.setWrapText(true);\r
+ // Note that the basic method is identical to the listInCell() method\r
+ // with one difference; a number prefixed to the items text.\r
+ for(String listItem : listItems) {\r
+ buffer.append(String.valueOf(itemNumber) + ". ");\r
+ buffer.append(listItem);\r
+ buffer.append("\n");\r
+ itemNumber += increment;\r
+ }\r
+ // The StringBuffer's contents are the source for the contents\r
+ // of the cell.\r
+ cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
+ cell.setCellStyle(wrapStyle);\r
+ }\r
+\r
+ /**\r
+ * Insert a bulleted list into a cell.\r
+ *\r
+ * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
+ * cell.\r
+ * @param listItems An ArrayList whose elements encapsulate the text for\r
+ * the lists items.\r
+ * @param cell An instance of the HSSFCell class that encapsulates a\r
+ * reference to the spreadsheet cell into which the list\r
+ * will be written.\r
+ */\r
+ public void bulletedListInCell(HSSFWorkbook workbook,\r
+ ArrayList<String> listItems,\r
+ HSSFCell cell) {\r
+ StringBuffer buffer = new StringBuffer();\r
+ // Note that again, an HSSFCellStye object is required and that\r
+ // it's wrap text property should be set to 'true'\r
+ HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
+ wrapStyle.setWrapText(true);\r
+ // Note that the basic method is identical to the listInCell() method\r
+ // with one difference; the bullet character prefixed to the items text.\r
+ for(String listItem : listItems) {\r
+ buffer.append(InCellLists.BULLET_CHARACTER + " ");\r
+ buffer.append(listItem);\r
+ buffer.append("\n");\r
+ }\r
+ // The StringBuffer's contents are the source for the contents\r
+ // of the cell.\r
+ cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
+ cell.setCellStyle(wrapStyle);\r
+ }\r
+\r
+ /**\r
+ * Insert a multi-level list into a cell.\r
+ *\r
+ * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
+ * cell.\r
+ * @param multiLevelListItems An ArrayList whose elements contain instances\r
+ * of the MultiLevelListItem class. Each element\r
+ * encapsulates the text for the high level item\r
+ * along with an ArrayList. Each element of this\r
+ * ArrayList encapsulates the text for a lower\r
+ * level item.\r
+ * @param cell An instance of the HSSFCell class that encapsulates a\r
+ * reference to the spreadsheet cell into which the list\r
+ * will be written.\r
+ */\r
+ public void multiLevelListInCell(HSSFWorkbook workbook,\r
+ ArrayList<MultiLevelListItem> multiLevelListItems,\r
+ HSSFCell cell) {\r
+ StringBuffer buffer = new StringBuffer();\r
+ ArrayList<String> lowerLevelItems = null;\r
+ // Note that again, an HSSFCellStye object is required and that\r
+ // it's wrap text property should be set to 'true'\r
+ HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
+ wrapStyle.setWrapText(true);\r
+ // Step through the ArrayList of MultilLevelListItem instances.\r
+ for(MultiLevelListItem multiLevelListItem : multiLevelListItems) {\r
+ // For each element in the ArrayList, get the text for the high\r
+ // level list item......\r
+ buffer.append(multiLevelListItem.getItemText());\r
+ buffer.append("\n");\r
+ // and then an ArrayList whose elements encapsulate the text\r
+ // for the lower level list items.\r
+ lowerLevelItems = multiLevelListItem.getLowerLevelItems();\r
+ if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) {\r
+ for(String item : lowerLevelItems) {\r
+ buffer.append(InCellLists.TAB);\r
+ buffer.append(item);\r
+ buffer.append("\n");\r
+ }\r
+ }\r
+ }\r
+ // The StringBuffer's contents are the source for the contents\r
+ // of the cell.\r
+ cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
+ cell.setCellStyle(wrapStyle);\r
+ }\r
+\r
+ /**\r
+ * Insert a multi-level list into a cell.\r
+ *\r
+ * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
+ * cell.\r
+ * @param multiLevelListItems An ArrayList whose elements contain instances\r
+ * of the MultiLevelListItem class. Each element\r
+ * encapsulates the text for the high level item\r
+ * along with an ArrayList. Each element of this\r
+ * ArrayList encapsulates the text for a lower\r
+ * level item.\r
+ * @param cell An instance of the HSSFCell class that encapsulates a\r
+ * reference to the spreadsheet cell into which the list\r
+ * will be written.\r
+ * @param highLevelStartingValue A primitive int containing the number\r
+ * for the first high level item in the list.\r
+ * @param highLevelIncrement A primitive int containing the value that\r
+ * should be used to calculate the number of\r
+ * subsequent high level item.\r
+ * @param lowLevelStartingValue A primitive int will containing the number\r
+ * for the first low level item associated\r
+ * with a high level item.\r
+ * @param lowLevelIncrement A primitive int containing the value that\r
+ * should be used to calculate the number of\r
+ * subsequent low level item.\r
+ */\r
+ public void multiLevelNumberedListInCell(HSSFWorkbook workbook,\r
+ ArrayList<MultiLevelListItem> multiLevelListItems,\r
+ HSSFCell cell,\r
+ int highLevelStartingValue,\r
+ int highLevelIncrement,\r
+ int lowLevelStartingValue,\r
+ int lowLevelIncrement) {\r
+ StringBuffer buffer = new StringBuffer();\r
+ int highLevelItemNumber = highLevelStartingValue;\r
+ int lowLevelItemNumber = 0;\r
+ ArrayList<String> lowerLevelItems = null;\r
+ // Note that again, an HSSFCellStye object is required and that\r
+ // it's wrap text property should be set to 'true'\r
+ HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
+ wrapStyle.setWrapText(true);\r
+ // Step through the ArrayList of MultilLevelListItem instances.\r
+ for(MultiLevelListItem multiLevelListItem : multiLevelListItems) {\r
+ // For each element in the ArrayList, get the text for the high\r
+ // level list item......\r
+ buffer.append(String.valueOf(highLevelItemNumber));\r
+ buffer.append(". ");\r
+ buffer.append(multiLevelListItem.getItemText());\r
+ buffer.append("\n");\r
+ // and then an ArrayList whose elements encapsulate the text\r
+ // for the lower level list items.\r
+ lowerLevelItems = multiLevelListItem.getLowerLevelItems();\r
+ if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) {\r
+ lowLevelItemNumber = lowLevelStartingValue;\r
+ for(String item : lowerLevelItems) {\r
+ buffer.append(InCellLists.TAB);\r
+ buffer.append(String.valueOf(highLevelItemNumber));\r
+ buffer.append(".");\r
+ buffer.append(String.valueOf(lowLevelItemNumber));\r
+ buffer.append(" ");\r
+ buffer.append(item);\r
+ buffer.append("\n");\r
+ lowLevelItemNumber += lowLevelIncrement;\r
+ }\r
+ }\r
+ highLevelItemNumber += highLevelIncrement;\r
+ }\r
+ // The StringBuffer's contents are the source for the contents\r
+ // of the cell.\r
+ cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
+ cell.setCellStyle(wrapStyle);\r
+ }\r
+\r
+ /**\r
+ * Insert a bulleted multi-level list into a cell.\r
+ *\r
+ * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
+ * cell.\r
+ * @param multiLevelListItems An ArrayList whose elements contain instances\r
+ * of the MultiLevelListItem class. Each element\r
+ * encapsulates the text for the high level item\r
+ * along with an ArrayList. Each element of this\r
+ * ArrayList encapsulates the text for a lower\r
+ * level item.\r
+ * @param cell An instance of the HSSFCell class that encapsulates a\r
+ * reference to the spreadsheet cell into which the list\r
+ * will be written.\r
+ */\r
+ public void multiLevelBulletedListInCell(HSSFWorkbook workbook,\r
+ ArrayList<MultiLevelListItem> multiLevelListItems,\r
+ HSSFCell cell) {\r
+ StringBuffer buffer = new StringBuffer();\r
+ ArrayList<String> lowerLevelItems = null;\r
+ // Note that again, an HSSFCellStye object is required and that\r
+ // it's wrap text property should be set to 'true'\r
+ HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
+ wrapStyle.setWrapText(true);\r
+ // Step through the ArrayList of MultilLevelListItem instances.\r
+ for(MultiLevelListItem multiLevelListItem : multiLevelListItems) {\r
+ // For each element in the ArrayList, get the text for the high\r
+ // level list item......\r
+ buffer.append(InCellLists.BULLET_CHARACTER);\r
+ buffer.append(" ");\r
+ buffer.append(multiLevelListItem.getItemText());\r
+ buffer.append("\n");\r
+ // and then an ArrayList whose elements encapsulate the text\r
+ // for the lower level list items.\r
+ lowerLevelItems = multiLevelListItem.getLowerLevelItems();\r
+ if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) {\r
+ for(String item : lowerLevelItems) {\r
+ buffer.append(InCellLists.TAB);\r
+ buffer.append(InCellLists.BULLET_CHARACTER);\r
+ buffer.append(" ");\r
+ buffer.append(item);\r
+ buffer.append("\n");\r
+ }\r
+ }\r
+ }\r
+ // The StringBuffer's contents are the source for the contents\r
+ // of the cell.\r
+ cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
+ cell.setCellStyle(wrapStyle);\r
+ }\r
+\r
+ /**\r
+ * The main entry point to the program. Demonstrates how to call the method\r
+ * that will create an Excel workbook containing many different sorts of\r
+ * lists.\r
+ *\r
+ * @param args the command line arguments.\r
+ */\r
+ public static void main(String[] args) {\r
+ new InCellLists().demonstrateMethodCalls("C:/temp/Latest In Cell List.xls");\r
+ }\r
+\r
+ /**\r
+ * An instance of this inner class models an item or element in a\r
+ * multi-level list. Each multi-level list item consists of the text for the\r
+ * high level items and an ArrayList containing the text for each of the\r
+ * associated lower level items. When written into a cell, each multi-level\r
+ * list item will have this general appearance.\r
+ *\r
+ * Item One\r
+ * Sub Item One.\r
+ * Sub Item Two.\r
+ * Item Two\r
+ * Sub Item One.\r
+ * Sub Item Two.\r
+ * etc.\r
+ *\r
+ * It would be quite possible to modify this class to model much more\r
+ * complex list structures descending through two, three or even more\r
+ * levels.\r
+ */\r
+ public final class MultiLevelListItem {\r
+\r
+ private String itemText = null;\r
+ private ArrayList<String> lowerLevelItems = null;\r
+\r
+ /**\r
+ * Create a new instance of the MultiLevelListItem class using the\r
+ * following parameters.\r
+ *\r
+ * @param itemText A String that encapsulates the text for the high\r
+ * level list item.\r
+ * @param lowerLevelItems An ArrayList whose elements encapsulate the\r
+ * text for the associated lower level list\r
+ * items.\r
+ */\r
+ public MultiLevelListItem(String itemText, ArrayList<String> lowerLevelItems) {\r
+ this.itemText = itemText;\r
+ this.lowerLevelItems = lowerLevelItems;\r
+ }\r
+\r
+ /**\r
+ * Get the text for the high level list item.\r
+ *\r
+ * @return A String that encapsulates the text for the high level list\r
+ * item.\r
+ */\r
+ public String getItemText() {\r
+ return(this.itemText);\r
+ }\r
+\r
+ /**\r
+ * Get the text for the associated lower level list items.\r
+ *\r
+ * @return An ArrayList whose elements each encapsulate the text for a\r
+ * single associated lower level list item.\r
+ */\r
+ public ArrayList<String> getLowerLevelItems() {\r
+ return(this.lowerLevelItems);\r
+ }\r
+ }\r
+}\r
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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 <fauzia.lala at wcom.com>
+ */
+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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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);
+ }
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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);
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+ }
+
+
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+ }
+
+
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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));
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.
+ * <p/>
+ * 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.
+ * <p/>
+ * 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
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<Integer,HSSFColor> 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]);
+ }
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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());
+ }
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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");
+ }
+
+
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<Integer,HSSFColor> 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]);
+ }
+}
--- /dev/null
+
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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);
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<sheetCount;i++) {
+ String sheetName = wb.getSheetName(i);
+ //Add the new sheet to the tabbed pane
+ sheetPane.addTab(sheetName, makeSheetView(wb.getSheetAt(i)));
+ }
+ setLayout(new BorderLayout());
+ add(sheetPane, BorderLayout.CENTER);
+ }
+
+ protected JComponent makeSheetView(HSSFSheet sheet) {
+ JTable sheetView = new JTable(new SVTableModel(sheet));
+ sheetView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
+ sheetView.setDefaultRenderer(HSSFCell.class, cellRenderer);
+ if (allowEdits)
+ sheetView.setDefaultEditor(HSSFCell.class, cellEditor);
+ JTableHeader header = sheetView.getTableHeader();
+ //Dont allow column reordering
+ header.setReorderingAllowed(false);
+ //Only allow column resizing if editing is allowed
+ header.setResizingAllowed(allowEdits);
+
+ //Set the columns the correct size
+ TableColumnModel columns = sheetView.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);
+ }
+
+ //Set the rows to the correct size
+ int rows = sheet.getPhysicalNumberOfRows();
+ Insets insets = cellRenderer.getInsets();
+ //Need to include the insets in the calculation of the row height to use.
+ int extraHeight = insets.bottom+insets.top;
+ for (int i=0; i< rows; i++) {
+ HSSFRow row = sheet.getRow(i);
+ if (row == null) {
+ sheetView.setRowHeight(i, (int)sheet.getDefaultRowHeightInPoints()+extraHeight);
+ } else {
+ sheetView.setRowHeight(i, (int)row.getHeightInPoints()+extraHeight);
+ }
+ }
+
+ //Add the row header to the sheet
+ SVRowHeader rowHeader = new SVRowHeader(sheet, sheetView, extraHeight);
+ JScrollPane scroll = new JScrollPane( sheetView );
+ scroll.setRowHeaderView(rowHeader);
+ return scroll;
+ }
+
+ public void paint(Graphics g) {
+ //JMH I am only overriding this to get a picture of the time taken to paint
+ long start = System.currentTimeMillis();
+ super.paint(g);
+ long elapsed = System.currentTimeMillis()-start;
+ System.out.println("Paint time = "+elapsed);
+ }
+
+ protected MouseListener createTabListener() {
+ return new TabListener();
+ }
+
+ /** This class defines the default MouseListener that listens to
+ * mouse events in the tabbed pane
+ *
+ * The default is to popup a menu when the event occurs over a tab
+ */
+ private class TabListener implements MouseListener {
+ public JPopupMenu popup;
+ public TabListener() {
+ popup = new JPopupMenu("Sheet");
+ popup.add(createInsertSheetAction());
+ popup.add(createDeleteSheetAction());
+ popup.add(createRenameSheetAction());
+ }
+
+ protected Action createInsertSheetAction() {
+ return new InsertSheetAction();
+ }
+
+ protected Action createDeleteSheetAction() {
+ return new DeleteSheetAction();
+ }
+
+ protected Action createRenameSheetAction() {
+ return new RenameSheetAction();
+ }
+
+
+ /** This method will display the popup if the mouseevent is a popup event
+ * and the event occurred over a tab
+ */
+ protected void checkPopup(MouseEvent e) {
+ if (e.isPopupTrigger()) {
+ int tab = sheetPane.getUI().tabForCoordinate(sheetPane, e.getX(), e.getY());
+ if (tab != -1) {
+ popup.show(sheetPane, e.getX(), e.getY());
+ }
+ }
+ }
+
+ public void mouseClicked(MouseEvent e) {
+ checkPopup(e);
+ }
+
+ public void mousePressed(MouseEvent e) {
+ checkPopup(e);
+ }
+
+ public void mouseReleased(MouseEvent e) {
+ checkPopup(e);
+ }
+
+ public void mouseEntered(MouseEvent e) {}
+ public void mouseExited(MouseEvent e) {}
+ }
+
+ /** This class defines the action that is performed when the sheet is renamed*/
+ private class RenameSheetAction extends AbstractAction {
+ public RenameSheetAction() {
+ super("Rename");
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ int tabIndex = sheetPane.getSelectedIndex();
+ if (tabIndex != -1) {
+ String newSheetName = JOptionPane.showInputDialog(sheetPane, "Enter a new Sheetname", "Rename Sheet", JOptionPane.QUESTION_MESSAGE);
+ if (newSheetName != null) {
+ wb.setSheetName(tabIndex, newSheetName);
+ sheetPane.setTitleAt(tabIndex, newSheetName);
+ }
+ }
+ }
+ }
+
+ /** This class defines the action that is performed when a sheet is inserted*/
+ private class InsertSheetAction extends AbstractAction {
+ public InsertSheetAction() {
+ super("Insert");
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ //Create a new sheet then search for the sheet and make sure that the
+ //sheetPane shows it.
+ HSSFSheet newSheet = wb.createSheet();
+ for (int i=0; i<wb.getNumberOfSheets();i++) {
+ HSSFSheet sheet = wb.getSheetAt(i);
+ if (newSheet == sheet) {
+ sheetPane.insertTab(wb.getSheetName(i), null, makeSheetView(sheet), null, i);
+ }
+ }
+ }
+ }
+
+ /** This class defines the action that is performed when the sheet is deleted*/
+ private class DeleteSheetAction extends AbstractAction {
+ public DeleteSheetAction() {
+ super("Delete");
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ int tabIndex = sheetPane.getSelectedIndex();
+ if (tabIndex != -1) {
+ if (JOptionPane.showConfirmDialog(sheetPane, "Are you sure that you want to delete the selected sheet", "Delete Sheet?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
+ wb.removeSheetAt(tabIndex);
+ sheetPane.remove(tabIndex);
+ }
+ }
+ }
+ }
+
+ public boolean isEditable() {
+ return allowEdits;
+ }
+
+ /**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");
+ }
+ try {
+ FileInputStream in = new FileInputStream(args[0]);
+ HSSFWorkbook wb = new HSSFWorkbook(in);
+ in.close();
+
+ SViewerPanel p = new SViewerPanel(wb, true);
+ JFrame frame;
+ frame = new JFrame() {
+ 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("Viewer Frame");
+ frame.getContentPane().add(p, BorderLayout.CENTER);
+ frame.setSize(800,640);
+ Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
+ frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
+ frame.setVisible(true);
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ System.exit(1);
+ }
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.brush;
+
+import java.awt.*;
+
+/**
+ * This is a basic brush that just draws the line with the given parameters.
+ * This is a {@link BasicStroke} object that can be used as a {@link Brush}.
+ *
+ * @author Ken Arnold, Industrious Media LLC
+ * @see BasicStroke
+ */
+public class BasicBrush extends BasicStroke implements Brush {
+ /**
+ * Creates a new basic brush with the given width. Invokes {@link
+ * BasicStroke#BasicStroke(float)}
+ *
+ * @param width The brush width.
+ *
+ * @see BasicStroke#BasicStroke(float)
+ */
+ public BasicBrush(float width) {
+ super(width);
+ }
+
+ /**
+ * Creates a new basic brush with the given width, cap, and join. Invokes
+ * {@link BasicStroke#BasicStroke(float,int,int)}
+ *
+ * @param width The brush width.
+ * @param cap The capping style.
+ * @param join The join style.
+ *
+ * @see BasicStroke#BasicStroke(float, int, int)
+ */
+ public BasicBrush(float width, int cap, int join) {
+ super(width, cap, join);
+ }
+
+ /**
+ * Creates a new basic brush with the given parameters. Invokes {@link
+ * BasicStroke#BasicStroke(float,int,int,float,float[],float)} with a miter
+ * limit of 11 (the normal default value).
+ *
+ * @param width The brush width.
+ * @param cap The capping style.
+ * @param join The join style.
+ * @param dashes The dash intervals.
+ * @param dashPos The intial dash position in the dash intervals.
+ *
+ * @see BasicStroke#BasicStroke(float, int, int, float, float[], float)
+ */
+ public BasicBrush(float width, int cap, int join, float[] dashes,
+ int dashPos) {
+ super(width, cap, join, 11.0f, dashes, dashPos);
+ }
+}
\ No newline at end of file
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.brush;
+
+import java.awt.*;
+
+/**
+ * This is the type you must implement to create a brush that will be used for a
+ * spreadsheet border.
+ *
+ * @author Ken Arnold, Industrious Media LLC
+ */
+public interface Brush extends Stroke {
+ /** Returns the width of the brush. */
+ float getLineWidth();
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.brush;
+
+import java.awt.*;
+
+/**
+ * This Stroke implementation applies a BasicStroke to a shape twice. If you
+ * draw with this Stroke, then instead of outlining the shape, you're outlining
+ * the outline of the shape.
+ *
+ * @author Ken Arnold, Industrious Media LLC
+ */
+public class DoubleStroke implements Brush {
+ BasicStroke stroke1, stroke2; // the two strokes to use
+
+ /**
+ * Creates a new double-stroke brush. This surrounds a cell with a two
+ * lines separated by white space between.
+ *
+ * @param width1 The width of the blank space in the middle
+ * @param width2 The width of the each of the two drawn strokes.
+ */
+ public DoubleStroke(float width1, float width2) {
+ stroke1 = new BasicStroke(width1); // Constructor arguments specify
+ stroke2 = new BasicStroke(width2); // the line widths for the strokes
+ }
+
+ /**
+ * Stroke the outline.
+ *
+ * @param s The shape in which to stroke.
+ *
+ * @return The created stroke as a new shape.
+ */
+ public Shape createStrokedShape(Shape s) {
+ // Use the first stroke to create an outline of the shape
+ Shape outline = stroke1.createStrokedShape(s);
+ // Use the second stroke to create an outline of that outline.
+ // It is this outline of the outline that will be filled in
+ return stroke2.createStrokedShape(outline);
+ }
+
+ /** {@inheritDoc} */
+ public float getLineWidth() {
+ return stroke1.getLineWidth() + 2 * stroke2.getLineWidth();
+ }
+}
\ No newline at end of file
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.brush;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.geom.*;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This class is used to hold pending brush paintings. The model is that some
+ * border drawing requires drawing strokes after all the cells have been
+ * painted. The list of pending paintings can be put in this object during the
+ * initial paint of the component, and then executed at the appropriate time,
+ * such as at the end of the containing object's {@link
+ * JComponent#paintChildren(Graphics)} method.
+ * <p/>
+ * 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<Painting> 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<Painting>();
+ 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.)
+ * <p/>
+ * 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 <tt>null</tt>
+ * 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
--- /dev/null
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!--
+ ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ ====================================================================
+-->
+<html>
+
+<body>
+This package contains some brushes that are used when drawing borders for Excel
+cells.
+</body>
+</html>
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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 ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
+ _out.write ("<!DOCTYPE document PUBLIC \"-//APACHE//DTD Documentation V1.1//EN\" \"./dtd/document-v11.dtd\">\r\n");
+ }
+
+ public void openDocument ()
+ throws IOException
+ {
+ _out.write ("<document>\r\n");
+ }
+ public void closeDocument ()
+ throws IOException
+ {
+ _out.write ("</document>\r\n");
+ }
+
+
+ public void openBody ()
+ throws IOException
+ {
+ _out.write ("<body>\r\n");
+ }
+
+ public void closeBody ()
+ throws IOException
+ {
+ _out.write ("</body>\r\n");
+ }
+
+
+ public void openSection ()
+ throws IOException
+ {
+ _out.write ("<section>");
+
+ }
+
+ public void closeSection ()
+ throws IOException
+ {
+ _out.write ("</section>");
+
+ }
+
+ public void openTitle ()
+ throws IOException
+ {
+ _out.write ("<title>");
+ }
+
+ public void closeTitle ()
+ throws IOException
+ {
+ _out.write ("</title>");
+ }
+
+ public void writePlainText (String text)
+ throws IOException
+ {
+ _out.write (text);
+ }
+
+ public void openParagraph ()
+ throws IOException
+ {
+ _out.write ("<p>");
+ }
+
+ public void closeParagraph ()
+ throws IOException
+ {
+ _out.write ("</p>");
+ }
+
+ public void openSource ()
+ throws IOException
+ {
+ _out.write ("<source><![CDATA[");
+ }
+ public void closeSource ()
+ throws IOException
+ {
+ _out.write ("]]></source>");
+ }
+
+
+ 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();
+ }
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+
+
+/**
+ * <p>Provides utility methods for encoding and decoding hexadecimal
+ * data.</p>
+ *
+ * @author Rainer Klute (klute@rainer-klute.de) - with portions from Tomcat
+ */
+public class Codec
+{
+
+ /**
+ * <p>The nibbles' hexadecimal values. A nibble is a half byte.</p>
+ */
+ 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'};
+
+
+
+ /**
+ * <p>Converts a string into its hexadecimal notation.</p>
+ */
+ public static String hexEncode(final String s)
+ {
+ return hexEncode(s.getBytes());
+ }
+
+
+
+ /**
+ * <p>Converts a byte array into its hexadecimal notation.</p>
+ */
+ public static String hexEncode(final byte[] s)
+ {
+ return hexEncode(s, 0, s.length);
+ }
+
+
+
+ /**
+ * <p>Converts a part of a byte array into its hexadecimal
+ * notation.</p>
+ */
+ 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();
+ }
+
+
+
+ /**
+ * <p>Converts a single byte into its hexadecimal notation.</p>
+ */
+ 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();
+ }
+
+
+
+ /**
+ * <p>Converts a short value (16-bit) into its hexadecimal
+ * notation.</p>
+ */
+ 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();
+ }
+
+
+
+ /**
+ * <p>Converts an int value (32-bit) into its hexadecimal
+ * notation.</p>
+ */
+ 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();
+ }
+
+
+
+ /**
+ * <p>Converts a long value (64-bit) into its hexadecimal
+ * notation.</p>
+ */
+ 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();
+ }
+
+
+
+ /**
+ * <p>Converts a class ID into its hexadecimal notation.</p>
+ */
+ public static String hexEncode(final ClassID classID)
+ {
+ return hexEncode(classID.getBytes());
+ }
+
+
+
+ /**
+ * <p>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'.</p>
+ *
+ * @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;
+ }
+
+
+
+ /**
+ * <p>Decodes a nibble.</p>
+ *
+ * @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 <em>c</em> 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.");
+ }
+
+
+
+ /**
+ * <p>For testing.</p>
+ */
+ 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);
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.*;
+
+/**
+ * <p>Describes the most important (whatever that is) features of a
+ * {@link POIFSDocument}.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class DocumentDescriptor
+{
+ String name;
+ POIFSDocumentPath path;
+ DocumentInputStream stream;
+
+ int size;
+ byte[] bytes;
+
+
+ /**
+ * <p>Creates a {@link DocumentDescriptor}.</p>
+ *
+ * @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);
+ }
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.*;
+
+/**
+ * <p>{@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.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+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;
+ }
+
+
+ /**
+ * <p>Renders {@link DocumentDescriptor} as a string.</p>
+ */
+ 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();
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.*;
+
+/**
+ * <p>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.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class ExtendableTreeCellRenderer implements TreeCellRenderer
+{
+
+ /**
+ * <p>Maps classes to renderers.</p>
+ */
+ 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;
+ }
+ });
+ }
+
+
+
+ /**
+ * <p>Registers a renderer for a class.</p>
+ **/
+ public void register(final Class c, final TreeCellRenderer renderer)
+ {
+ renderers.put(c, renderer);
+ }
+
+
+
+ /**
+ * <p>Unregisters a renderer for a class. The renderer for the
+ * {@link Object} class cannot be unregistered.</p>
+ */
+ public void unregister(final Class c)
+ {
+ if (c == Object.class)
+ throw new IllegalArgumentException
+ ("Renderer for Object cannot be unregistered.");
+ renderers.put(c, null);
+ }
+
+
+
+ /**
+ * <p>Renders an object in a tree cell depending of the object's
+ * class.</p>
+ *
+ * @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);
+ }
+
+
+
+ /**
+ * <p>Find the renderer for the specified class.</p>
+ */
+ 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;
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>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!</p>
+ *
+ * @see POIFSReader
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class POIBrowser extends JFrame
+{
+
+ /**
+ * <p>The tree's root node must be visible to all methods.</p>
+ */
+ protected MutableTreeNode rootNode;
+
+
+
+ /**
+ * <p>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}.</p>
+ */
+ 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);
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>Describes the most important (whatever that is) features of a
+ * stream containing a {@link PropertySet}.</p>
+ *
+ * @author Rainer Klute (klute@rainer-klute.de)
+ */
+public class PropertySetDescriptor extends DocumentDescriptor
+{
+
+ protected PropertySet propertySet;
+
+ /**
+ * <p>Returns this {@link PropertySetDescriptor}'s {@link
+ * PropertySet}.</p>
+ */
+ public PropertySet getPropertySet()
+ {
+ return propertySet;
+ }
+
+
+
+ /**
+ * <p>Creates a {@link PropertySetDescriptor} by reading a {@link
+ * PropertySet} from a {@link DocumentInputStream}.</p>
+ *
+ * @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);
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>Renders a {@link PropertySetDescriptor} by more or less dumping
+ * the stuff into a {@link JTextArea}.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+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;
+ }
+
+
+
+ /**
+ * <p>Returns a string representation of a list of {@link
+ * Section}s.</p>
+ */
+ 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();
+ }
+
+
+
+ /**
+ * <p>Returns a string representation of a {@link Section}.</p>
+ * @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();
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * <p>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.</p>
+ *
+ * <p>The root tree node should be the root tree node of a {@link
+ * javax.swing.tree.TreeModel}.</p>
+ *
+ * <p>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.</p>
+ *
+ * <p>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.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class TreeReaderListener implements POIFSReaderListener
+{
+
+ /**
+ * <p>The tree's root node. POI filesystems get attached to this
+ * node as children.</p>
+ */
+ protected MutableTreeNode rootNode;
+
+ /**
+ * <p>Maps filenames and POI document paths to their associated
+ * tree nodes.</p>
+ */
+ protected Map pathToNode;
+
+ /**
+ * <p>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.</p>
+ */
+ protected String filename;
+
+
+
+ /**
+ * <p>Creates a {@link TreeReaderListener} which should then be
+ * registered with a
+ * {@link org.apache.poi.poifs.eventfilesystem.POIFSReader}.</p>
+ *
+ * @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.
+ }
+
+
+
+ /** <p>The number of bytes to dump.</p> */
+ private int nrOfBytes = 50;
+
+ public void setNrOfBytes(final int nrOfBytes)
+ {
+ this.nrOfBytes = nrOfBytes;
+ }
+
+ public int getNrOfBytes()
+ {
+ return nrOfBytes;
+ }
+
+
+
+ /**
+ * <p>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.</p>
+ */
+ 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);
+ }
+
+
+
+ /**
+ * <p>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.</p>
+ *
+ * @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;
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.*;
+
+/**
+ * <p>Contains various (well, just one at the moment) static utility
+ * methods.</p>
+ *
+ * @author Rainer Klute <a
+ * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
+ */
+public class Util {
+
+ /**
+ * <p>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 <tt>c.setOpaque(true)</tt>.</p>
+ */
+ public static void invert(JComponent c) {
+ Color invBackground = c.getForeground();
+ Color invForeground = c.getBackground();
+ c.setBackground(invBackground);
+ c.setForeground(invForeground);
+ }
+}
+
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+\r
+\r
+package org.apache.poi.ss.examples;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.net.URL;\r
+\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.hssf.usermodel.HSSFSheet;\r
+import org.apache.poi.ss.usermodel.ClientAnchor;\r
+import org.apache.poi.ss.usermodel.Drawing;\r
+import org.apache.poi.ss.usermodel.Row;\r
+import org.apache.poi.ss.usermodel.Sheet;\r
+import org.apache.poi.ss.usermodel.Workbook;\r
+import org.apache.poi.ss.util.CellReference;\r
+import org.apache.poi.util.IOUtils;\r
+\r
+\r
+/**\r
+ * Demonstrates how to add an image to a worksheet and set that images size\r
+ * to a specific number of millimetres irrespective of the width of the columns\r
+ * or height of the rows. Overridden methods are provided so that the location\r
+ * of the image - the cells row and column coordinates that define the top\r
+ * left hand corners of the image - can be identified either in the familiar\r
+ * Excel manner - A1 for instance - or using POI's methodology of a column and\r
+ * row index where 0, 0 would indicate cell A1.\r
+ *\r
+ * The best way to make use of these techniques is to delay adding the image to\r
+ * the sheet until all other work has been completed. That way, the sizes of\r
+ * all rows and columns will have been adjusted - assuming that step was\r
+ * necessary. Even though the anchors type is set to prevent the image moving\r
+ * or re-sizing, this setting does not have any effect until the sheet is being\r
+ * viewed using the Excel application.\r
+ *\r
+ * The key to the process is the ClientAnchor class. It defines methods that allow\r
+ * us to define the location of an image by specifying the following;\r
+ *\r
+ * * How far - in terms of coordinate positions - the image should be inset\r
+ * from the left hand border of a cell.\r
+ * * How far - in terms of coordinate positions - the image should be inset\r
+ * from the from the top of the cell.\r
+ * * How far - in terms of coordinate positions - the right hand edge of\r
+ * the image should protrude into a cell (measured from the cells left hand\r
+ * edge to the images right hand edge).\r
+ * * How far - in terms of coordinate positions - the bottom edge of the\r
+ * image should protrude into a row (measured from the cells top edge to\r
+ * the images bottom edge).\r
+ * * The index of the column that contains the cell whose top left hand\r
+ * corner should be aligned with the top left hand corner of the image.\r
+ * * The index of the row that contains the cell whose top left hand corner\r
+ * should be aligned with the images top left hand corner.\r
+ * * The index of the column that contains the cell whose top left hand\r
+ * corner should be aligned with the images bottom right hand corner\r
+ * * The index number of the row that contains the cell whose top left\r
+ * hand corner should be aligned with the images bottom right hand corner.\r
+ *\r
+ * It can be used to add an image into cell A1, for example, in the following\r
+ * manner;\r
+ *\r
+ * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();\r
+ *\r
+ * anchor.setDx1(0);\r
+ * anchor.setDy1(0);\r
+ * anchor.setDx2(0);\r
+ * anchor.setDy2(0);\r
+ * anchor.setCol1(0);\r
+ * anchor.setRow1(0);\r
+ * anchor.setCol2(1);\r
+ * anchor.setRow2(1);\r
+ *\r
+ * Taken together, the first four methods define the locations of the top left\r
+ * and bottom right hand corners of the image if you imagine that the image is\r
+ * represented by a simple rectangle. The setDx1() and setDy1() methods locate\r
+ * the top left hand corner of the image while setDx2() and and Dy2() locate the\r
+ * bottom right hand corner of the image. An individual image can be inserted\r
+ * into a single cell or is can lie across many cells and the latter four methods\r
+ * are used to define just where the image should be positioned. They do this by\r
+ * again by identifying where the top left and bottom right hand corners of the\r
+ * image should be located but this time in terms of the indexes of the cells\r
+ * in which those corners should be located. The setCol1() and setRow1() methods\r
+ * together identify the cell that should contain the top left hand corner of\r
+ * the image while setCol2() and setRow2() do the same for the images bottom\r
+ * right hand corner. \r
+ *\r
+ * Knowing that, it is possible to look again at the example above and to see\r
+ * that the top left hand corner of the image will be located in cell A1 (0, 0)\r
+ * and it will be aligned with the very top left hand corner of the cell. Likewise,\r
+ * the bottom right hand corner of the image will be located in cell B2 (1, 1) and\r
+ * it will again be aligned with the top left hand corner of the cell. This has the\r
+ * effect of making the image seem to occupy the whole of cell A1. Interestingly, it\r
+ * also has an effect on the images resizing behaviour because testing has \r
+ * demonstrated that if the image is wholly contained within one cell and is not\r
+ * 'attached' for want of a better word, to a neighbouring cell, then that image\r
+ * will not increase in size in response to the user dragging the column wider\r
+ * or the cell higher.\r
+ *\r
+ * The following example demonstrates a slightly different way to insert an\r
+ * image into cell A1 and to ensure that it occupies the whole of the cell. This\r
+ * is accomplished by specifying the the images bottom right hand corner should be\r
+ * aligned with the bottom right hand corner of the cell. It is also a case\r
+ * where the image will not increase in size if the user increases the size of\r
+ * the enclosing cell - irrespective of the anchors type - but it will reduce in\r
+ * size if the cell is made smaller.\r
+ *\r
+ * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();\r
+ *\r
+ * anchor.setDx1(0);\r
+ * anchor.setDy1(0);\r
+ * anchor.setDx2(1023);\r
+ * anchor.setDy2(255);\r
+ * anchor.setCol1(0);\r
+ * anchor.setRow1(0);\r
+ * anchor.setCol2(0);\r
+ * anchor.setRow2(0);\r
+ *\r
+ * Note that the final four method calls all pass the same value and seem to\r
+ * indicate that the images top left hand corner is aligned with the top left\r
+ * hand corner of cell A1 and that it's bottom right hand corner is also\r
+ * aligned with the top left hand corner of cell A1. Yet, running this code\r
+ * would see the image fully occupying cell A1. That is the result of the\r
+ * values passed to parameters three and four; these I have referred to as\r
+ * determining the images coordinates within the cell. They indicate that the\r
+ * image should occupy - in order - the full width of the column and the full\r
+ * height of the row.\r
+ *\r
+ * The co-ordinate values shown are the maxima; and they are independent of\r
+ * row height/column width and of the font used. Passing 255 will always result\r
+ * in the image occupying the full height of the row and passing 1023 will\r
+ * always result in the image occupying the full width of the column. They help\r
+ * in situations where an image is larger than a column/row and must overlap\r
+ * into the next column/row. Using them does mean, however, that it is often\r
+ * necessary to perform conversions between Excels characters units, points,\r
+ * pixels and millimetres in order to establish how many rows/columns an image\r
+ * should occupy and just what the various insets ought to be.\r
+ *\r
+ * Note that the setDx1(int) and setDy1(int) methods of the ClientAchor class\r
+ * are not made use of in the code that follows. It would be fairly trivial\r
+ * however to extend this example further and provide methods that would centre\r
+ * an image within a cell or allow the user to specify that a plain border a\r
+ * fixed number of millimetres wide should wrap around the image. Those first\r
+ * two parameters would make this sort of functionality perfectly possible.\r
+ *\r
+ * Owing to the various conversions used, the actual size of the image may vary\r
+ * from that required; testing has so far found this to be in the region of\r
+ * plus or minus two millimetres. Most likely by modifying the way the\r
+ * calculations are performed - possibly using double(s) throughout and\r
+ * rounding the values at the correct point - it is likely that these errors\r
+ * could be reduced or removed.\r
+ *\r
+ * A note concerning Excels image resizing behaviour. The ClientAnchor\r
+ * class contains a method called setAnchorType(int) which can be used to\r
+ * determine how Excel will resize an image in response to the user increasing\r
+ * or decreasing the dimensions of the cell containing the image. There are \r
+ * three values that can be passed to this method; 0 = To move and size the \r
+ * image with the cell, 2 = To move but don't size the image with the cell,\r
+ * 3 = To prevent the image from moving or being resized along with the cell. If\r
+ * an image is inserted using this class and placed into a single cell then if\r
+ * the setAnchorType(int) method is called and a value of either 0 or 2 passed\r
+ * to it, the resultant resizing behaviour may be a surprise. The image will not\r
+ * grow in size of the column is made wider or the row higher but it will shrink\r
+ * if the columns width or rows height are reduced.\r
+ *\r
+ * @author Mark Beardsley [msb at apache.org] and Mark Southern [southern at scripps.edu]\r
+ * @version 1.00 5th August 2009.\r
+ * 2.00 26th February 2010.\r
+ * Ported to make use of the the SS usermodel classes.\r
+ * Ability to reuse the Drawing Patriarch so that multiple images\r
+ * can be inserted without unintentionally erasing earlier images.\r
+ * Check on image type added; i.e. jpg, jpeg or png.\r
+ * The String used to contain the files name is now converted\r
+ * into a URL.\r
+ * 2.10 17th May 2012\r
+ * Corrected gross error that occurred when using the code with\r
+ * XSSF or SXSSF workbooks. In short, the code did not correctly\r
+ * calculate the size of the image(s) owing to the use of EMUs\r
+ * within the OOXML file format. That problem has largely been\r
+ * corrected although it should be mentioned that images are not\r
+ * sized with the same level of accuracy. Discrepancies of up to\r
+ * 2mm have been noted in testing. Further investigation will\r
+ * continue to rectify this issue.\r
+ */\r
+public class AddDimensionedImage {\r
+\r
+ // Four constants that determine how - and indeed whether - the rows\r
+ // and columns an image may overlie should be expanded to accomodate that\r
+ // image.\r
+ // Passing EXPAND_ROW will result in the height of a row being increased\r
+ // to accomodate the image if it is not already larger. The image will\r
+ // be layed across one or more columns.\r
+ // Passing EXPAND_COLUMN will result in the width of the column being\r
+ // increased to accomodate the image if it is not already larger. The image\r
+ // will be layed across one or many rows.\r
+ // Passing EXPAND_ROW_AND_COLUMN will result in the height of the row\r
+ // bing increased along with the width of the column to accomdate the\r
+ // image if either is not already larger.\r
+ // Passing OVERLAY_ROW_AND_COLUMN will result in the image being layed\r
+ // over one or more rows and columns. No row or column will be resized,\r
+ // instead, code will determine how many rows and columns the image should\r
+ // overlie.\r
+ public static final int EXPAND_ROW = 1;\r
+ public static final int EXPAND_COLUMN = 2;\r
+ public static final int EXPAND_ROW_AND_COLUMN = 3;\r
+ public static final int OVERLAY_ROW_AND_COLUMN = 7;\r
+ \r
+ // Modified to support EMU - English Metric Units - used within the OOXML\r
+ // workbooks, this multoplier is used to convert between measurements in\r
+ // millimetres and in EMUs\r
+ private static final int EMU_PER_MM = 36000;\r
+ \r
+ /**\r
+ * Add an image to a worksheet.\r
+ *\r
+ * @param cellNumber A String that contains the location of the cell whose\r
+ * top left hand corner should be aligned with the top\r
+ * left hand corner of the image; for example "A1", "A2"\r
+ * etc. This is to support the familiar Excel syntax.\r
+ * Whilst images are are not actually inserted into cells\r
+ * this provides a convenient method of indicating where\r
+ * the image should be positioned on the sheet.\r
+ * @param sheet A reference to the sheet that contains the cell referenced\r
+ * above.\r
+ * @param drawing An instance of the DrawingPatriarch class. This is now\r
+ * passed into the method where it was, previously, recovered\r
+ * from the sheet in order to allow multiple pictures be\r
+ * inserted. If the patriarch was not 'cached in this manner\r
+ * each time it was created any previously positioned images\r
+ * would be simply over-written.\r
+ * @param imageFile An instance of the URL class that encapsulates the name\r
+ * of and path to the image that is to be 'inserted into'\r
+ * the sheet.\r
+ * @param reqImageWidthMM A primitive double that contains the required\r
+ * width of the image in millimetres.\r
+ * @param reqImageHeightMM A primitive double that contains the required\r
+ * height of the image in millimetres.\r
+ * @param resizeBehaviour A primitive int whose value will determine how\r
+ * the code should react if the image is larger than\r
+ * the cell referenced by the cellNumber parameter.\r
+ * Four constants are provided to determine what\r
+ * should happen;\r
+ * AddDimensionedImage.EXPAND_ROW\r
+ * AddDimensionedImage.EXPAND_COLUMN\r
+ * AddDimensionedImage.EXPAND_ROW_AND_COLUMN\r
+ * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN\r
+ * @throws java.io.FileNotFoundException If the file containing the image\r
+ * cannot be located.\r
+ * @throws java.io.IOException If a problem occurs whilst reading the file\r
+ * of image data.\r
+ * @throws java.lang.IllegalArgumentException If an invalid value is passed\r
+ * to the resizeBehaviour\r
+ * parameter.\r
+ */\r
+ public void addImageToSheet(String cellNumber, Sheet sheet, Drawing drawing,\r
+ URL imageFile, double reqImageWidthMM, double reqImageHeightMM,\r
+ int resizeBehaviour) throws IOException, IllegalArgumentException {\r
+ // Convert the String into column and row indices then chain the\r
+ // call to the overridden addImageToSheet() method.\r
+ CellReference cellRef = new CellReference(cellNumber);\r
+ this.addImageToSheet(cellRef.getCol(), cellRef.getRow(), sheet, drawing,\r
+ imageFile, reqImageWidthMM, reqImageHeightMM,resizeBehaviour);\r
+ }\r
+\r
+ /**\r
+ * Add an image to a worksheet.\r
+ *\r
+ * @param colNumber A primitive int that contains the index number of a\r
+ * column on the worksheet; POI column indices are zero\r
+ * based. Together with the rowNumber parameter's value,\r
+ * this parameter identifies a cell on the worksheet. The\r
+ * images top left hand corner will be aligned with the\r
+ * top left hand corner of this cell.\r
+ * @param rowNumber A primitive int that contains the index number of a row\r
+ * on the worksheet; POI row indices are zero based.\r
+ * Together with the rowNumber parameter's value, this\r
+ * parameter identifies a cell on the worksheet. The\r
+ * images top left hand corner will be aligned with the\r
+ * top left hand corner of this cell.\r
+ * @param sheet A reference to the sheet that contains the cell identified\r
+ * by the two parameters above.\r
+ * @param drawing An instance of the DrawingPatriarch class. This is now\r
+ * passed into the method where it was, previously, recovered\r
+ * from the sheet in order to allow multiple pictures be\r
+ * inserted. If the patriarch was not 'cached in this manner\r
+ * each time it was created any previously positioned images\r
+ * would be simply over-written.\r
+ * @param imageFile An instance of the URL class that encapsulates the name\r
+ * of and path to the image that is to be 'inserted into'\r
+ * the sheet.\r
+ * @param reqImageWidthMM A primitive double that contains the required\r
+ * width of the image in millimetres.\r
+ * @param reqImageHeightMM A primitive double that contains the required\r
+ * height of the image in millimetres.\r
+ * @param resizeBehaviour A primitive int whose value will determine how\r
+ * the code should react if the image is larger than\r
+ * the cell referenced by the colNumber and\r
+ * rowNumber parameters. Four constants are provided\r
+ * to determine what should happen;\r
+ * AddDimensionedImage.EXPAND_ROW\r
+ * AddDimensionedImage.EXPAND_COLUMN\r
+ * AddDimensionedImage.EXPAND_ROW_AND_COLUMN\r
+ * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN\r
+ * @throws java.io.FileNotFoundException If the file containing the image\r
+ * cannot be located.\r
+ * @throws java.io.IOException If a problem occurs whilst reading the file\r
+ * of image data.\r
+ * @throws java.lang.IllegalArgumentException If an invalid value is passed\r
+ * to the resizeBehaviour\r
+ * parameter or if the extension\r
+ * of the image file indicates that\r
+ * it is of a type that cannot\r
+ * currently be added to the worksheet.\r
+ */\r
+ public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing drawing,\r
+ URL imageFile, double reqImageWidthMM, double reqImageHeightMM,\r
+ int resizeBehaviour) throws IOException,\r
+ IllegalArgumentException {\r
+ ClientAnchor anchor = null;\r
+ ClientAnchorDetail rowClientAnchorDetail = null;\r
+ ClientAnchorDetail colClientAnchorDetail = null;\r
+ int imageType = 0;\r
+\r
+ // Validate the resizeBehaviour parameter.\r
+ if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&\r
+ (resizeBehaviour != AddDimensionedImage.EXPAND_ROW) &&\r
+ (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN) &&\r
+ (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) {\r
+ throw new IllegalArgumentException("Invalid value passed to the " +\r
+ "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()");\r
+ }\r
+\r
+ // Call methods to calculate how the image and sheet should be\r
+ // manipulated to accomodate the image; columns and then rows.\r
+ colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber,\r
+ reqImageWidthMM, resizeBehaviour);\r
+ rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber,\r
+ reqImageHeightMM, resizeBehaviour);\r
+\r
+ // Having determined if and how to resize the rows, columns and/or the\r
+ // image, create the ClientAnchor object to position the image on\r
+ // the worksheet. Note how the two ClientAnchorDetail records are\r
+ // interrogated to recover the row/column co-ordinates and any insets.\r
+ // The first two parameters are not used currently but could be if the\r
+ // need arose to extend the functionality of this code by adding the\r
+ // ability to specify that a clear 'border' be placed around the image.\r
+ anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();\r
+\r
+ anchor.setDx1(0);\r
+ anchor.setDy1(0);\r
+ anchor.setDx2(colClientAnchorDetail.getInset());\r
+ anchor.setDy2(rowClientAnchorDetail.getInset());\r
+ anchor.setCol1(colClientAnchorDetail.getFromIndex());\r
+ anchor.setRow1(rowClientAnchorDetail.getFromIndex());\r
+ anchor.setCol2(colClientAnchorDetail.getToIndex());\r
+ anchor.setRow2(rowClientAnchorDetail.getToIndex());\r
+\r
+ // For now, set the anchor type to do not move or resize the\r
+ // image as the size of the row/column is adjusted. This could easilly\r
+ // become another parameter passed to the method. Please read the note\r
+ // above regarding the behaviour of image resizing.\r
+ anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE);\r
+\r
+ // Now, add the picture to the workbook. Note that unlike the similar\r
+ // method in the HSSF Examples section, the image type is checked. First,\r
+ // the image files location is identified by interrogating the URL passed\r
+ // to the method, the images type is identified before it is added to the\r
+ // sheet.\r
+ String sURL = imageFile.toString().toLowerCase();\r
+ if( sURL.endsWith(".png") ) {\r
+ imageType = Workbook.PICTURE_TYPE_PNG;\r
+ }\r
+ else if( sURL.endsWith("jpg") || sURL.endsWith(".jpeg") ) {\r
+ imageType = Workbook.PICTURE_TYPE_JPEG;\r
+ }\r
+ else {\r
+ throw new IllegalArgumentException("Invalid Image file : " +\r
+ sURL);\r
+ }\r
+ int index = sheet.getWorkbook().addPicture(\r
+ IOUtils.toByteArray(imageFile.openStream()), imageType);\r
+ drawing.createPicture(anchor, index);\r
+ }\r
+\r
+ /**\r
+ * Determines whether the sheets columns should be re-sized to accomodate\r
+ * the image, adjusts the columns width if necessary and creates then\r
+ * returns a ClientAnchorDetail object that facilitates construction of\r
+ * an ClientAnchor that will fix the image on the sheet and establish\r
+ * it's size.\r
+ *\r
+ * @param sheet A reference to the sheet that will 'contain' the image.\r
+ * @param colNumber A primtive int that contains the index number of a\r
+ * column on the sheet.\r
+ * @param reqImageWidthMM A primitive double that contains the required\r
+ * width of the image in millimetres\r
+ * @param resizeBehaviour A primitive int whose value will indicate how the\r
+ * width of the column should be adjusted if the\r
+ * required width of the image is greater than the\r
+ * width of the column.\r
+ * @return An instance of the ClientAnchorDetail class that will contain\r
+ * the index number of the column containing the cell whose top\r
+ * left hand corner also defines the top left hand corner of the\r
+ * image, the index number column containing the cell whose top\r
+ * left hand corner also defines the bottom right hand corner of\r
+ * the image and an inset that determines how far the right hand\r
+ * edge of the image can protrude into the next column - expressed\r
+ * as a specific number of coordinate positions.\r
+ */\r
+ private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber,\r
+ double reqImageWidthMM, int resizeBehaviour) {\r
+\r
+ double colWidthMM = 0.0D;\r
+ double colCoordinatesPerMM = 0.0D;\r
+ int pictureWidthCoordinates = 0;\r
+ ClientAnchorDetail colClientAnchorDetail = null;\r
+\r
+ // Get the colum's width in millimetres\r
+ colWidthMM = ConvertImageUnits.widthUnits2Millimetres(\r
+ (short)sheet.getColumnWidth(colNumber));\r
+\r
+ // Check that the column's width will accomodate the image at the\r
+ // required dimension. If the width of the column is LESS than the\r
+ // required width of the image, decide how the application should\r
+ // respond - resize the column or overlay the image across one or more\r
+ // columns.\r
+ if(colWidthMM < reqImageWidthMM) {\r
+\r
+ // Should the column's width simply be expanded?\r
+ if((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN) ||\r
+ (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) {\r
+ // Set the width of the column by converting the required image\r
+ // width from millimetres into Excel's column width units.\r
+ sheet.setColumnWidth(colNumber,\r
+ ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM));\r
+ // To make the image occupy the full width of the column, convert\r
+ // the required width of the image into co-ordinates. This value\r
+ // will become the inset for the ClientAnchorDetail class that\r
+ // is then instantiated.\r
+ if(sheet instanceof HSSFSheet) {\r
+ colWidthMM = reqImageWidthMM;\r
+ colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS /\r
+ colWidthMM;\r
+ pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM);\r
+\r
+ }\r
+ else {\r
+ pictureWidthCoordinates = (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM;\r
+ }\r
+ colClientAnchorDetail = new ClientAnchorDetail(colNumber,\r
+ colNumber, pictureWidthCoordinates);\r
+ }\r
+ // If the user has chosen to overlay both rows and columns or just\r
+ // to expand ONLY the size of the rows, then calculate how to lay\r
+ // the image out across one or more columns.\r
+ else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) ||\r
+ (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) {\r
+ colClientAnchorDetail = this.calculateColumnLocation(sheet,\r
+ colNumber, reqImageWidthMM);\r
+ }\r
+ }\r
+ // If the column is wider than the image.\r
+ else {\r
+ if(sheet instanceof HSSFSheet) {\r
+ // Mow many co-ordinate positions are there per millimetre?\r
+ colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS /\r
+ colWidthMM;\r
+ // Given the width of the image, what should be it's co-ordinate?\r
+ pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM);\r
+ }\r
+ else {\r
+ pictureWidthCoordinates = (int)reqImageWidthMM *\r
+ AddDimensionedImage.EMU_PER_MM;\r
+ }\r
+ colClientAnchorDetail = new ClientAnchorDetail(colNumber,\r
+ colNumber, pictureWidthCoordinates);\r
+ }\r
+ return(colClientAnchorDetail);\r
+ }\r
+\r
+ /**\r
+ * Determines whether the sheets row should be re-sized to accomodate\r
+ * the image, adjusts the rows height if necessary and creates then\r
+ * returns a ClientAnchorDetail object that facilitates construction of\r
+ * a ClientAnchor that will fix the image on the sheet and establish\r
+ * it's size.\r
+ *\r
+ * @param sheet A reference to the sheet that will 'contain' the image.\r
+ * @param rowNumber A primitive int that contains the index number of a\r
+ * row on the sheet.\r
+ * @param reqImageHeightMM A primitive double that contains the required\r
+ * height of the image in millimetres\r
+ * @param resizeBehaviour A primitive int whose value will indicate how the\r
+ * height of the row should be adjusted if the\r
+ * required height of the image is greater than the\r
+ * height of the row.\r
+ * @return An instance of the ClientAnchorDetail class that will contain\r
+ * the index number of the row containing the cell whose top\r
+ * left hand corner also defines the top left hand corner of the\r
+ * image, the index number of the row containing the cell whose\r
+ * top left hand corner also defines the bottom right hand\r
+ * corner of the image and an inset that determines how far the\r
+ * bottom edge of the image can protrude into the next (lower)\r
+ * row - expressed as a specific number of coordinate positions.\r
+ */\r
+ private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber,\r
+ double reqImageHeightMM, int resizeBehaviour) {\r
+ Row row = null;\r
+ double rowHeightMM = 0.0D;\r
+ double rowCoordinatesPerMM = 0.0D;\r
+ int pictureHeightCoordinates = 0;\r
+ ClientAnchorDetail rowClientAnchorDetail = null;\r
+\r
+ // Get the row and it's height\r
+ row = sheet.getRow(rowNumber);\r
+ if(row == null) {\r
+ // Create row if it does not exist.\r
+ row = sheet.createRow(rowNumber);\r
+ }\r
+\r
+ // Get the row's height in millimetres\r
+ rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE;\r
+\r
+ // Check that the row's height will accomodate the image at the required\r
+ // dimensions. If the height of the row is LESS than the required height\r
+ // of the image, decide how the application should respond - resize the\r
+ // row or overlay the image across a series of rows.\r
+ if(rowHeightMM < reqImageHeightMM) {\r
+ if((resizeBehaviour == AddDimensionedImage.EXPAND_ROW) ||\r
+ (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) {\r
+ row.setHeightInPoints((float)(reqImageHeightMM *\r
+ ConvertImageUnits.POINTS_PER_MILLIMETRE));\r
+ if(sheet instanceof HSSFSheet) { \r
+ rowHeightMM = reqImageHeightMM;\r
+ rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS /\r
+ rowHeightMM;\r
+ pictureHeightCoordinates = (int)(reqImageHeightMM *\r
+ rowCoordinatesPerMM);\r
+ }\r
+ else {\r
+ pictureHeightCoordinates = (int)(reqImageHeightMM *\r
+ AddDimensionedImage.EMU_PER_MM);\r
+ }\r
+ rowClientAnchorDetail = new ClientAnchorDetail(rowNumber,\r
+ rowNumber, pictureHeightCoordinates);\r
+ }\r
+ // If the user has chosen to overlay both rows and columns or just\r
+ // to expand ONLY the size of the columns, then calculate how to lay\r
+ // the image out ver one or more rows.\r
+ else if((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) ||\r
+ (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) {\r
+ rowClientAnchorDetail = this.calculateRowLocation(sheet,\r
+ rowNumber, reqImageHeightMM);\r
+ }\r
+ }\r
+ // Else, if the image is smaller than the space available\r
+ else {\r
+ if(sheet instanceof HSSFSheet) {\r
+ rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS /\r
+ rowHeightMM;\r
+ pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM);\r
+ }\r
+ else {\r
+ pictureHeightCoordinates = (int)(reqImageHeightMM *\r
+ AddDimensionedImage.EMU_PER_MM);\r
+ }\r
+ rowClientAnchorDetail = new ClientAnchorDetail(rowNumber,\r
+ rowNumber, pictureHeightCoordinates);\r
+ }\r
+ return(rowClientAnchorDetail);\r
+ }\r
+\r
+ /**\r
+ * If the image is to overlie more than one column, calculations need to be\r
+ * performed to determine how many columns and whether the image will\r
+ * overlie just a part of one column in order to be presented at the\r
+ * required size.\r
+ *\r
+ * @param sheet The sheet that will 'contain' the image.\r
+ * @param startingColumn A primitive int whose value is the index of the\r
+ * column that contains the cell whose top left hand\r
+ * corner should be aligned with the top left hand\r
+ * corner of the image.\r
+ * @param reqImageWidthMM A primitive double whose value will indicate the\r
+ * required width of the image in millimetres.\r
+ * @return An instance of the ClientAnchorDetail class that will contain\r
+ * the index number of the column containing the cell whose top\r
+ * left hand corner also defines the top left hand corner of the\r
+ * image, the index number column containing the cell whose top\r
+ * left hand corner also defines the bottom right hand corner of\r
+ * the image and an inset that determines how far the right hand\r
+ * edge of the image can protrude into the next column - expressed\r
+ * as a specific number of coordinate positions.\r
+ */\r
+ private ClientAnchorDetail calculateColumnLocation(Sheet sheet,\r
+ int startingColumn,\r
+ double reqImageWidthMM) {\r
+ ClientAnchorDetail anchorDetail = null;\r
+ double totalWidthMM = 0.0D;\r
+ double colWidthMM = 0.0D;\r
+ double overlapMM = 0.0D;\r
+ double coordinatePositionsPerMM = 0.0D;\r
+ int toColumn = startingColumn;\r
+ int inset = 0;\r
+\r
+ // Calculate how many columns the image will have to\r
+ // span in order to be presented at the required size.\r
+ while(totalWidthMM < reqImageWidthMM) {\r
+ colWidthMM = ConvertImageUnits.widthUnits2Millimetres(\r
+ (short)(sheet.getColumnWidth(toColumn)));\r
+ // Note use of the cell border width constant. Testing with an image\r
+ // declared to fit exactly into one column demonstrated that it's\r
+ // width was greater than the width of the column the POI returned.\r
+ // Further, this difference was a constant value that I am assuming\r
+ // related to the cell's borders. Either way, that difference needs\r
+ // to be allowed for in this calculation.\r
+ totalWidthMM += (colWidthMM + ConvertImageUnits.CELL_BORDER_WIDTH_MILLIMETRES);\r
+ toColumn++;\r
+ }\r
+ // De-crement by one the last column value.\r
+ toColumn--;\r
+ // Highly unlikely that this will be true but, if the width of a series\r
+ // of columns is exactly equal to the required width of the image, then\r
+ // simply build a ClientAnchorDetail object with an inset equal to the\r
+ // total number of co-ordinate positions available in a column, a\r
+ // from column co-ordinate (top left hand corner) equal to the value\r
+ // of the startingColumn parameter and a to column co-ordinate equal\r
+ // to the toColumn variable.\r
+ //\r
+ // Convert both values to ints to perform the test.\r
+ if((int)totalWidthMM == (int)reqImageWidthMM) {\r
+ // A problem could occur if the image is sized to fit into one or\r
+ // more columns. If that occurs, the value in the toColumn variable\r
+ // will be in error. To overcome this, there are two options, to\r
+ // ibcrement the toColumn variable's value by one or to pass the\r
+ // total number of co-ordinate positions to the third paramater\r
+ // of the ClientAnchorDetail constructor. For no sepcific reason,\r
+ // the latter option is used below.\r
+ if(sheet instanceof HSSFSheet) {\r
+ anchorDetail = new ClientAnchorDetail(startingColumn,\r
+ toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS);\r
+ }\r
+ else {\r
+ anchorDetail = new ClientAnchorDetail(startingColumn,\r
+ toColumn, (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM);\r
+ }\r
+ }\r
+ // In this case, the image will overlap part of another column and it is\r
+ // necessary to calculate just how much - this will become the inset\r
+ // for the ClientAnchorDetail object.\r
+ else {\r
+ // Firstly, claculate how much of the image should overlap into\r
+ // the next column.\r
+ overlapMM = reqImageWidthMM - (totalWidthMM - colWidthMM);\r
+\r
+ // When the required size is very close indded to the column size,\r
+ // the calcaulation above can produce a negative value. To prevent\r
+ // problems occuring in later caculations, this is simply removed\r
+ // be setting the overlapMM value to zero.\r
+ if(overlapMM < 0) {\r
+ overlapMM = 0.0D;\r
+ }\r
+\r
+ if(sheet instanceof HSSFSheet) {\r
+ // Next, from the columns width, calculate how many co-ordinate\r
+ // positons there are per millimetre\r
+ coordinatePositionsPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS /\r
+ colWidthMM;\r
+ // From this figure, determine how many co-ordinat positions to\r
+ // inset the left hand or bottom edge of the image.\r
+ inset = (int)(coordinatePositionsPerMM * overlapMM);\r
+ }\r
+ else {\r
+ inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM;\r
+ }\r
+\r
+ // Now create the ClientAnchorDetail object, setting the from and to\r
+ // columns and the inset.\r
+ anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, inset);\r
+ }\r
+ return(anchorDetail);\r
+ }\r
+\r
+ /**\r
+ * If the image is to overlie more than one rows, calculations need to be\r
+ * performed to determine how many rows and whether the image will\r
+ * overlie just a part of one row in order to be presented at the\r
+ * required size.\r
+ *\r
+ * @param sheet The sheet that will 'contain' the image.\r
+ * @param startingRow A primitive int whose value is the index of the row\r
+ * that contains the cell whose top left hand corner\r
+ * should be aligned with the top left hand corner of\r
+ * the image.\r
+ * @param reqImageHeightMM A primitive double whose value will indicate the\r
+ * required height of the image in millimetres.\r
+ * @return An instance of the ClientAnchorDetail class that will contain\r
+ * the index number of the row containing the cell whose top\r
+ * left hand corner also defines the top left hand corner of the\r
+ * image, the index number of the row containing the cell whose top\r
+ * left hand corner also defines the bottom right hand corner of\r
+ * the image and an inset that determines how far the bottom edge\r
+ * can protrude into the next (lower) row - expressed as a specific\r
+ * number of co-ordinate positions.\r
+ */\r
+ private ClientAnchorDetail calculateRowLocation(Sheet sheet,\r
+ int startingRow, double reqImageHeightMM) {\r
+ ClientAnchorDetail clientAnchorDetail = null;\r
+ Row row = null;\r
+ double rowHeightMM = 0.0D;\r
+ double totalRowHeightMM = 0.0D;\r
+ double overlapMM = 0.0D;\r
+ double rowCoordinatesPerMM = 0.0D;\r
+ int toRow = startingRow;\r
+ int inset = 0;\r
+\r
+ // Step through the rows in the sheet and accumulate a total of their\r
+ // heights.\r
+ while(totalRowHeightMM < reqImageHeightMM) {\r
+ row = sheet.getRow(toRow);\r
+ // Note, if the row does not already exist on the sheet then create\r
+ // it here.\r
+ if(row == null) {\r
+ row = sheet.createRow(toRow);\r
+ }\r
+ // Get the row's height in millimetres and add to the running total.\r
+ rowHeightMM = row.getHeightInPoints() /\r
+ ConvertImageUnits.POINTS_PER_MILLIMETRE;\r
+ totalRowHeightMM += rowHeightMM;\r
+ toRow++;\r
+ }\r
+ // Owing to the way the loop above works, the rowNumber will have been\r
+ // incremented one row too far. Undo that here.\r
+ toRow--;\r
+ // Check to see whether the image should occupy an exact number of\r
+ // rows. If so, build the ClientAnchorDetail record to point\r
+ // to those rows and with an inset of the total number of co-ordinate\r
+ // position in the row.\r
+ //\r
+ // To overcome problems that can occur with comparing double values for\r
+ // equality, cast both to int(s) to truncate the value; VERY crude and\r
+ // I do not really like it!!\r
+ if((int)totalRowHeightMM == (int)reqImageHeightMM) {\r
+ if(sheet instanceof HSSFSheet) {\r
+ clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow,\r
+ ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS);\r
+ }\r
+ else {\r
+ clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow,\r
+ (int)reqImageHeightMM * AddDimensionedImage.EMU_PER_MM);\r
+ }\r
+ }\r
+ else {\r
+ // Calculate how far the image will project into the next row. Note\r
+ // that the height of the last row assessed is subtracted from the\r
+ // total height of all rows assessed so far.\r
+ overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM);\r
+\r
+ // To prevent an exception being thrown when the required width of\r
+ // the image is very close indeed to the column size.\r
+ if(overlapMM < 0) {\r
+ overlapMM = 0.0D;\r
+ }\r
+\r
+ if(sheet instanceof HSSFSheet) {\r
+ rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS /\r
+ rowHeightMM;\r
+ inset = (int)(overlapMM * rowCoordinatesPerMM);\r
+ }\r
+ else {\r
+ inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM;\r
+ }\r
+ clientAnchorDetail = new ClientAnchorDetail(startingRow,\r
+ toRow, inset);\r
+ }\r
+ return(clientAnchorDetail);\r
+ }\r
+\r
+ /**\r
+ * The main entry point to the program. It contains code that demonstrates\r
+ * one way to use the program.\r
+ *\r
+ * Note, the code is not restricted to use on new workbooks only. If an\r
+ * image is to be inserted into an existing workbook. just open that\r
+ * workbook, gat a reference to a sheet and pass that;\r
+ *\r
+ * AddDimensionedImage addImage = new AddDimensionedImage();\r
+ *\r
+ * File file = new File("....... Existing Workbook .......");\r
+ * FileInputStream fis = new FileInputStream(file);\r
+ * Workbook workbook = new HSSFWorkbook(fis);\r
+ * HSSFSheet sheet = workbook.getSheetAt(0);\r
+ * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20,\r
+ * AddDimensionedImage.EXPAND.ROW);\r
+ *\r
+ * @param args the command line arguments\r
+ */\r
+ public static void main(String[] args) {\r
+ String imageFile = null;\r
+ String outputFile = null;\r
+ FileOutputStream fos = null;\r
+ Workbook workbook = null;\r
+ Sheet sheet = null;\r
+ try {\r
+ if(args.length < 2){\r
+ System.err.println("Usage: AddDimensionedImage imageFile outputFile");\r
+ return;\r
+ }\r
+ workbook = new HSSFWorkbook(); // OR XSSFWorkbook\r
+ sheet = workbook.createSheet("Picture Test");\r
+ imageFile = args[0];\r
+ outputFile = args[1];\r
+ new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),\r
+ new File(imageFile).toURI().toURL(), 100, 40,\r
+ AddDimensionedImage.EXPAND_ROW_AND_COLUMN);\r
+ fos = new FileOutputStream(outputFile);\r
+ workbook.write(fos);\r
+ }\r
+ catch(FileNotFoundException fnfEx) {\r
+ System.out.println("Caught an: " + fnfEx.getClass().getName());\r
+ System.out.println("Message: " + fnfEx.getMessage());\r
+ System.out.println("Stacktrace follows...........");\r
+ fnfEx.printStackTrace(System.out);\r
+ }\r
+ catch(IOException ioEx) {\r
+ System.out.println("Caught an: " + ioEx.getClass().getName());\r
+ System.out.println("Message: " + ioEx.getMessage());\r
+ System.out.println("Stacktrace follows...........");\r
+ ioEx.printStackTrace(System.out);\r
+ }\r
+ finally {\r
+ if(fos != null) {\r
+ try {\r
+ fos.close();\r
+ fos = null;\r
+ }\r
+ catch(IOException ioEx) {\r
+ // I G N O R E\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * The HSSFClientAnchor class accepts eight arguments. In order, these are;\r
+ *\r
+ * * How far the left hand edge of the image is inset from the left hand\r
+ * edge of the cell\r
+ * * How far the top edge of the image is inset from the top of the cell\r
+ * * How far the right hand edge of the image is inset from the left\r
+ * hand edge of the cell\r
+ * * How far the bottom edge of the image is inset from the top of the\r
+ * cell.\r
+ * * Together, arguments five and six determine the column and row\r
+ * coordinates of the cell whose top left hand corner will be aligned\r
+ * with the images top left hand corner.\r
+ * * Together, arguments seven and eight determine the column and row\r
+ * coordinates of the cell whose top left hand corner will be aligned\r
+ * with the images bottom right hand corner.\r
+ *\r
+ * An instance of the ClientAnchorDetail class provides three of the eight\r
+ * parameters, one of the coordinates for the images top left hand corner,\r
+ * one of the coordinates for the images bottom right hand corner and\r
+ * either how far the image should be inset from the top or the left hand\r
+ * edge of the cell.\r
+ *\r
+ * @author Mark Beardsley [msb at apache.org]\r
+ * @version 1.00 5th August 2009.\r
+ */\r
+ public class ClientAnchorDetail {\r
+\r
+ public int fromIndex = 0;\r
+ public int toIndex = 0;\r
+ public int inset = 0;\r
+\r
+ /**\r
+ * Create a new instance of the ClientAnchorDetail class using the\r
+ * following parameters.\r
+ *\r
+ * @param fromIndex A primitive int that contains one of the\r
+ * coordinates (row or column index) for the top left\r
+ * hand corner of the image.\r
+ * @param toIndex A primitive int that contains one of the\r
+ * coordinates (row or column index) for the bottom\r
+ * right hand corner of the image.\r
+ * @param inset A primitive int that contains a value which indicates\r
+ * how far the image should be inset from the top or the\r
+ * left hand edge of a cell.\r
+ */\r
+ public ClientAnchorDetail(int fromIndex, int toIndex, int inset) {\r
+ this.fromIndex = fromIndex;\r
+ this.toIndex = toIndex;\r
+ this.inset = inset;\r
+ }\r
+\r
+ /**\r
+ * Get one of the number of the column or row that contains the cell\r
+ * whose top left hand corner will be aligned with the top left hand\r
+ * corner of the image.\r
+ *\r
+ * @return The value - row or column index - for one of the coordinates\r
+ * of the top left hand corner of the image.\r
+ */\r
+ public int getFromIndex() {\r
+ return(this.fromIndex);\r
+ }\r
+\r
+ /**\r
+ * Get one of the number of the column or row that contains the cell\r
+ * whose top left hand corner will be aligned with the bottom right hand\r
+ * corner of the image.\r
+ *\r
+ * @return The value - row or column index - for one of the coordinates\r
+ * of the bottom right hand corner of the image.\r
+ */\r
+ public int getToIndex() {\r
+ return(this.toIndex);\r
+ }\r
+\r
+ /**\r
+ * Get the images offset from the edge of a cell.\r
+ *\r
+ * @return How far either the right hand or bottom edge of the image is\r
+ * inset from the left hand or top edge of a cell.\r
+ */\r
+ public int getInset() {\r
+ return(this.inset);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Utility methods used to convert Excels character based column and row\r
+ * size measurements into pixels and/or millimetres. The class also contains\r
+ * various constants that are required in other calculations.\r
+ *\r
+ * @author xio[darjino@hotmail.com]\r
+ * @version 1.01 30th July 2009.\r
+ * Added by Mark Beardsley [msb at apache.org].\r
+ * Additional constants.\r
+ * widthUnits2Millimetres() and millimetres2Units() methods.\r
+ */\r
+ public static class ConvertImageUnits {\r
+\r
+ // Each cell conatins a fixed number of co-ordinate points; this number\r
+ // does not vary with row height or column width or with font. These two\r
+ // constants are defined below.\r
+ public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB\r
+ public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB\r
+ // The resoultion of an image can be expressed as a specific number\r
+ // of pixels per inch. Displays and printers differ but 96 pixels per\r
+ // inch is an acceptable standard to beging with.\r
+ public static final int PIXELS_PER_INCH = 96; // MB\r
+ // Cnstants that defines how many pixels and points there are in a\r
+ // millimetre. These values are required for the conversion algorithm.\r
+ public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB\r
+ public static final double POINTS_PER_MILLIMETRE = 2.83; // MB\r
+ // The column width returned by HSSF and the width of a picture when\r
+ // positioned to exactly cover one cell are different by almost exactly\r
+ // 2mm - give or take rounding errors. This constant allows that\r
+ // additional amount to be accounted for when calculating how many\r
+ // celles the image ought to overlie.\r
+ public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB\r
+ public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;\r
+ public static final int UNIT_OFFSET_LENGTH = 7;\r
+ public static final int[] UNIT_OFFSET_MAP = new int[]\r
+ { 0, 36, 73, 109, 146, 182, 219 };\r
+\r
+ /**\r
+ * pixel units to excel width units(units of 1/256th of a character width)\r
+ * @param pxs\r
+ * @return\r
+ */\r
+ public static short pixel2WidthUnits(int pxs) {\r
+ short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR *\r
+ (pxs / UNIT_OFFSET_LENGTH));\r
+ widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];\r
+ return widthUnits;\r
+ }\r
+\r
+ /**\r
+ * excel width units(units of 1/256th of a character width) to pixel\r
+ * units.\r
+ *\r
+ * @param widthUnits\r
+ * @return\r
+ */\r
+ public static int widthUnits2Pixel(short widthUnits) {\r
+ int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR)\r
+ * UNIT_OFFSET_LENGTH;\r
+ int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;\r
+ pixels += Math.round(offsetWidthUnits /\r
+ ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));\r
+ return pixels;\r
+ }\r
+\r
+ /**\r
+ * Convert Excels width units into millimetres.\r
+ *\r
+ * @param widthUnits The width of the column or the height of the\r
+ * row in Excels units.\r
+ * @return A primitive double that contains the columns width or rows\r
+ * height in millimetres.\r
+ */\r
+ public static double widthUnits2Millimetres(short widthUnits) {\r
+ return(ConvertImageUnits.widthUnits2Pixel(widthUnits) /\r
+ ConvertImageUnits.PIXELS_PER_MILLIMETRES);\r
+ }\r
+\r
+ /**\r
+ * Convert into millimetres Excels width units..\r
+ *\r
+ * @param millimetres A primitive double that contains the columns\r
+ * width or rows height in millimetres.\r
+ * @return A primitive int that contains the columns width or rows\r
+ * height in Excels units.\r
+ */\r
+ public static int millimetres2WidthUnits(double millimetres) {\r
+ return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres *\r
+ ConvertImageUnits.PIXELS_PER_MILLIMETRES)));\r
+ }\r
+ \r
+ public static int pointsToPixels(double points) {\r
+ return (int) Math.round(points / 72D * PIXELS_PER_INCH);\r
+ }\r
+ \r
+ public static double pointsToMillimeters(double points) {\r
+ return points / 72D * 25.4;\r
+ }\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/* ====================================================================\r
+Licensed to the Apache Software Foundation (ASF) under one or more\r
+contributor license agreements. See the NOTICE file distributed with\r
+this work for additional information regarding copyright ownership.\r
+The ASF licenses this file to You under the Apache License, Version 2.0\r
+(the "License"); you may not use this file except in compliance with\r
+the License. You may obtain a copy of the License at\r
+\r
+http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+Unless required by applicable law or agreed to in writing, software\r
+distributed under the License is distributed on an "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+See the License for the specific language governing permissions and\r
+limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.ss.examples;\r
+\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.ss.usermodel.*;\r
+import org.apache.poi.xssf.usermodel.*;\r
+\r
+/**\r
+ * Shows how various alignment options work.\r
+ */\r
+public class AligningCells {\r
+\r
+ public static void main(String[] args) throws IOException {\r
+ Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();\r
+\r
+ Sheet sheet = wb.createSheet();\r
+ Row row = sheet.createRow((short) 2);\r
+ row.setHeightInPoints(30);\r
+ for (int i = 0; i < 8; i++) {\r
+ //column width is set in units of 1/256th of a character width\r
+ sheet.setColumnWidth(i, 256 * 15);\r
+ }\r
+\r
+ createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);\r
+ createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);\r
+ createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);\r
+ createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);\r
+ createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);\r
+ createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);\r
+ createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);\r
+\r
+ // Write the output to a file\r
+ FileOutputStream fileOut = new FileOutputStream("ss-example-align.xlsx");\r
+ wb.write(fileOut);\r
+ fileOut.close();\r
+ }\r
+\r
+ /**\r
+ * Creates a cell and aligns it a certain way.\r
+ *\r
+ * @param wb the workbook\r
+ * @param row the row to create the cell in\r
+ * @param column the column number to create the cell in\r
+ * @param halign the horizontal alignment for the cell.\r
+ */\r
+ private static void createCell(Workbook wb, Row row, short column, short halign, short valign) {\r
+ CreationHelper ch = wb.getCreationHelper();\r
+ Cell cell = row.createCell(column);\r
+ cell.setCellValue(ch.createRichTextString("Align It"));\r
+ CellStyle cellStyle = wb.createCellStyle();\r
+ cellStyle.setAlignment(halign);\r
+ cellStyle.setVerticalAlignment(valign);\r
+ cell.setCellStyle(cellStyle);\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb){
+ Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
+ 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;
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.
+ * <pre>
+ * Usage:
+ * CalendarDemo -xls|xlsx <year>
+ * </pre>
+ *
+ * @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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb){
+ Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
+
+ 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;
+ }
+}
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.ss.examples;\r
+\r
+import java.io.File;\r
+\r
+import org.apache.poi.hssf.usermodel.HSSFFont;\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.hssf.util.HSSFColor;\r
+import org.apache.poi.ss.usermodel.Cell;\r
+import org.apache.poi.ss.usermodel.CellStyle;\r
+import org.apache.poi.ss.usermodel.Color;\r
+import org.apache.poi.ss.usermodel.DataFormatter;\r
+import org.apache.poi.ss.usermodel.Font;\r
+import org.apache.poi.ss.usermodel.Row;\r
+import org.apache.poi.ss.usermodel.Sheet;\r
+import org.apache.poi.ss.usermodel.Workbook;\r
+import org.apache.poi.ss.usermodel.WorkbookFactory;\r
+import org.apache.poi.ss.util.CellReference;\r
+import org.apache.poi.xssf.usermodel.XSSFColor;\r
+import org.apache.poi.xssf.usermodel.XSSFFont;\r
+\r
+/**\r
+ * Demonstrates how to read excel styles for cells\r
+ */\r
+public class CellStyleDetails {\r
+ public static void main(String[] args) throws Exception {\r
+ if(args.length == 0) {\r
+ throw new IllegalArgumentException("Filename must be given");\r
+ }\r
+ \r
+ Workbook wb = WorkbookFactory.create(new File(args[0]));\r
+ DataFormatter formatter = new DataFormatter();\r
+ \r
+ for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {\r
+ Sheet sheet = wb.getSheetAt(sn);\r
+ System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());\r
+ \r
+ for(Row row : sheet) {\r
+ System.out.println(" Row " + row.getRowNum());\r
+ \r
+ for(Cell cell : row) {\r
+ CellReference ref = new CellReference(cell);\r
+ System.out.print(" " + ref.formatAsString());\r
+ System.out.print(" (" + cell.getColumnIndex() + ") ");\r
+ \r
+ CellStyle style = cell.getCellStyle();\r
+ System.out.print("Format=" + style.getDataFormatString() + " ");\r
+ System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");\r
+ System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");\r
+ \r
+ Font font = wb.getFontAt( style.getFontIndex() );\r
+ System.out.print("Font=" + font.getFontName() + " ");\r
+ System.out.print("FontColor=");\r
+ if(font instanceof HSSFFont) {\r
+ System.out.print( renderColor( ((HSSFFont)font).getHSSFColor((HSSFWorkbook)wb)) );\r
+ }\r
+ if(font instanceof XSSFFont) {\r
+ System.out.print( renderColor( ((XSSFFont)font).getXSSFColor()) );\r
+ }\r
+ \r
+ System.out.println();\r
+ System.out.println(" " + formatter.formatCellValue(cell));\r
+ }\r
+ }\r
+ \r
+ System.out.println();\r
+ }\r
+ }\r
+ \r
+ private static String renderColor(Color color) {\r
+ if(color instanceof HSSFColor) {\r
+ return ((HSSFColor)color).getHexString();\r
+ } else if(color instanceof XSSFColor) {\r
+ return ((XSSFColor)color).getARGBHex();\r
+ } else {\r
+ return "(none)";\r
+ }\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ====================================================================\r
+ */\r
+\r
+package org.apache.poi.ss.examples;\r
+\r
+import org.apache.poi.hssf.usermodel.*;\r
+import org.apache.poi.ss.usermodel.*;\r
+import org.apache.poi.ss.util.CellRangeAddress;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+/**\r
+ * Excel Conditional Formatting -- Examples\r
+ *\r
+ * <p>\r
+ * Based on the code snippets from http://www.contextures.com/xlcondformat03.html\r
+ * </p>\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class ConditionalFormats {\r
+\r
+ public static void main(String[] args) throws IOException {\r
+ Workbook wb;\r
+\r
+ if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook();\r
+ else wb = new XSSFWorkbook();\r
+\r
+ sameCell(wb.createSheet("Same Cell"));\r
+ multiCell(wb.createSheet("MultiCell"));\r
+ errors(wb.createSheet("Errors"));\r
+ hideDupplicates(wb.createSheet("Hide Dups"));\r
+ formatDuplicates(wb.createSheet("Duplicates"));\r
+ inList(wb.createSheet("In List"));\r
+ expiry(wb.createSheet("Expiry"));\r
+ shadeAlt(wb.createSheet("Shade Alt"));\r
+ shadeBands(wb.createSheet("Shade Bands"));\r
+\r
+ // Write the output to a file\r
+ String file = "cf-poi.xls";\r
+ if(wb instanceof XSSFWorkbook) file += "x";\r
+ FileOutputStream out = new FileOutputStream(file);\r
+ wb.write(out);\r
+ out.close();\r
+\r
+ }\r
+\r
+ /**\r
+ * Highlight cells based on their values\r
+ */\r
+ static void sameCell(Sheet sheet) {\r
+ sheet.createRow(0).createCell(0).setCellValue(84);\r
+ sheet.createRow(1).createCell(0).setCellValue(74);\r
+ sheet.createRow(2).createCell(0).setCellValue(50);\r
+ sheet.createRow(3).createCell(0).setCellValue(51);\r
+ sheet.createRow(4).createCell(0).setCellValue(49);\r
+ sheet.createRow(5).createCell(0).setCellValue(41);\r
+\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ // Condition 1: Cell Value Is greater than 70 (Blue Fill)\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.GT, "70");\r
+ PatternFormatting fill1 = rule1.createPatternFormatting();\r
+ fill1.setFillBackgroundColor(IndexedColors.BLUE.index);\r
+ fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
+\r
+ // Condition 2: Cell Value Is less than 50 (Green Fill)\r
+ ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.LT, "50");\r
+ PatternFormatting fill2 = rule2.createPatternFormatting();\r
+ fill2.setFillBackgroundColor(IndexedColors.GREEN.index);\r
+ fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A1:A6")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1, rule2);\r
+\r
+ sheet.getRow(0).createCell(2).setCellValue("<== Condition 1: Cell Value Is greater than 70 (Blue Fill)");\r
+ sheet.getRow(4).createCell(2).setCellValue("<== Condition 2: Cell Value Is less than 50 (Green Fill)");\r
+ }\r
+\r
+ /**\r
+ * Highlight multiple cells based on a formula\r
+ */\r
+ static void multiCell(Sheet sheet) {\r
+ // header row\r
+ Row row0 = sheet.createRow(0);\r
+ row0.createCell(0).setCellValue("Units");\r
+ row0.createCell(1).setCellValue("Cost");\r
+ row0.createCell(2).setCellValue("Total");\r
+\r
+ Row row1 = sheet.createRow(1);\r
+ row1.createCell(0).setCellValue(71);\r
+ row1.createCell(1).setCellValue(29);\r
+ row1.createCell(2).setCellValue(2059);\r
+\r
+ Row row2 = sheet.createRow(2);\r
+ row2.createCell(0).setCellValue(85);\r
+ row2.createCell(1).setCellValue(29);\r
+ row2.createCell(2).setCellValue(2059);\r
+\r
+ Row row3 = sheet.createRow(3);\r
+ row3.createCell(0).setCellValue(71);\r
+ row3.createCell(1).setCellValue(29);\r
+ row3.createCell(2).setCellValue(2059);\r
+\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ // Condition 1: Formula Is =$B2>75 (Blue Fill)\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("$A2>75");\r
+ PatternFormatting fill1 = rule1.createPatternFormatting();\r
+ fill1.setFillBackgroundColor(IndexedColors.BLUE.index);\r
+ fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A2:C4")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1);\r
+\r
+ sheet.getRow(2).createCell(4).setCellValue("<== Condition 1: Formula Is =$B2>75 (Blue Fill)");\r
+ }\r
+\r
+ /**\r
+ * Use Excel conditional formatting to check for errors,\r
+ * and change the font colour to match the cell colour.\r
+ * In this example, if formula result is #DIV/0! then it will have white font colour.\r
+ */\r
+ static void errors(Sheet sheet) {\r
+ sheet.createRow(0).createCell(0).setCellValue(84);\r
+ sheet.createRow(1).createCell(0).setCellValue(0);\r
+ sheet.createRow(2).createCell(0).setCellFormula("ROUND(A1/A2,0)");\r
+ sheet.createRow(3).createCell(0).setCellValue(0);\r
+ sheet.createRow(4).createCell(0).setCellFormula("ROUND(A6/A4,0)");\r
+ sheet.createRow(5).createCell(0).setCellValue(41);\r
+\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ // Condition 1: Formula Is =ISERROR(C2) (White Font)\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("ISERROR(A1)");\r
+ FontFormatting font = rule1.createFontFormatting();\r
+ font.setFontColorIndex(IndexedColors.WHITE.index);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A1:A6")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1);\r
+\r
+ sheet.getRow(2).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)");\r
+ sheet.getRow(4).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)");\r
+ }\r
+\r
+ /**\r
+ * Use Excel conditional formatting to hide the duplicate values,\r
+ * and make the list easier to read. In this example, when the table is sorted by Region,\r
+ * the second (and subsequent) occurences of each region name will have white font colour.\r
+ */\r
+ static void hideDupplicates(Sheet sheet) {\r
+ sheet.createRow(0).createCell(0).setCellValue("City");\r
+ sheet.createRow(1).createCell(0).setCellValue("Boston");\r
+ sheet.createRow(2).createCell(0).setCellValue("Boston");\r
+ sheet.createRow(3).createCell(0).setCellValue("Chicago");\r
+ sheet.createRow(4).createCell(0).setCellValue("Chicago");\r
+ sheet.createRow(5).createCell(0).setCellValue("New York");\r
+\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ // Condition 1: Formula Is =A2=A1 (White Font)\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("A2=A1");\r
+ FontFormatting font = rule1.createFontFormatting();\r
+ font.setFontColorIndex(IndexedColors.WHITE.index);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A2:A6")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1);\r
+\r
+ sheet.getRow(1).createCell(1).setCellValue("<== the second (and subsequent) " +\r
+ "occurences of each region name will have white font colour. " +\r
+ "Condition: Formula Is =A2=A1 (White Font)");\r
+ }\r
+\r
+ /**\r
+ * Use Excel conditional formatting to highlight duplicate entries in a column.\r
+ */\r
+ static void formatDuplicates(Sheet sheet) {\r
+ sheet.createRow(0).createCell(0).setCellValue("Code");\r
+ sheet.createRow(1).createCell(0).setCellValue(4);\r
+ sheet.createRow(2).createCell(0).setCellValue(3);\r
+ sheet.createRow(3).createCell(0).setCellValue(6);\r
+ sheet.createRow(4).createCell(0).setCellValue(3);\r
+ sheet.createRow(5).createCell(0).setCellValue(5);\r
+ sheet.createRow(6).createCell(0).setCellValue(8);\r
+ sheet.createRow(7).createCell(0).setCellValue(0);\r
+ sheet.createRow(8).createCell(0).setCellValue(2);\r
+ sheet.createRow(9).createCell(0).setCellValue(8);\r
+ sheet.createRow(10).createCell(0).setCellValue(6);\r
+\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ // Condition 1: Formula Is =A2=A1 (White Font)\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($A$2:$A$11,A2)>1");\r
+ FontFormatting font = rule1.createFontFormatting();\r
+ font.setFontStyle(false, true);\r
+ font.setFontColorIndex(IndexedColors.BLUE.index);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A2:A11")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1);\r
+\r
+ sheet.getRow(2).createCell(1).setCellValue("<== Duplicates numbers in the column are highlighted. " +\r
+ "Condition: Formula Is =COUNTIF($A$2:$A$11,A2)>1 (Blue Font)");\r
+ }\r
+\r
+ /**\r
+ * Use Excel conditional formatting to highlight items that are in a list on the worksheet.\r
+ */\r
+ static void inList(Sheet sheet) {\r
+ sheet.createRow(0).createCell(0).setCellValue("Codes");\r
+ sheet.createRow(1).createCell(0).setCellValue("AA");\r
+ sheet.createRow(2).createCell(0).setCellValue("BB");\r
+ sheet.createRow(3).createCell(0).setCellValue("GG");\r
+ sheet.createRow(4).createCell(0).setCellValue("AA");\r
+ sheet.createRow(5).createCell(0).setCellValue("FF");\r
+ sheet.createRow(6).createCell(0).setCellValue("XX");\r
+ sheet.createRow(7).createCell(0).setCellValue("CC");\r
+\r
+ sheet.getRow(0).createCell(2).setCellValue("Valid");\r
+ sheet.getRow(1).createCell(2).setCellValue("AA");\r
+ sheet.getRow(2).createCell(2).setCellValue("BB");\r
+ sheet.getRow(3).createCell(2).setCellValue("CC");\r
+\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ // Condition 1: Formula Is =A2=A1 (White Font)\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($C$2:$C$4,A2)");\r
+ PatternFormatting fill1 = rule1.createPatternFormatting();\r
+ fill1.setFillBackgroundColor(IndexedColors.LIGHT_BLUE.index);\r
+ fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A2:A8")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1);\r
+\r
+ sheet.getRow(2).createCell(3).setCellValue("<== Use Excel conditional formatting to highlight items that are in a list on the worksheet");\r
+ }\r
+\r
+ /**\r
+ * Use Excel conditional formatting to highlight payments that are due in the next thirty days.\r
+ * In this example, Due dates are entered in cells A2:A4.\r
+ */\r
+ static void expiry(Sheet sheet) {\r
+ CellStyle style = sheet.getWorkbook().createCellStyle();\r
+ style.setDataFormat((short)BuiltinFormats.getBuiltinFormat("d-mmm"));\r
+\r
+ sheet.createRow(0).createCell(0).setCellValue("Date");\r
+ sheet.createRow(1).createCell(0).setCellFormula("TODAY()+29");\r
+ sheet.createRow(2).createCell(0).setCellFormula("A2+1");\r
+ sheet.createRow(3).createCell(0).setCellFormula("A3+1");\r
+\r
+ for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style);\r
+\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ // Condition 1: Formula Is =A2=A1 (White Font)\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("AND(A2-TODAY()>=0,A2-TODAY()<=30)");\r
+ FontFormatting font = rule1.createFontFormatting();\r
+ font.setFontStyle(false, true);\r
+ font.setFontColorIndex(IndexedColors.BLUE.index);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A2:A4")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1);\r
+\r
+ sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted");\r
+ }\r
+\r
+ /**\r
+ * Use Excel conditional formatting to shade alternating rows on the worksheet\r
+ */\r
+ static void shadeAlt(Sheet sheet) {\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ // Condition 1: Formula Is =A2=A1 (White Font)\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)");\r
+ PatternFormatting fill1 = rule1.createPatternFormatting();\r
+ fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);\r
+ fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A1:Z100")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1);\r
+\r
+ sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows");\r
+ sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),2) (Light Green Fill)");\r
+ }\r
+\r
+ /**\r
+ * You can use Excel conditional formatting to shade bands of rows on the worksheet. \r
+ * In this example, 3 rows are shaded light grey, and 3 are left with no shading.\r
+ * In the MOD function, the total number of rows in the set of banded rows (6) is entered.\r
+ */\r
+ static void shadeBands(Sheet sheet) {\r
+ SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
+\r
+ ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),6)<3");\r
+ PatternFormatting fill1 = rule1.createPatternFormatting();\r
+ fill1.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index);\r
+ fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
+\r
+ CellRangeAddress[] regions = {\r
+ CellRangeAddress.valueOf("A1:Z100")\r
+ };\r
+\r
+ sheetCF.addConditionalFormatting(regions, rule1);\r
+\r
+ sheet.createRow(0).createCell(1).setCellValue("Shade Bands of Rows");\r
+ sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),6)<2 (Light Grey Fill)");\r
+ }\r
+}\r
--- /dev/null
+ /* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+ ==================================================================== */\r
+\r
+package org.apache.poi.ss.examples;\r
+import java.io.*;\r
+import org.apache.poi.xssf.usermodel.*;\r
+import org.apache.poi.hssf.usermodel.*;\r
+import org.apache.poi.ss.usermodel.*;\r
+import org.apache.poi.ss.util.CellRangeAddressList;\r
+\r
+/**\r
+ * Demonstrates one technique that may be used to create linked or dependent\r
+ * drop down lists. This refers to a situation in which the selection made\r
+ * in one drop down list affects the options that are displayed in the second\r
+ * or subsequent drop down list(s). In this example, the value the user selects\r
+ * from the down list in cell A1 will affect the values displayed in the linked\r
+ * drop down list in cell B1. For the sake of simplicity, the data for the drop\r
+ * down lists is included on the same worksheet but this does not have to be the\r
+ * case; the data could appear on a separate sheet. If this were done, then the\r
+ * names for the regions would have to be different, they would have to include\r
+ * the name of the sheet.\r
+ * \r
+ * There are two keys to this technique. The first is the use of named area or \r
+ * regions of cells to hold the data for the drop down lists and the second is\r
+ * making use of the INDIRECT() function to convert a name into the addresses\r
+ * of the cells it refers to.\r
+ * \r
+ * Note that whilst this class builds just two linked drop down lists, there is\r
+ * nothing to prevent more being created. Quite simply, use the value selected\r
+ * by the user in one drop down list to determine what is shown in another and the\r
+ * value selected in that drop down list to determine what is shown in a third,\r
+ * and so on. Also, note that the data for the drop down lists is contained on\r
+ * contained on the same sheet as the validations themselves. This is done simply\r
+ * for simplicity and there is nothing to prevent a separate sheet being created\r
+ * and used to hold the data. If this is done then problems may be encountered\r
+ * if the sheet is opened with OpenOffice Calc. To prevent these problems, it is\r
+ * better to include the name of the sheet when calling the setRefersToFormula()\r
+ * method.\r
+ *\r
+ * @author Mark Beardsley [msb at apache.org]\r
+ * @version 1.00 30th March 2012\r
+ */\r
+public class LinkedDropDownLists {\r
+\r
+ LinkedDropDownLists(String workbookName) {\r
+ File file = null;\r
+ FileOutputStream fos = null;\r
+ Workbook workbook = null;\r
+ Sheet sheet = null;\r
+ DataValidationHelper dvHelper = null;\r
+ DataValidationConstraint dvConstraint = null;\r
+ DataValidation validation = null;\r
+ CellRangeAddressList addressList = null;\r
+ try {\r
+\r
+ // Using the ss.usermodel allows this class to support both binary\r
+ // and xml based workbooks. The choice of which one to create is\r
+ // made by checking the file extension.\r
+ if (workbookName.endsWith(".xlsx")) {\r
+ workbook = new XSSFWorkbook();\r
+ } else {\r
+ workbook = new HSSFWorkbook();\r
+ }\r
+ \r
+ // Build the sheet that will hold the data for the validations. This\r
+ // must be done first as it will create names that are referenced \r
+ // later.\r
+ sheet = workbook.createSheet("Linked Validations");\r
+ LinkedDropDownLists.buildDataSheet(sheet);\r
+\r
+ // Build the first data validation to occupy cell A1. Note\r
+ // that it retrieves it's data from the named area or region called\r
+ // CHOICES. Further information about this can be found in the\r
+ // static buildDataSheet() method below.\r
+ addressList = new CellRangeAddressList(0, 0, 0, 0);\r
+ dvHelper = sheet.getDataValidationHelper();\r
+ dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");\r
+ validation = dvHelper.createValidation(dvConstraint, addressList);\r
+ sheet.addValidationData(validation);\r
+ \r
+ // Now, build the linked or dependent drop down list that will\r
+ // occupy cell B1. The key to the whole process is the use of the\r
+ // INDIRECT() function. In the buildDataSheet(0 method, a series of\r
+ // named regions are created and the names of three of them mirror\r
+ // the options available to the user in the first drop down list\r
+ // (in cell A1). Using the INDIRECT() function makes it possible\r
+ // to convert the selection the user makes in that first drop down\r
+ // into the addresses of a named region of cells and then to use\r
+ // those cells to populate the second drop down list.\r
+ addressList = new CellRangeAddressList(0, 0, 1, 1);\r
+ dvConstraint = dvHelper.createFormulaListConstraint(\r
+ "INDIRECT(UPPER($A$1))");\r
+ validation = dvHelper.createValidation(dvConstraint, addressList);\r
+ sheet.addValidationData(validation);\r
+ \r
+ file = new File(workbookName);\r
+ fos = new FileOutputStream(file);\r
+ workbook.write(fos);\r
+ } catch (IOException ioEx) {\r
+ System.out.println("Caught a: " + ioEx.getClass().getName());\r
+ System.out.println("Message: " + ioEx.getMessage());\r
+ System.out.println("Stacktrace follws:.....");\r
+ ioEx.printStackTrace(System.out);\r
+ } finally {\r
+ try {\r
+ if (fos != null) {\r
+ fos.close();\r
+ fos = null;\r
+ }\r
+ } catch (IOException ioEx) {\r
+ System.out.println("Caught a: " + ioEx.getClass().getName());\r
+ System.out.println("Message: " + ioEx.getMessage());\r
+ System.out.println("Stacktrace follws:.....");\r
+ ioEx.printStackTrace(System.out);\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Called to populate the named areas/regions. The contents of the cells on\r
+ * row one will be used to populate the first drop down list. The contents of\r
+ * the cells on rows two, three and four will be used to populate the second\r
+ * drop down list, just which row will be determined by the choice the user\r
+ * makes in the first drop down list.\r
+ * \r
+ * In all cases, the approach is to create a row, create and populate cells\r
+ * with data and then specify a name that identifies those cells. With the\r
+ * exception of the first range, the names that are chosen for each range\r
+ * of cells are quite important. In short, each of the options the user \r
+ * could select in the first drop down list is used as the name for another\r
+ * range of cells. Thus, in this example, the user can select either \r
+ * 'Animal', 'Vegetable' or 'Mineral' in the first drop down and so the\r
+ * sheet contains ranges named 'ANIMAL', 'VEGETABLE' and 'MINERAL'.\r
+ * \r
+ * @param dataSheet An instance of a class that implements the Sheet Sheet\r
+ * interface (HSSFSheet or XSSFSheet).\r
+ */\r
+ private static final void buildDataSheet(Sheet dataSheet) {\r
+ Row row = null;\r
+ Cell cell = null;\r
+ Name name = null;\r
+\r
+ // The first row will hold the data for the first validation.\r
+ row = dataSheet.createRow(10);\r
+ cell = row.createCell(0);\r
+ cell.setCellValue("Animal");\r
+ cell = row.createCell(1);\r
+ cell.setCellValue("Vegetable");\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Mineral");\r
+ name = dataSheet.getWorkbook().createName();\r
+ name.setRefersToFormula("$A$11:$C$11");\r
+ name.setNameName("CHOICES");\r
+\r
+ // The next three rows will hold the data that will be used to\r
+ // populate the second, or linked, drop down list.\r
+ row = dataSheet.createRow(11);\r
+ cell = row.createCell(0);\r
+ cell.setCellValue("Lion");\r
+ cell = row.createCell(1);\r
+ cell.setCellValue("Tiger");\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Leopard");\r
+ cell = row.createCell(3);\r
+ cell.setCellValue("Elephant");\r
+ cell = row.createCell(4);\r
+ cell.setCellValue("Eagle");\r
+ cell = row.createCell(5);\r
+ cell.setCellValue("Horse");\r
+ cell = row.createCell(6);\r
+ cell.setCellValue("Zebra");\r
+ name = dataSheet.getWorkbook().createName();\r
+ name.setRefersToFormula("$A$12:$G$12");\r
+ name.setNameName("ANIMAL");\r
+\r
+ row = dataSheet.createRow(12);\r
+ cell = row.createCell(0);\r
+ cell.setCellValue("Cabbage");\r
+ cell = row.createCell(1);\r
+ cell.setCellValue("Cauliflower");\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Potato");\r
+ cell = row.createCell(3);\r
+ cell.setCellValue("Onion");\r
+ cell = row.createCell(4);\r
+ cell.setCellValue("Beetroot");\r
+ cell = row.createCell(5);\r
+ cell.setCellValue("Asparagus");\r
+ cell = row.createCell(6);\r
+ cell.setCellValue("Spinach");\r
+ cell = row.createCell(7);\r
+ cell.setCellValue("Chard");\r
+ name = dataSheet.getWorkbook().createName();\r
+ name.setRefersToFormula("$A$13:$H$13");\r
+ name.setNameName("VEGETABLE");\r
+\r
+ row = dataSheet.createRow(13);\r
+ cell = row.createCell(0);\r
+ cell.setCellValue("Bauxite");\r
+ cell = row.createCell(1);\r
+ cell.setCellValue("Quartz");\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Feldspar");\r
+ cell = row.createCell(3);\r
+ cell.setCellValue("Shist");\r
+ cell = row.createCell(4);\r
+ cell.setCellValue("Shale");\r
+ cell = row.createCell(5);\r
+ cell.setCellValue("Mica");\r
+ name = dataSheet.getWorkbook().createName();\r
+ name.setRefersToFormula("$A$14:$F$14");\r
+ name.setNameName("MINERAL");\r
+ }\r
+}\r
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb){
+ Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
+
+ 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)");
+ }
+}
--- /dev/null
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb) {
+ Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
+ 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;
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb){
+ Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
+ 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;
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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 <em>one</em> way to convert an Excel spreadsheet into a CSV
+ * file. This class makes the following assumptions;
+ * <list>
+ * <li>1. Where the Excel workbook contains more that one worksheet, then a single
+ * CSV file will contain the data from all of the worksheets.</li>
+ * <li>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 - ,,.</li>
+ * <li>3. Empty fields will represent missing cells.</li>
+ * <li>4. A record consisting of empty fields will be used to represent an empty row
+ * in the Excel workbook.</li>
+ * </list>
+ * Therefore, if the worksheet looked like this;
+ *
+ * <pre>
+ * ___________________________________________
+ * | | | | | |
+ * | A | B | C | D | E |
+ * ___|_______|_______|_______|_______|_______|
+ * | | | | | |
+ * 1 | 1 | 2 | 3 | 4 | 5 |
+ * ___|_______|_______|_______|_______|_______|
+ * | | | | | |
+ * 2 | | | | | |
+ * ___|_______|_______|_______|_______|_______|
+ * | | | | | |
+ * 3 | | A | | B | |
+ * ___|_______|_______|_______|_______|_______|
+ * | | | | | |
+ * 4 | | | | | Z |
+ * ___|_______|_______|_______|_______|_______|
+ * | | | | | |
+ * 5 | 1,400 | | 250 | | |
+ * ___|_______|_______|_______|_______|_______|
+ *
+ * </pre>
+ *
+ * Then, the resulting CSV file will contain the following lines (records);
+ * <pre>
+ * 1,2,3,4,5
+ * ,,,,
+ * ,A,,B,
+ * ,,,,Z
+ * "1,400",,250,,
+ * </pre><p>
+ * 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.
+ * </p><p>
+ * 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.
+ * </p><p>
+ * 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.
+ * </p><p>
+ * 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".
+ * </p><p>
+ * 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.
+ * </p>
+ * @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<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<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<String> 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<String> csvLine = new ArrayList<String>();
+
+ // 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 <em>"Hello" he said</em> then it should be modified
+ * to appear as <em>"""Hello"" he said"</em>. Furthermore, if the field
+ * contains either embedded separator or EOL characters, it should also
+ * be surrounded with speech marks. As a result <em>1,400</em> would become
+ * <em>"1,400"</em> 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"));
+ }
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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 <tt>result</tt> is <tt>NaN</> or <tt>Infinity</tt>
+ */
+ private void checkValue(double result) throws EvaluationException {
+ if (Double.isNaN(result) || Double.isInfinite(result)) {
+ throw new EvaluationException(ErrorEval.NUM_ERROR);
+ }
+ }
+}
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ====================================================================\r
+ */\r
+\r
+package org.apache.poi.ss.examples.formula;\r
+\r
+import org.apache.poi.ss.formula.OperationEvaluationContext;\r
+import org.apache.poi.ss.formula.eval.ErrorEval;\r
+import org.apache.poi.ss.formula.eval.ValueEval;\r
+import org.apache.poi.ss.formula.functions.FreeRefFunction;\r
+import org.apache.poi.ss.formula.udf.UDFFinder;\r
+import org.apache.poi.ss.usermodel.Row;\r
+import org.apache.poi.ss.usermodel.Sheet;\r
+import org.apache.poi.ss.usermodel.Workbook;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+/**\r
+ * Demonstrates how to use functions provided by third-party add-ins, e.g. Bloomberg Excel Add-in.\r
+ *\r
+ * There can be situations when you are not interested in formula evaluation,\r
+ * you just need to set the formula and the workbook will be evaluation by the client.\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class SettingExternalFunction {\r
+\r
+ /**\r
+ * wrap external functions in a plugin\r
+ */\r
+ public static class BloombergAddIn implements UDFFinder {\r
+ private final Map<String, FreeRefFunction> _functionsByName;\r
+\r
+ public BloombergAddIn() {\r
+ // dummy function that returns NA\r
+ // don't care about the implementation, we are not interested in evaluation\r
+ // and this method will never be called\r
+ FreeRefFunction NA = new FreeRefFunction() {\r
+ public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {\r
+ return ErrorEval.NA;\r
+ }\r
+ };\r
+ _functionsByName = new HashMap<String, FreeRefFunction>();\r
+ _functionsByName.put("BDP", NA);\r
+ _functionsByName.put("BDH", NA);\r
+ _functionsByName.put("BDS", NA);\r
+ }\r
+\r
+ public FreeRefFunction findFunction(String name) {\r
+ return _functionsByName.get(name.toUpperCase());\r
+ }\r
+\r
+ }\r
+\r
+ public static void main( String[] args ) throws IOException {\r
+\r
+ Workbook wb = new XSSFWorkbook(); // or new HSSFWorkbook()\r
+\r
+ // register the add-in\r
+ wb.addToolPack(new BloombergAddIn());\r
+\r
+ Sheet sheet = wb.createSheet();\r
+ Row row = sheet.createRow(0);\r
+ row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100");\r
+ row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") ");\r
+ row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") ");\r
+\r
+ FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx");\r
+ wb.write(out);\r
+ out.close();\r
+\r
+ }\r
+\r
+}\r
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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);
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<Short, String> 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<Short, String> VERTICAL_ALIGN = mapFor(
+ VERTICAL_BOTTOM, "bottom", VERTICAL_CENTER, "middle", VERTICAL_TOP,
+ "top");
+
+ private static final Map<Short, String> 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 <K, V> Map<K, V> mapFor(Object... mapping) {
+ Map<K, V> map = new HashMap<K, V>();
+ 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 "<tt>.xlsx</tt>" 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(
+ "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>%n");
+ out.format("<html>%n");
+ out.format("<head>%n");
+ out.format("</head>%n");
+ out.format("<body>%n");
+ }
+
+ print();
+
+ if (completeHTML) {
+ out.format("</body>%n");
+ out.format("</html>%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("<link href=\"excelStyle.css\" rel=\"stylesheet\" type=\"text/css\">%n");
+ out.format("<style type=\"text/css\">%n");
+ printStyles();
+ out.format("</style>%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<CellStyle> seen = new HashSet<CellStyle>();
+ for (int i = 0; i < wb.getNumberOfSheets(); i++) {
+ Sheet sheet = wb.getSheetAt(i);
+ Iterator<Row> 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 <K> void styleOut(String attr, K key, Map<K, String> 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("<table class=%s>%n", DEFAULTS_CLASS);
+ printCols(sheet);
+ printSheetContent(sheet);
+ out.format("</table>%n");
+ }
+
+ private void printCols(Sheet sheet) {
+ out.format("<col/>%n");
+ ensureColumnBounds(sheet);
+ for (int i = firstColumn; i < endColumn; i++) {
+ out.format("<col/>%n");
+ }
+ }
+
+ private void ensureColumnBounds(Sheet sheet) {
+ if (gotBounds)
+ return;
+
+ Iterator<Row> 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("<thead>%n");
+ out.format(" <tr class=%s>%n", COL_HEAD_CLASS);
+ out.format(" <th class=%s>◊</th>%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(" <th class=%s>%s</th>%n", COL_HEAD_CLASS, colName);
+ }
+ out.format(" </tr>%n");
+ out.format("</thead>%n");
+ }
+
+ private void printSheetContent(Sheet sheet) {
+ printColumnHeads();
+
+ out.format("<tbody>%n");
+ Iterator<Row> rows = sheet.rowIterator();
+ while (rows.hasNext()) {
+ Row row = rows.next();
+
+ out.format(" <tr>%n");
+ out.format(" <td class=%s>%d</td>%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(" <td class=%s %s>%s</td>%n", styleName(style),
+ attrs, content);
+ }
+ out.format(" </tr>%n");
+ }
+ out.format("</tbody>%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
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<Integer,HSSFColor> 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
--- /dev/null
+/*
+ ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT 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;
+}
--- /dev/null
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!--
+ ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ ====================================================================
+-->
+<html>
+<head>
+</head>
+<body>
+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.
+</body>
+</html>
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import org.apache.poi.openxml4j.opc.PackagePart;\r
+\r
+import java.awt.*;\r
+import java.awt.geom.Rectangle2D;\r
+import java.io.FileInputStream;\r
+import java.io.InputStream;\r
+import java.util.List;\r
+\r
+/**\r
+ * Demonstrates how you can extract data from a .pptx file\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public final class DataExtraction {\r
+\r
+ public static void main(String args[]) throws Exception {\r
+\r
+ if (args.length == 0) {\r
+ System.out.println("Input file is required");\r
+ return;\r
+ }\r
+\r
+ FileInputStream is = new FileInputStream(args[0]);\r
+ XMLSlideShow ppt = new XMLSlideShow(is);\r
+ is.close();\r
+\r
+ // Get the document's embedded files.\r
+ List<PackagePart> embeds = ppt.getAllEmbedds();\r
+ for (PackagePart p : embeds) {\r
+ String type = p.getContentType();\r
+ String name = p.getPartName().getName(); //typically file name\r
+ \r
+ InputStream pIs = p.getInputStream();\r
+ // make sense of the part data\r
+ pIs.close();\r
+ \r
+ }\r
+\r
+ // Get the document's embedded files.\r
+ List<XSLFPictureData> images = ppt.getAllPictures();\r
+ for (XSLFPictureData data : images) {\r
+ PackagePart p = data.getPackagePart();\r
+\r
+ String type = p.getContentType();\r
+ String name = data.getFileName();\r
+\r
+ InputStream pIs = p.getInputStream();\r
+ // make sense of the image data\r
+ pIs.close();\r
+\r
+\r
+\r
+ }\r
+\r
+ Dimension pageSize = ppt.getPageSize(); // size of the canvas in points\r
+ for(XSLFSlide slide : ppt.getSlides()) {\r
+ for(XSLFShape shape : slide){\r
+ Rectangle2D anchor = shape.getAnchor(); // position on the canvas\r
+ if(shape instanceof XSLFTextShape) {\r
+ XSLFTextShape txShape = (XSLFTextShape)shape;\r
+ System.out.println(txShape.getText());\r
+ } else if (shape instanceof XSLFPictureShape){\r
+ XSLFPictureShape pShape = (XSLFPictureShape)shape;\r
+ XSLFPictureData pData = pShape.getPictureData();\r
+ System.out.println(pData.getFileName());\r
+ } else {\r
+ System.out.println("Process me: " + shape.getClass());\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import java.io.FileInputStream;\r
+import java.io.FileOutputStream;\r
+\r
+/**\r
+ * Merge multiple pptx presentations together\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public final class MergePresentations {\r
+\r
+ public static void main(String args[]) throws Exception {\r
+ XMLSlideShow ppt = new XMLSlideShow();\r
+\r
+ for(String arg : args){\r
+ FileInputStream is = new FileInputStream(arg);\r
+ XMLSlideShow src = new XMLSlideShow(is);\r
+ is.close();\r
+\r
+ for(XSLFSlide srcSlide : src.getSlides()){\r
+ ppt.createSlide().importContent(srcSlide);\r
+ }\r
+ }\r
+\r
+ FileOutputStream out = new FileOutputStream("merged.pptx");\r
+ ppt.write(out);\r
+ out.close();\r
+ }\r
+\r
+}\r
--- /dev/null
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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 <pptx file>");
+ }
+
+ 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());
+ }
+ }
+
+ }
+}
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ====================================================================\r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import org.apache.poi.POIXMLDocumentPart;\r
+import org.apache.poi.ss.util.CellRangeAddress;\r
+import org.apache.poi.ss.util.CellReference;\r
+import org.apache.poi.xssf.usermodel.XSSFRow;\r
+import org.apache.poi.xssf.usermodel.XSSFSheet;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieChart;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieSer;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData;\r
+import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.FileInputStream;\r
+import java.io.FileOutputStream;\r
+import java.io.FileReader;\r
+import java.io.OutputStream;\r
+\r
+/**\r
+ * Build a pie chart from a template pptx\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class PieChartDemo {\r
+ private static void usage(){\r
+ System.out.println("Usage: PieChartDemo <pie-chart-template.pptx> <pie-chart-data.txt>");\r
+ System.out.println(" pie-chart-template.pptx template with a pie chart");\r
+ System.out.println(" pie-chart-data.txt the model to set. First line is chart title, " +\r
+ "then go pairs {axis-label value}");\r
+ }\r
+\r
+ public static void main(String[] args) throws Exception {\r
+ if(args.length < 2) {\r
+ usage();\r
+ return;\r
+ }\r
+\r
+ BufferedReader modelReader = new BufferedReader(new FileReader(args[1]));\r
+\r
+ String chartTitle = modelReader.readLine(); // first line is chart title\r
+\r
+ XMLSlideShow pptx = new XMLSlideShow(new FileInputStream(args[0]));\r
+ XSLFSlide slide = pptx.getSlides()[0];\r
+\r
+ // find chart in the slide\r
+ XSLFChart chart = null;\r
+ for(POIXMLDocumentPart part : slide.getRelations()){\r
+ if(part instanceof XSLFChart){\r
+ chart = (XSLFChart) part;\r
+ break;\r
+ }\r
+ }\r
+\r
+ if(chart == null) throw new IllegalStateException("chart not found in the template");\r
+\r
+ // embedded Excel workbook that holds the chart data\r
+ POIXMLDocumentPart xlsPart = chart.getRelations().get(0);\r
+ XSSFWorkbook wb = new XSSFWorkbook();\r
+ XSSFSheet sheet = wb.createSheet();\r
+\r
+ CTChart ctChart = chart.getCTChart();\r
+ CTPlotArea plotArea = ctChart.getPlotArea();\r
+\r
+ CTPieChart pieChart = plotArea.getPieChartArray(0);\r
+ //Pie Chart Series\r
+ CTPieSer ser = pieChart.getSerArray(0);\r
+\r
+ // Series Text\r
+ CTSerTx tx = ser.getTx();\r
+ tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle);\r
+ sheet.createRow(0).createCell(1).setCellValue(chartTitle);\r
+ String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString();\r
+ tx.getStrRef().setF(titleRef);\r
+\r
+\r
+ // Category Axis Data\r
+ CTAxDataSource cat = ser.getCat();\r
+ CTStrData strData = cat.getStrRef().getStrCache();\r
+\r
+ // Values\r
+ CTNumDataSource val = ser.getVal();\r
+ CTNumData numData = val.getNumRef().getNumCache();\r
+\r
+ strData.setPtArray(null); // unset old axis text\r
+ numData.setPtArray(null); // unset old values\r
+\r
+\r
+ // set model\r
+ int idx = 0;\r
+ int rownum = 1;\r
+ String ln;\r
+ while((ln = modelReader.readLine()) != null){\r
+ String[] vals = ln.split("\\s+");\r
+ CTNumVal numVal = numData.addNewPt();\r
+ numVal.setIdx(idx);\r
+ numVal.setV(vals[1]);\r
+\r
+ CTStrVal sVal = strData.addNewPt();\r
+ sVal.setIdx(idx);\r
+ sVal.setV(vals[0]);\r
+\r
+ idx++;\r
+ XSSFRow row = sheet.createRow(rownum++);\r
+ row.createCell(0).setCellValue(vals[0]);\r
+ row.createCell(1).setCellValue(Double.valueOf(vals[1]));\r
+ }\r
+ numData.getPtCount().setVal(idx);\r
+ strData.getPtCount().setVal(idx);\r
+\r
+ String numDataRange = new CellRangeAddress(1, rownum-1, 1, 1).formatAsString(sheet.getSheetName(), true);\r
+ val.getNumRef().setF(numDataRange);\r
+ String axisDataRange = new CellRangeAddress(1, rownum-1, 0, 0).formatAsString(sheet.getSheetName(), true);\r
+ cat.getStrRef().setF(axisDataRange);\r
+\r
+ // updated the embedded workbook with the data\r
+ OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream();\r
+ wb.write(xlsOut);\r
+ xlsOut.close();\r
+\r
+ // save the result\r
+ FileOutputStream out = new FileOutputStream("pie-chart-demo-output.pptx");\r
+ pptx.write(out);\r
+ out.close();\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+/**\r
+ * Demonstrates how to create slides with predefined layout\r
+ * and fill the placeholder shapes\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class Tutorial1 {\r
+\r
+ public static void main(String[] args) throws IOException{\r
+ XMLSlideShow ppt = new XMLSlideShow();\r
+\r
+ // XSLFSlide#createSlide() with no arguments creates a blank slide\r
+ XSLFSlide blankSlide = ppt.createSlide();\r
+\r
+ \r
+ XSLFSlideMaster master = ppt.getSlideMasters()[0];\r
+\r
+ XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);\r
+ XSLFSlide slide1 = ppt.createSlide(layout1) ;\r
+ XSLFTextShape[] ph1 = slide1.getPlaceholders();\r
+ XSLFTextShape titlePlaceholder1 = ph1[0];\r
+ titlePlaceholder1.setText("This is a title");\r
+ XSLFTextShape subtitlePlaceholder1 = ph1[1];\r
+ subtitlePlaceholder1.setText("this is a subtitle");\r
+\r
+ XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);\r
+ XSLFSlide slide2 = ppt.createSlide(layout2) ;\r
+ XSLFTextShape[] ph2 = slide2.getPlaceholders();\r
+ XSLFTextShape titlePlaceholder2 = ph2[0];\r
+ titlePlaceholder2.setText("This is a title");\r
+ XSLFTextShape bodyPlaceholder = ph2[1];\r
+ // we are going to add text by paragraphs. Clear the default placehoder text before that\r
+ bodyPlaceholder.clearText();\r
+ XSLFTextParagraph p1 = bodyPlaceholder.addNewTextParagraph();\r
+ p1.setLevel(0);\r
+ p1.addNewTextRun().setText("Level1 text");\r
+ XSLFTextParagraph p2 = bodyPlaceholder.addNewTextParagraph();\r
+ p2.setLevel(1);\r
+ p2.addNewTextRun().setText("Level2 text");\r
+ XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph();\r
+ p3.setLevel(3);\r
+ p3.addNewTextRun().setText("Level3 text");\r
+\r
+ FileOutputStream out = new FileOutputStream("slides.pptx");\r
+ ppt.write(out);\r
+ out.close();\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import java.awt.*;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+/**\r
+ * Basic paragraph and text formatting\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class Tutorial2 {\r
+\r
+ public static void main(String[] args) throws IOException{\r
+ XMLSlideShow ppt = new XMLSlideShow();\r
+\r
+ XSLFSlide slide1 = ppt.createSlide();\r
+ XSLFTextBox shape1 = slide1.createTextBox();\r
+ // initial height of the text box is 100 pt but\r
+ Rectangle anchor = new Rectangle(10, 100, 300, 100);\r
+ shape1.setAnchor(anchor);\r
+\r
+ XSLFTextParagraph p1 = shape1.addNewTextParagraph();\r
+ XSLFTextRun r1 = p1.addNewTextRun();\r
+ r1.setText("Paragraph Formatting");\r
+ r1.setFontSize(24);\r
+ r1.setFontColor(new Color(85, 142, 213));\r
+\r
+ XSLFTextParagraph p2 = shape1.addNewTextParagraph();\r
+ // If spaceBefore >= 0, then space is a percentage of normal line height.\r
+ // If spaceBefore < 0, the absolute value of linespacing is the spacing in points\r
+ p2.setSpaceBefore(-20); // 20 pt from the previous paragraph\r
+ p2.setSpaceAfter(300); // 3 lines after the paragraph\r
+ XSLFTextRun r2 = p2.addNewTextRun();\r
+ r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph.");\r
+ r2.setFontSize(16);\r
+\r
+ XSLFTextParagraph p3 = shape1.addNewTextParagraph();\r
+\r
+ XSLFTextRun r3 = p3.addNewTextRun();\r
+ r3.setText("Run Formatting");\r
+ r3.setFontSize(24);\r
+ r3.setFontColor(new Color(85, 142, 213));\r
+\r
+ XSLFTextParagraph p4 = shape1.addNewTextParagraph();\r
+ p4.setSpaceBefore(-20); // 20 pt from the previous paragraph\r
+ p4.setSpaceAfter(300); // 3 lines after the paragraph\r
+ XSLFTextRun r4 = p4.addNewTextRun();\r
+ r4.setFontSize(16);\r
+ r4.setText(\r
+ "Run level formatting is the most granular property level and allows " +\r
+ "for the specifying of all low level text properties. The text run is " +\r
+ "what all paragraphs are derived from and thus specifying various " +\r
+ "properties per run will allow for a diversely formatted text paragraph.");\r
+\r
+ // resize the shape to fit text\r
+ shape1.resizeToFitText();\r
+\r
+ FileOutputStream out = new FileOutputStream("text.pptx");\r
+ ppt.write(out);\r
+ out.close();\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import java.awt.*;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+/**\r
+ * How to set slide title\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class Tutorial3 {\r
+\r
+ public static void main(String[] args) throws IOException{\r
+ XMLSlideShow ppt = new XMLSlideShow();\r
+\r
+ XSLFSlide slide = ppt.createSlide();\r
+\r
+ XSLFTextShape titleShape = slide.createTextBox();\r
+ titleShape.setPlaceholder(Placeholder.TITLE);\r
+ titleShape.setText("This is a slide title");\r
+ titleShape.setAnchor(new Rectangle(50, 50, 400, 100));\r
+\r
+ FileOutputStream out = new FileOutputStream("title.pptx");\r
+ ppt.write(out);\r
+ out.close();\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import java.awt.*;\r
+import java.awt.geom.Rectangle2D;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+/**\r
+ * PPTX Tables\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class Tutorial4 {\r
+\r
+ public static void main(String[] args) throws IOException{\r
+ XMLSlideShow ppt = new XMLSlideShow();\r
+\r
+ // XSLFSlide#createSlide() with no arguments creates a blank slide\r
+ XSLFSlide slide = ppt.createSlide();\r
+\r
+ XSLFTable tbl = slide.createTable();\r
+ tbl.setAnchor(new Rectangle2D.Double(50, 50, 450, 300));\r
+\r
+ int numColumns = 3;\r
+ int numRows = 5;\r
+ XSLFTableRow headerRow = tbl.addRow();\r
+ headerRow.setHeight(50);\r
+ // header\r
+ for(int i = 0; i < numColumns; i++) {\r
+ XSLFTableCell th = headerRow.addCell();\r
+ XSLFTextParagraph p = th.addNewTextParagraph();\r
+ p.setTextAlign(TextAlign.CENTER);\r
+ XSLFTextRun r = p.addNewTextRun();\r
+ r.setText("Header " + (i+1));\r
+ r.setBold(true);\r
+ r.setFontColor(Color.white);\r
+ th.setFillColor(new Color(79, 129, 189));\r
+ th.setBorderBottom(2);\r
+ th.setBorderBottomColor(Color.white);\r
+\r
+ tbl.setColumnWidth(i, 150); // all columns are equally sized\r
+ }\r
+ \r
+ // rows\r
+ \r
+ for(int rownum = 0; rownum < numRows; rownum ++){\r
+ XSLFTableRow tr = tbl.addRow();\r
+ tr.setHeight(50);\r
+ // header\r
+ for(int i = 0; i < numColumns; i++) {\r
+ XSLFTableCell cell = tr.addCell();\r
+ XSLFTextParagraph p = cell.addNewTextParagraph();\r
+ XSLFTextRun r = p.addNewTextRun();\r
+\r
+ r.setText("Cell " + (i+1));\r
+ if(rownum % 2 == 0)\r
+ cell.setFillColor(new Color(208, 216, 232));\r
+ else\r
+ cell.setFillColor(new Color(233, 247, 244));\r
+\r
+ }\r
+ \r
+ }\r
+\r
+\r
+ FileOutputStream out = new FileOutputStream("table.pptx");\r
+ ppt.write(out);\r
+ out.close();\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import org.apache.poi.util.IOUtils;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+/**\r
+ * Images\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class Tutorial5 {\r
+\r
+ public static void main(String[] args) throws IOException{\r
+ XMLSlideShow ppt = new XMLSlideShow();\r
+\r
+ XSLFSlide slide = ppt.createSlide();\r
+ File img = new File(System.getProperty("POI.testdata.path"), "slideshow/clock.jpg");\r
+ byte[] data = IOUtils.toByteArray(new FileInputStream(img));\r
+ int pictureIndex = ppt.addPicture(data, XSLFPictureData.PICTURE_TYPE_PNG);\r
+\r
+ XSLFPictureShape shape = slide.createPicture(pictureIndex);\r
+\r
+ FileOutputStream out = new FileOutputStream("images.pptx");\r
+ ppt.write(out);\r
+ out.close();\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import java.awt.*;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+/**\r
+ * Hyperlinks\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class Tutorial6 {\r
+\r
+ public static void main(String[] args) throws IOException{\r
+ XMLSlideShow ppt = new XMLSlideShow();\r
+\r
+ XSLFSlide slide1 = ppt.createSlide();\r
+ XSLFSlide slide2 = ppt.createSlide();\r
+\r
+ XSLFTextBox shape1 = slide1.createTextBox();\r
+ shape1.setAnchor(new Rectangle(50, 50, 200, 50));\r
+ XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun();\r
+ XSLFHyperlink link1 = r1.createHyperlink();\r
+ r1.setText("http://poi.apache.org"); // visible text\r
+ link1.setAddress("http://poi.apache.org"); // link address\r
+\r
+ XSLFTextBox shape2 = slide1.createTextBox();\r
+ shape2.setAnchor(new Rectangle(300, 50, 200, 50));\r
+ XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun();\r
+ XSLFHyperlink link2 = r2.createHyperlink();\r
+ r2.setText("Go to the second slide"); // visible text\r
+ link2.setAddress(slide2); // link address\r
+\r
+\r
+\r
+ FileOutputStream out = new FileOutputStream("hyperlinks.pptx");\r
+ ppt.write(out);\r
+ out.close();\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ==================================================================== \r
+ */\r
+\r
+package org.apache.poi.xslf.usermodel;\r
+\r
+import java.awt.*;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+/**\r
+ * Bullets and numbering\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class Tutorial7 {\r
+\r
+ public static void main(String[] args) throws IOException{\r
+ XMLSlideShow ppt = new XMLSlideShow();\r
+\r
+ XSLFSlide slide = ppt.createSlide();\r
+ XSLFTextBox shape = slide.createTextBox();\r
+ shape.setAnchor(new Rectangle(50, 50, 400, 200));\r
+\r
+ XSLFTextParagraph p1 = shape.addNewTextParagraph();\r
+ p1.setLevel(0);\r
+ p1.setBullet(true);\r
+ XSLFTextRun r1 = p1.addNewTextRun();\r
+ r1.setText("Bullet1");\r
+\r
+ XSLFTextParagraph p2 = shape.addNewTextParagraph();\r
+ // indentation before text\r
+ p2.setLeftMargin(60);\r
+ // the bullet is set 40 pt before the text\r
+ p2.setIndent(-40);\r
+ p2.setBullet(true);\r
+ // customize bullets\r
+ p2.setBulletFontColor(Color.red);\r
+ p2.setBulletFont("Wingdings");\r
+ p2.setBulletCharacter("\u0075");\r
+ p2.setLevel(1);\r
+ XSLFTextRun r2 = p2.addNewTextRun();\r
+ r2.setText("Bullet2");\r
+\r
+ // the next three paragraphs form an auto-numbered list\r
+ XSLFTextParagraph p3 = shape.addNewTextParagraph();\r
+ p3.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 1);\r
+ p3.setLevel(2);\r
+ XSLFTextRun r3 = p3.addNewTextRun();\r
+ r3.setText("Numbered List Item - 1");\r
+\r
+ XSLFTextParagraph p4 = shape.addNewTextParagraph();\r
+ p4.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 2);\r
+ p4.setLevel(2);\r
+ XSLFTextRun r4 = p4.addNewTextRun();\r
+ r4.setText("Numbered List Item - 2");\r
+\r
+ XSLFTextParagraph p5 = shape.addNewTextParagraph();\r
+ p5.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 3);\r
+ p5.setLevel(2);\r
+ XSLFTextRun r5 = p5.addNewTextRun();\r
+ r5.setText("Numbered List Item - 3");\r
+\r
+ shape.resizeToFitText();\r
+\r
+ FileOutputStream out = new FileOutputStream("list.pptx");\r
+ ppt.write(out);\r
+ out.close();\r
+ }\r
+}\r
--- /dev/null
+My Chart\r
+First 1.0\r
+Second 3.0\r
+Third 4.0
\ No newline at end of file
--- /dev/null
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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());
+ }
+ }
+ }
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.
+ * <p/>
+ * 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.
+ * <p/>
+ * 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
+ * <p/>
+ * Also see Standard ECMA-376, 1st edition, part 4, pages 1928ff, at
+ * http://www.ecma-international.org/publications/standards/Ecma-376.htm
+ * <p/>
+ * 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 <xlsx file> [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();
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<InputStream> 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]);
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF 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
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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
+ *
+ * <p>
+ * 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.
+ * </p>
+ * See <a "http://poi.apache.org/spreadsheet/how-to.html#sxssf">
+ * http://poi.apache.org/spreadsheet/how-to.html#sxssf</a>.
+
+ *
+ * @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<String, XSSFCellStyle> 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<String, XSSFCellStyle> createStyles(XSSFWorkbook wb){
+ Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();
+ 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<String, XSSFCellStyle> 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<ZipEntry> en = (Enumeration<ZipEntry>) 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("<?xml version=\"1.0\" encoding=\""+XML_ENCODING+"\"?>" +
+ "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" );
+ _out.write("<sheetData>\n");
+ }
+
+ public void endSheet() throws IOException {
+ _out.write("</sheetData>");
+ _out.write("</worksheet>");
+ }
+
+ /**
+ * Insert a new row
+ *
+ * @param rownum 0-based row number
+ */
+ public void insertRow(int rownum) throws IOException {
+ _out.write("<row r=\""+(rownum+1)+"\">\n");
+ this._rownum = rownum;
+ }
+
+ /**
+ * Insert row end marker
+ */
+ public void endRow() throws IOException {
+ _out.write("</row>\n");
+ }
+
+ public void createCell(int columnIndex, String value, int styleIndex) throws IOException {
+ String ref = new CellReference(_rownum, columnIndex).formatAsString();
+ _out.write("<c r=\""+ref+"\" t=\"inlineStr\"");
+ if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
+ _out.write(">");
+ _out.write("<is><t>"+value+"</t></is>");
+ _out.write("</c>");
+ }
+
+ 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("<c r=\""+ref+"\" t=\"n\"");
+ if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
+ _out.write(">");
+ _out.write("<v>"+value+"</v>");
+ _out.write("</c>");
+ }
+
+ 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);
+ }
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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.
+ *
+ * <pre>
+ * Usage:
+ * CalendarDemo <year>
+ * </pre>
+ *
+ * @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<String, XSSFCellStyle> 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<String, XSSFCellStyle> createStyles(XSSFWorkbook wb){
+ Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();
+
+ 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;
+ }
+}
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.xssf.usermodel.examples;\r
+\r
+import org.apache.poi.ss.usermodel.*;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+\r
+import java.io.IOException;\r
+import java.io.FileOutputStream;\r
+\r
+/**\r
+ * Demonstrates how to work with excel cell comments.\r
+ *\r
+ * <p>\r
+ * Excel comment is a kind of a text shape,\r
+ * so inserting a comment is very similar to placing a text box in a worksheet\r
+ * </p>\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class CellComments {\r
+ public static void main(String[] args) throws IOException {\r
+ Workbook wb = new XSSFWorkbook();\r
+\r
+ CreationHelper factory = wb.getCreationHelper();\r
+\r
+ Sheet sheet = wb.createSheet();\r
+\r
+ Cell cell1 = sheet.createRow(3).createCell(5);\r
+ cell1.setCellValue("F4");\r
+\r
+ Drawing drawing = sheet.createDrawingPatriarch();\r
+\r
+ ClientAnchor anchor = factory.createClientAnchor();\r
+\r
+ Comment comment1 = drawing.createCellComment(anchor);\r
+ RichTextString str1 = factory.createRichTextString("Hello, World!");\r
+ comment1.setString(str1);\r
+ comment1.setAuthor("Apache POI");\r
+ cell1.setCellComment(comment1);\r
+\r
+ Cell cell2 = sheet.createRow(2).createCell(2);\r
+ cell2.setCellValue("C3");\r
+\r
+ Comment comment2 = drawing.createCellComment(anchor);\r
+ RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");\r
+ //apply custom font to the text in the comment\r
+ Font font = wb.createFont();\r
+ font.setFontName("Arial");\r
+ font.setFontHeightInPoints((short)14);\r
+ font.setBoldweight(Font.BOLDWEIGHT_BOLD);\r
+ font.setColor(IndexedColors.RED.getIndex());\r
+ str2.applyFont(font);\r
+\r
+ comment2.setString(str2);\r
+ comment2.setAuthor("Apache POI");\r
+ comment2.setColumn(2);\r
+ comment2.setRow(2);\r
+\r
+ String fname = "comments.xlsx";\r
+ FileOutputStream out = new FileOutputStream(fname);\r
+ wb.write(out);\r
+ out.close();\r
+\r
+ }\r
+}\r
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+
+}
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.xssf.usermodel.examples;\r
+\r
+import org.apache.poi.openxml4j.opc.OPCPackage;\r
+import org.apache.poi.xssf.extractor.XSSFExportToXml;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+import org.apache.poi.xssf.usermodel.XSSFMap;\r
+\r
+import java.io.ByteArrayOutputStream;\r
+\r
+/**\r
+ * Print all custom XML mappings registered in the given workbook\r
+ */\r
+public class CustomXMLMapping {\r
+\r
+ public static void main(String[] args) throws Exception {\r
+ OPCPackage pkg = OPCPackage.open(args[0]);\r
+ XSSFWorkbook wb = new XSSFWorkbook(pkg);\r
+\r
+ for (XSSFMap map : wb.getCustomXMLMappings()) {\r
+ XSSFExportToXml exporter = new XSSFExportToXml(map);\r
+\r
+ ByteArrayOutputStream os = new ByteArrayOutputStream();\r
+ exporter.exportToXML(os, true);\r
+ String xml = os.toString("UTF-8");\r
+ System.out.println(xml);\r
+ }\r
+ pkg.close();\r
+ }\r
+}\r
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.xssf.usermodel.examples;\r
+\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+import org.apache.poi.openxml4j.opc.OPCPackage;\r
+import org.apache.poi.openxml4j.opc.PackagePart;\r
+import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
+import org.apache.poi.hslf.HSLFSlideShow;\r
+import org.apache.poi.hwpf.HWPFDocument;\r
+import org.apache.poi.xslf.XSLFSlideShow;\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+\r
+import java.io.InputStream;\r
+\r
+/**\r
+ * Demonstrates how you can extract embedded data from a .xlsx file\r
+ */\r
+public class EmbeddedObjects {\r
+ public static void main(String[] args) throws Exception {\r
+ OPCPackage pkg = OPCPackage.open(args[0]);\r
+ XSSFWorkbook workbook = new XSSFWorkbook(pkg);\r
+ for (PackagePart pPart : workbook.getAllEmbedds()) {\r
+ String contentType = pPart.getContentType();\r
+ // Excel Workbook - either binary or OpenXML\r
+ if (contentType.equals("application/vnd.ms-excel")) {\r
+ HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());\r
+ }\r
+ // Excel Workbook - OpenXML file format\r
+ else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {\r
+ XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());\r
+ }\r
+ // Word Document - binary (OLE2CDF) file format\r
+ else if (contentType.equals("application/msword")) {\r
+ HWPFDocument document = new HWPFDocument(pPart.getInputStream());\r
+ }\r
+ // Word Document - OpenXML file format\r
+ else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {\r
+ XWPFDocument document = new XWPFDocument(pPart.getInputStream());\r
+ }\r
+ // PowerPoint Document - binary file format\r
+ else if (contentType.equals("application/vnd.ms-powerpoint")) {\r
+ HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream());\r
+ }\r
+ // PowerPoint Document - OpenXML file format\r
+ else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {\r
+ OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());\r
+ XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);\r
+ }\r
+ // Any other type of embedded object.\r
+ else {\r
+ System.out.println("Unknown Embedded Document: " + contentType);\r
+ InputStream inputStream = pPart.getInputStream();\r
+ }\r
+ }\r
+ pkg.close();\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();\r
+\r
+ //cell style for hyperlinks\r
+ //by default hyperlinks are blue and underlined\r
+ CellStyle hlink_style = wb.createCellStyle();\r
+ Font hlink_font = wb.createFont();\r
+ hlink_font.setUnderline(Font.U_SINGLE);\r
+ 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();
+
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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());
+ }
+ }
+ }
+ }
+}
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.xssf.usermodel.examples;\r
+\r
+import org.apache.poi.ss.usermodel.*;\r
+import org.apache.poi.ss.usermodel.charts.*;\r
+import org.apache.poi.ss.util.CellRangeAddress;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+\r
+import java.io.FileOutputStream;\r
+\r
+/**\r
+ * Line chart example.\r
+ *\r
+ * @author Martin Andersson\r
+ */\r
+public class LineChart {\r
+\r
+ public static void main(String[] args) throws Exception {\r
+ Workbook wb = new XSSFWorkbook();\r
+ Sheet sheet = wb.createSheet("linechart");\r
+ final int NUM_OF_ROWS = 3;\r
+ final int NUM_OF_COLUMNS = 10;\r
+\r
+ // Create a row and put some cells in it. Rows are 0 based.\r
+ Row row;\r
+ Cell cell;\r
+ for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {\r
+ row = sheet.createRow((short) rowIndex);\r
+ for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {\r
+ cell = row.createCell((short) colIndex);\r
+ cell.setCellValue(colIndex * (rowIndex + 1));\r
+ }\r
+ }\r
+\r
+ Drawing drawing = sheet.createDrawingPatriarch();\r
+ ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);\r
+\r
+ Chart chart = drawing.createChart(anchor);\r
+ ChartLegend legend = chart.getOrCreateLegend();\r
+ legend.setPosition(LegendPosition.TOP_RIGHT);\r
+\r
+ LineChartData data = chart.getChartDataFactory().createLineChartData();\r
+\r
+ // Use a category axis for the bottom axis.\r
+ ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);\r
+ ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);\r
+ leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);\r
+\r
+ ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));\r
+ ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));\r
+ ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));\r
+\r
+\r
+ data.addSerie(xs, ys1);\r
+ data.addSerie(xs, ys2);\r
+\r
+ chart.plot(data, bottomAxis, leftAxis);\r
+\r
+ // Write the output to a file\r
+ FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx");\r
+ wb.write(fileOut);\r
+ fileOut.close();\r
+ }\r
+}\r
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
+ ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
+ ChartDataSource<Number> 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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();
+
+ }
+}
--- /dev/null
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF 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();
+ }
+
+
+}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF 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<XWPFTableRow> 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<XWPFTableCell> 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();
+ }
+
+}
--- /dev/null
+/*\r
+ * ====================================================================\r
+ * Licensed to the Apache Software Foundation (ASF) under one or more\r
+ * contributor license agreements. See the NOTICE file distributed with\r
+ * this work for additional information regarding copyright ownership.\r
+ * The ASF licenses this file to You under the Apache License, Version 2.0\r
+ * (the "License"); you may not use this file except in compliance with\r
+ * the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ====================================================================\r
+ */\r
+\r
+package org.apache.poi.xwpf.usermodel;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileOutputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.util.List;\r
+import java.util.Iterator;\r
+\r
+import junit.framework.Assert;\r
+import org.apache.poi.openxml4j.opc.PackagePart;\r
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
+import org.apache.poi.ss.usermodel.WorkbookFactory;\r
+import org.apache.poi.ss.usermodel.Workbook;\r
+import org.apache.poi.ss.usermodel.Sheet;\r
+import org.apache.poi.ss.usermodel.Row;\r
+import org.apache.poi.ss.usermodel.Cell;\r
+\r
+/**\r
+ * Tests whether it is possible to successfully update an Excel workbook that is\r
+ * embedded into a WordprocessingML document. Note that the test has currently\r
+ * only been conducted with a binary Excel workbook and NOT yet with a\r
+ * SpreadsheetML workbook embedded into the document.\r
+ *\r
+ * <p>\r
+ * This code was successfully tested with the following file from the POI test collection:\r
+ * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx\r
+ * </p>\r
+ *\r
+ * @author Mark B\r
+ */\r
+public class UpdateEmbeddedDoc {\r
+\r
+ private XWPFDocument doc = null;\r
+ private File docFile = null;\r
+\r
+ private static final int SHEET_NUM = 0;\r
+ private static final int ROW_NUM = 0;\r
+ private static final int CELL_NUM = 0;\r
+ private static final double NEW_VALUE = 100.98D;\r
+ private static final String BINARY_EXTENSION = "xls";\r
+ private static final String OPENXML_EXTENSION = "xlsx";\r
+\r
+ /**\r
+ * Create a new instance of the UpdateEmbeddedDoc class using the following\r
+ * parameters;\r
+ *\r
+ * @param filename An instance of the String class that encapsulates the name\r
+ * of and path to a WordprocessingML Word document that contains an\r
+ * embedded binary Excel workbook.\r
+ * @throws java.io.FileNotFoundException Thrown if the file cannot be found\r
+ * on the underlying file system.\r
+ * @throws java.io.IOException Thrown if a problem occurs in the underlying\r
+ * file system.\r
+ */\r
+ public UpdateEmbeddedDoc(String filename) throws FileNotFoundException, IOException {\r
+ this.docFile = new File(filename);\r
+ FileInputStream fis = null;\r
+ if (!this.docFile.exists()) {\r
+ throw new FileNotFoundException("The Word dcoument " +\r
+ filename +\r
+ " does not exist.");\r
+ }\r
+ try {\r
+\r
+ // Open the Word document file and instantiate the XWPFDocument\r
+ // class.\r
+ fis = new FileInputStream(this.docFile);\r
+ this.doc = new XWPFDocument(fis);\r
+ } finally {\r
+ if (fis != null) {\r
+ try {\r
+ fis.close();\r
+ fis = null;\r
+ } catch (IOException ioEx) {\r
+ System.out.println("IOException caught trying to close " +\r
+ "FileInputStream in the constructor of " +\r
+ "UpdateEmbeddedDoc.");\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Called to update the embedded Excel workbook. As the format and structire\r
+ * of the workbook are known in advance, all this code attempts to do is\r
+ * write a new value into the first cell on the first row of the first\r
+ * worksheet. Prior to executing this method, that cell will contain the\r
+ * value 1.\r
+ *\r
+ * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException\r
+ * Rather\r
+ * than use the specific classes (HSSF/XSSF) to handle the embedded\r
+ * workbook this method uses those defeined in the SS stream. As\r
+ * a result, it might be the case that a SpreadsheetML file is\r
+ * opened for processing, throwing this exception if that file is\r
+ * invalid.\r
+ * @throws java.io.IOException Thrown if a problem occurs in the underlying\r
+ * file system.\r
+ */\r
+ public void updateEmbeddedDoc() throws OpenXML4JException, IOException {\r
+ Workbook workbook = null;\r
+ Sheet sheet = null;\r
+ Row row = null;\r
+ Cell cell = null;\r
+ PackagePart pPart = null;\r
+ Iterator<PackagePart> pIter = null;\r
+ List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();\r
+ if (embeddedDocs != null && !embeddedDocs.isEmpty()) {\r
+ pIter = embeddedDocs.iterator();\r
+ while (pIter.hasNext()) {\r
+ pPart = pIter.next();\r
+ if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||\r
+ pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {\r
+\r
+ // Get an InputStream from the pacage part and pass that\r
+ // to the create method of the WorkbookFactory class. Update\r
+ // the resulting Workbook and then stream that out again\r
+ // using an OutputStream obtained from the same PackagePart.\r
+ workbook = WorkbookFactory.create(pPart.getInputStream());\r
+ sheet = workbook.getSheetAt(SHEET_NUM);\r
+ row = sheet.getRow(ROW_NUM);\r
+ cell = row.getCell(CELL_NUM);\r
+ cell.setCellValue(NEW_VALUE);\r
+ workbook.write(pPart.getOutputStream());\r
+ }\r
+ }\r
+\r
+ // Finally, write the newly modified Word document out to file.\r
+ this.doc.write(new FileOutputStream(this.docFile));\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Called to test whether or not the embedded workbook was correctly\r
+ * updated. This method simply recovers the first cell from the first row\r
+ * of the first workbook and tests the value it contains.\r
+ * <p/>\r
+ * Note that execution will not continue up to the assertion as the\r
+ * embedded workbook is now corrupted and causes an IllegalArgumentException\r
+ * with the following message\r
+ * <p/>\r
+ * <em>java.lang.IllegalArgumentException: Your InputStream was neither an\r
+ * OLE2 stream, nor an OOXML stream</em>\r
+ * <p/>\r
+ * to be thrown when the WorkbookFactory.createWorkbook(InputStream) method\r
+ * is executed.\r
+ *\r
+ * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException\r
+ * Rather\r
+ * than use the specific classes (HSSF/XSSF) to handle the embedded\r
+ * workbook this method uses those defeined in the SS stream. As\r
+ * a result, it might be the case that a SpreadsheetML file is\r
+ * opened for processing, throwing this exception if that file is\r
+ * invalid.\r
+ * @throws java.io.IOException Thrown if a problem occurs in the underlying\r
+ * file system.\r
+ */\r
+ public void checkUpdatedDoc() throws OpenXML4JException, IOException {\r
+ Workbook workbook = null;\r
+ Sheet sheet = null;\r
+ Row row = null;\r
+ Cell cell = null;\r
+ PackagePart pPart = null;\r
+ Iterator<PackagePart> pIter = null;\r
+ List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();\r
+ if (embeddedDocs != null && !embeddedDocs.isEmpty()) {\r
+ pIter = embeddedDocs.iterator();\r
+ while (pIter.hasNext()) {\r
+ pPart = pIter.next();\r
+ if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||\r
+ pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {\r
+ workbook = WorkbookFactory.create(pPart.getInputStream());\r
+ sheet = workbook.getSheetAt(SHEET_NUM);\r
+ row = sheet.getRow(ROW_NUM);\r
+ cell = row.getCell(CELL_NUM);\r
+ Assert.assertEquals(cell.getNumericCellValue(), NEW_VALUE);\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Code to test updating of the embedded Excel workbook.\r
+ *\r
+ * @param args\r
+ */\r
+ public static void main(String[] args) {\r
+ try {\r
+ UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]);\r
+ ued.updateEmbeddedDoc();\r
+ ued.checkUpdatedDoc();\r
+ } catch (Exception ex) {\r
+ System.out.println(ex.getClass().getName());\r
+ System.out.println(ex.getMessage());\r
+ ex.printStackTrace(System.out);\r
+ }\r
+ }\r
+}\r
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>This class copies a POI file system to a new file and compares the copy
- * with the original.</p>
- *
- * <p>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.</p>
- *
- * <p>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.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class CopyCompare
-{
- /**
- * <p>Runs the example program. The application expects one or two
- * arguments:</p>
- *
- * <ol>
- *
- * <li><p>The first argument is the disk file name of the POI filesystem to
- * copy.</p></li>
- *
- * <li><p>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.</p></li>
- *
- * </ol>
- *
- * @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());
- }
-
-
-
- /**
- * <p>Compares two {@link DirectoryEntry} instances of a POI file system.
- * The directories must contain the same streams with the same names and
- * contents.</p>
- *
- * @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 <code>true</code> if the directories are equal, else
- * <code>false</code>.
- * @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;
- }
-
-
-
- /**
- * <p>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.</p>
- *
- * @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 <code>true</code> if the documents are equal, else
- * <code>false</code>.
- * @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;
- }
-
-
-
- /**
- * <p>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.</p>
- */
- static class CopyFile implements POIFSReaderListener
- {
- String dstName;
- OutputStream out;
- POIFSFileSystem poiFs;
-
-
- /**
- * <p>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.</p>
- *
- * @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();
- }
-
-
- /**
- * <p>The method is called by POI's eventing API for each file in the
- * origin POIFS.</p>
- */
- 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));
- }
- }
-
-
-
- /**
- * <p>Writes a {@link PropertySet} to a POI filesystem.</p>
- *
- * @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());
- }
-
-
-
- /**
- * <p>Copies the bytes from a {@link DocumentInputStream} to a new
- * stream in a POI filesystem.</p>
- *
- * @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);
- }
-
-
- /**
- * <p>Writes the POI file system to a disk file.</p>
- *
- * @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();
-
-
-
- /**
- * <p>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.</p>
- *
- * <p>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.</p>
- *
- * @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);
- }
- }
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>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:</p>
- *
- * <ul>
- *
- * <li><p>Open the POI filesystem.</p></li>
- *
- * <li><p>Read the summary information.</p></li>
- *
- * <li><p>Read and print the "author" property.</p></li>
- *
- * <li><p>Change the author to "Rainer Klute".</p></li>
- *
- * <li><p>Read the document summary information.</p></li>
- *
- * <li><p>Read and print the "category" property.</p></li>
- *
- * <li><p>Change the category to "POI example".</p></li>
- *
- * <li><p>Read the custom properties (if available).</p></li>
- *
- * <li><p>Insert a new custom property.</p></li>
- *
- * <li><p>Write the custom properties back to the document summary
- * information.</p></li>
- *
- * <li><p>Write the summary information to the POI filesystem.</p></li>
- *
- * <li><p>Write the document summary information to the POI filesystem.</p></li>
- *
- * <li><p>Write the POI filesystem back to the original file.</p></li>
- *
- * </ol>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de">klute@rainer-klute.de</a>
- */
-public class ModifyDocumentSummaryInformation {
-
- /**
- * <p>Main method - see class description.</p>
- *
- * @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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>Sample application showing how to read a document's custom property set.
- * Call it with the document's file name as command-line parameter.</p>
- *
- * <p>Explanations can be found in the HPSF HOW-TO.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class ReadCustomPropertySets
-{
-
- /**
- * <p>Runs the example program.</p>
- *
- * @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);
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>Sample application showing how to read a OLE 2 document's
- * title. Call it with the document's file name as command line
- * parameter.</p>
- *
- * <p>Explanations can be found in the HPSF HOW-TO.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class ReadTitle
-{
- /**
- * <p>Runs the example program.</p>
- *
- * @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.");
- }
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>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:</p>
- *
- * <ul>
- *
- * <li><p>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.</p></li>
- *
- * <li><p>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.</p></li>
- *
- * </ul>
- *
- * <p>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.</p>
- *
- * <p>Further explanations can be found in the HPSF HOW-TO.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class WriteAuthorAndTitle
-{
- /**
- * <p>Runs the example program.</p>
- *
- * @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();
- }
-
-
-
- /**
- * <p>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.</p>
- */
- static class ModifySICopyTheRest implements POIFSReaderListener
- {
- String dstName;
- OutputStream out;
- POIFSFileSystem poiFs;
-
-
- /**
- * <p>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.</p>
- *
- * @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();
- }
-
-
- /**
- * <p>The method is called by POI's eventing API for each file in the
- * origin POIFS.</p>
- */
- 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));
- }
- }
-
-
- /**
- * <p>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.</p>
- *
- * @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);
- }
-
-
- /**
- * <p>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.</p>
- *
- * @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());
- }
-
-
-
- /**
- * <p>Copies the bytes from a {@link DocumentInputStream} to a new
- * stream in a POI filesystem.</p>
- *
- * @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);
- }
-
-
- /**
- * <p>Writes the POI file system to a disk file.</p>
- *
- * @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();
-
-
-
- /**
- * <p>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.</p>
- *
- * <p>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.</p>
- *
- * @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);
- }
- }
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>This class is a simple sample application showing how to create a property
- * set and write it to disk.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class WriteTitle
-{
- /**
- * <p>Runs the example program.</p>
- *
- * @param args Command-line arguments. The first and only command-line
- * argument is the name of the POI file system to create.
- * @throws 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));
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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);
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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");
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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);
- }
- }
- }
-
- }
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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 <scale> -slide <num>] ppt");
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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);
- }
- }
- }
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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 <xls file> [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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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);
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.
- *
- * <p>
- * Excel comment is a kind of a text shape,
- * so inserting a comment is very similar to placing a text box in a worksheet
- * </p>
- *
- * @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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.hssf.usermodel.examples;\r
-\r
-import org.apache.poi.hssf.usermodel.*;\r
-import org.apache.poi.poifs.filesystem.DirectoryNode;\r
-import org.apache.poi.poifs.filesystem.Entry;\r
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;\r
-import org.apache.poi.hwpf.HWPFDocument;\r
-import org.apache.poi.hslf.HSLFSlideShow;\r
-import org.apache.poi.hslf.usermodel.SlideShow;\r
-\r
-import java.io.FileInputStream;\r
-import java.util.Iterator;\r
-\r
-/**\r
- * Demonstrates how you can extract embedded data from a .xls file\r
- */\r
-public class EmeddedObjects {\r
- public static void main(String[] args) throws Exception {\r
- POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));\r
- HSSFWorkbook workbook = new HSSFWorkbook(fs);\r
- for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {\r
- //the OLE2 Class Name of the object\r
- String oleName = obj.getOLE2ClassName();\r
- if (oleName.equals("Worksheet")) {\r
- DirectoryNode dn = (DirectoryNode) obj.getDirectory();\r
- HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, fs, false);\r
- //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets());\r
- } else if (oleName.equals("Document")) {\r
- DirectoryNode dn = (DirectoryNode) obj.getDirectory();\r
- HWPFDocument embeddedWordDocument = new HWPFDocument(dn);\r
- //System.out.println(entry.getName() + ": " + embeddedWordDocument.getRange().text());\r
- } else if (oleName.equals("Presentation")) {\r
- DirectoryNode dn = (DirectoryNode) obj.getDirectory();\r
- SlideShow embeddedPowerPointDocument = new SlideShow(new HSLFSlideShow(dn));\r
- //System.out.println(entry.getName() + ": " + embeddedPowerPointDocument.getSlides().length);\r
- } else {\r
- if(obj.hasDirectoryEntry()){\r
- // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is\r
- DirectoryNode dn = (DirectoryNode) obj.getDirectory();\r
- for (Iterator entries = dn.getEntries(); entries.hasNext();) {\r
- Entry entry = (Entry) entries.next();\r
- //System.out.println(oleName + "." + entry.getName());\r
- }\r
- } else {\r
- // There is no DirectoryEntry\r
- // Recover the object's data from the HSSFObjectData instance.\r
- byte[] objectData = obj.getObjectData();\r
- }\r
- }\r
- }\r
- }\r
-}\r
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.");
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.<br/>
- *
- * 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)}.<br/>
- *
- * 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.<br/>
- *
- * 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();
- }
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
-==================================================================== */\r
-\r
-\r
-package org.apache.poi.hssf.usermodel.examples;\r
-\r
-import java.io.File;\r
-import java.io.FileOutputStream;\r
-import java.io.FileNotFoundException;\r
-import java.io.IOException;\r
-import java.util.ArrayList;\r
-\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
-import org.apache.poi.hssf.usermodel.HSSFSheet;\r
-import org.apache.poi.hssf.usermodel.HSSFRow;\r
-import org.apache.poi.hssf.usermodel.HSSFCell;\r
-import org.apache.poi.hssf.usermodel.HSSFCellStyle;\r
-import org.apache.poi.hssf.usermodel.HSSFDataFormat;\r
-import org.apache.poi.hssf.usermodel.HSSFRichTextString;\r
-\r
-/**\r
- * This class contains code that demonstrates how to insert plain, numbered\r
- * and bulleted lists into an Excel spreadsheet cell.\r
- *\r
- * Look at the code contained in the demonstrateMethodCalls() method. It calls\r
- * other methods that create plain, numbered and bulleted single and\r
- * multi-level lists. The demonstrateMethodCalls() method appears at the top\r
- * of the class definition.\r
- *\r
- * Though different methods are provided to construct single and multi-level\r
- * plain, numbered and bulleted lists, close examination will reveal that they\r
- * are not strictly necessary. If the inputs to the listInCell() and\r
- * multilLevelListInCell() methods are constructed to include the bullet\r
- * character or the item numbers then these methods alone may be sufficient.\r
- *\r
- * @author Mark Beardsley [msb at apache.org]\r
- */\r
-public class InCellLists {\r
-\r
- // This character looks like a solid, black, loser case letter 'o'\r
- // positioned up from the base line of the text.\r
- private static final char BULLET_CHARACTER = '\u2022';\r
-\r
- // The tab character - \t - cannot be used to create a tab space\r
- // within a cell as it is rendered as a square. Therefore, four\r
- // spaces are used to simulate that character.\r
- private static final String TAB = " ";\r
-\r
- /**\r
- * Call each of the list creation methods.\r
- *\r
- * @param outputFilename A String that encapsulates the name of and path to\r
- * the Excel spreadsheet file this code will create.\r
- */\r
- public void demonstrateMethodCalls(String outputFilename) {\r
- HSSFWorkbook workbook = null;\r
- HSSFSheet sheet = null;\r
- HSSFRow row = null;\r
- HSSFCell cell = null;\r
- File outputFile = null;\r
- FileOutputStream fos = null;\r
- ArrayList<MultiLevelListItem> multiLevelListItems = null;\r
- ArrayList<String> listItems = null;\r
- String listItem = null;\r
- try {\r
- workbook = new HSSFWorkbook();\r
- sheet = workbook.createSheet("In Cell Lists");\r
- row = sheet.createRow(0);\r
-\r
- // Create a cell at A1 and insert a single, bulleted, item into\r
- // that cell.\r
- cell = row.createCell(0);\r
- this.bulletedItemInCell(workbook, "List Item", cell);\r
-\r
- // Create a cell at A2 and insert a plain list - that is one\r
- // whose items are neither bulleted or numbered - into that cell.\r
- row = sheet.createRow(1);\r
- cell = row.createCell(0);\r
- listItems = new ArrayList<String>();\r
- listItems.add("List Item One.");\r
- listItems.add("List Item Two.");\r
- listItems.add("List Item Three.");\r
- listItems.add("List Item Four.");\r
- this.listInCell(workbook, listItems, cell);\r
- // The row height and cell width are set here to ensure that the\r
- // list may be seen.\r
- row.setHeight((short)1100);\r
- sheet.setColumnWidth(0, 9500);\r
-\r
- // Create a cell at A3 and insert a numbered list into that cell.\r
- // Note that a couple of items have been added to the listItems\r
- // ArrayList\r
- row = sheet.createRow(2);\r
- cell = row.createCell(0);\r
- listItems.add("List Item Five.");\r
- listItems.add("List Item Six.");\r
- this.numberedListInCell(workbook, listItems, cell, 1, 2);\r
- row.setHeight((short)1550);\r
-\r
- // Create a cell at A4 and insert a numbered list into that cell.\r
- // Note that a couple of items have been added to the listItems\r
- // ArrayList\r
- row = sheet.createRow(3);\r
- cell = row.createCell(0);\r
- listItems.add("List Item Seven.");\r
- listItems.add("List Item Eight.");\r
- listItems.add("List Item Nine.");\r
- listItems.add("List Item Ten.");\r
- this.bulletedListInCell(workbook, listItems, cell);\r
- row.setHeight((short)2550);\r
-\r
- // Insert a plain, multi-level list into cell A5. Note that\r
- // the major difference here is that the list items are passed as\r
- // an ArrayList of MultiLevelListItems. Note that an ArrayList\r
- // of instances of an inner class was used here in preference to\r
- // a Hashtable or HashMap as the ArrayList will preserve the\r
- // ordering of the items added to it; the first item added will\r
- // be the first item recovered and the last item added, the last\r
- // item recovered.\r
- row = sheet.createRow(4);\r
- cell = row.createCell(0);\r
- multiLevelListItems = new ArrayList<MultiLevelListItem>();\r
- listItems = new ArrayList<String>();\r
- listItems.add("ML List Item One - Sub Item One.");\r
- listItems.add("ML List Item One - Sub Item Two.");\r
- listItems.add("ML List Item One - Sub Item Three.");\r
- listItems.add("ML List Item One - Sub Item Four.");\r
- multiLevelListItems.add(new MultiLevelListItem("List Item One.", listItems));\r
- // Passing either null or an empty ArrayList will signal that\r
- // there are no lower level items associated with the top level\r
- // item\r
- multiLevelListItems.add(new MultiLevelListItem("List Item Two.", null));\r
- multiLevelListItems.add(new MultiLevelListItem("List Item Three.", null));\r
- listItems = new ArrayList<String>();\r
- listItems.add("ML List Item Four - Sub Item One.");\r
- listItems.add("ML List Item Four - Sub Item Two.");\r
- listItems.add("ML List Item Four - Sub Item Three.");\r
- multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems));\r
- this.multiLevelListInCell(workbook, multiLevelListItems, cell);\r
- row.setHeight((short)2800);\r
-\r
- // Insert a numbered multi-level list into cell A6. Note that the\r
- // same ArrayList as constructed for the above plain multi-level\r
- // list example will be re-used\r
- row = sheet.createRow(5);\r
- cell = row.createCell(0);\r
- this.multiLevelNumberedListInCell(workbook, multiLevelListItems,\r
- cell, 1, 1, 1, 2);\r
- row.setHeight((short)2800);\r
-\r
- // Insert a numbered multi-level list into cell A7. Note that the\r
- // same ArrayList as constructed for the plain multi-level list\r
- // example will be re-used\r
- row = sheet.createRow(6);\r
- cell = row.createCell(0);\r
- this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell);\r
- row.setHeight((short)2800);\r
-\r
- // Save the completed workbook\r
- outputFile = new File(outputFilename);\r
- fos = new FileOutputStream(outputFile);\r
- workbook.write(fos);\r
- }\r
- catch(FileNotFoundException fnfEx) {\r
- System.out.println("Caught a: " + fnfEx.getClass().getName());\r
- System.out.println("Message: " + fnfEx.getMessage());\r
- System.out.println("Stacktrace follows...........");\r
- fnfEx.printStackTrace(System.out);\r
- }\r
- catch(IOException ioEx) {\r
- System.out.println("Caught a: " + ioEx.getClass().getName());\r
- System.out.println("Message: " + ioEx.getMessage());\r
- System.out.println("Stacktrace follows...........");\r
- ioEx.printStackTrace(System.out);\r
- }\r
- finally {\r
- if(fos != null) {\r
- try {\r
- fos.close();\r
- }\r
- catch(IOException ioEx) {\r
-\r
- }\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Inserts a single bulleted item into a cell.\r
- *\r
- * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
- * cell.\r
- * @param listItem An instance of the String class encapsulating the\r
- * items text.\r
- * @param cell An instance of the HSSFCell class that encapsulates a\r
- * reference to the spreadsheet cell into which the list item\r
- * will be written.\r
- */\r
- public void bulletedItemInCell(HSSFWorkbook workbook, String listItem, HSSFCell cell) {\r
- // A format String must be built to ensure that the contents of the\r
- // cell appear as a bulleted item.\r
- HSSFDataFormat format = workbook.createDataFormat();\r
- String formatString = InCellLists.BULLET_CHARACTER + " @";\r
- int formatIndex = format.getFormat(formatString);\r
-\r
- // Construct an HSSFCellStyle and set it's data formt to use the\r
- // object created above.\r
- HSSFCellStyle bulletStyle = workbook.createCellStyle();\r
- bulletStyle.setDataFormat((short)formatIndex);\r
-\r
- // Set the cells contents and style.\r
- cell.setCellValue(new HSSFRichTextString(listItem));\r
- cell.setCellStyle(bulletStyle);\r
- }\r
-\r
- /**\r
- * Inserts a list of plain items - that is items that are neither\r
- * numbered or bulleted - into a single cell.\r
- *\r
- * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
- * cell.\r
- * @param listItems An ArrayList whose elements encapsulate the text for\r
- * the list's items.\r
- * @param cell An instance of the HSSFCell class that encapsulates a\r
- * reference to the spreadsheet cell into which the list\r
- * will be written.\r
- */\r
- public void listInCell(HSSFWorkbook workbook, ArrayList<String> listItems, HSSFCell cell) {\r
- StringBuffer buffer = new StringBuffer();\r
- HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
- wrapStyle.setWrapText(true);\r
- for(String listItem : listItems) {\r
- buffer.append(listItem);\r
- buffer.append("\n");\r
- }\r
- // The StringBuffer's contents are the source for the contents\r
- // of the cell.\r
- cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
- cell.setCellStyle(wrapStyle);\r
- }\r
-\r
- /**\r
- * Inserts a numbered list into a single cell.\r
- *\r
- * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
- * cell.\r
- * @param listItems An ArrayList whose elements encapsulate the text for\r
- * the lists items.\r
- * @param cell An instance of the HSSFCell class that encapsulates a\r
- * reference to the spreadsheet cell into which the list\r
- * will be written.\r
- * @param startingValue A primitive int containing the number for the first\r
- * item in the list.\r
- * @param increment A primitive int containing the value that should be used\r
- * to calculate subsequent item numbers.\r
- */\r
- public void numberedListInCell(HSSFWorkbook workbook,\r
- ArrayList<String> listItems,\r
- HSSFCell cell,\r
- int startingValue,\r
- int increment) {\r
- StringBuffer buffer = new StringBuffer();\r
- int itemNumber = startingValue;\r
- // Note that again, an HSSFCellStye object is required and that\r
- // it's wrap text property should be set to 'true'\r
- HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
- wrapStyle.setWrapText(true);\r
- // Note that the basic method is identical to the listInCell() method\r
- // with one difference; a number prefixed to the items text.\r
- for(String listItem : listItems) {\r
- buffer.append(String.valueOf(itemNumber) + ". ");\r
- buffer.append(listItem);\r
- buffer.append("\n");\r
- itemNumber += increment;\r
- }\r
- // The StringBuffer's contents are the source for the contents\r
- // of the cell.\r
- cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
- cell.setCellStyle(wrapStyle);\r
- }\r
-\r
- /**\r
- * Insert a bulleted list into a cell.\r
- *\r
- * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
- * cell.\r
- * @param listItems An ArrayList whose elements encapsulate the text for\r
- * the lists items.\r
- * @param cell An instance of the HSSFCell class that encapsulates a\r
- * reference to the spreadsheet cell into which the list\r
- * will be written.\r
- */\r
- public void bulletedListInCell(HSSFWorkbook workbook,\r
- ArrayList<String> listItems,\r
- HSSFCell cell) {\r
- StringBuffer buffer = new StringBuffer();\r
- // Note that again, an HSSFCellStye object is required and that\r
- // it's wrap text property should be set to 'true'\r
- HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
- wrapStyle.setWrapText(true);\r
- // Note that the basic method is identical to the listInCell() method\r
- // with one difference; the bullet character prefixed to the items text.\r
- for(String listItem : listItems) {\r
- buffer.append(InCellLists.BULLET_CHARACTER + " ");\r
- buffer.append(listItem);\r
- buffer.append("\n");\r
- }\r
- // The StringBuffer's contents are the source for the contents\r
- // of the cell.\r
- cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
- cell.setCellStyle(wrapStyle);\r
- }\r
-\r
- /**\r
- * Insert a multi-level list into a cell.\r
- *\r
- * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
- * cell.\r
- * @param multiLevelListItems An ArrayList whose elements contain instances\r
- * of the MultiLevelListItem class. Each element\r
- * encapsulates the text for the high level item\r
- * along with an ArrayList. Each element of this\r
- * ArrayList encapsulates the text for a lower\r
- * level item.\r
- * @param cell An instance of the HSSFCell class that encapsulates a\r
- * reference to the spreadsheet cell into which the list\r
- * will be written.\r
- */\r
- public void multiLevelListInCell(HSSFWorkbook workbook,\r
- ArrayList<MultiLevelListItem> multiLevelListItems,\r
- HSSFCell cell) {\r
- StringBuffer buffer = new StringBuffer();\r
- ArrayList<String> lowerLevelItems = null;\r
- // Note that again, an HSSFCellStye object is required and that\r
- // it's wrap text property should be set to 'true'\r
- HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
- wrapStyle.setWrapText(true);\r
- // Step through the ArrayList of MultilLevelListItem instances.\r
- for(MultiLevelListItem multiLevelListItem : multiLevelListItems) {\r
- // For each element in the ArrayList, get the text for the high\r
- // level list item......\r
- buffer.append(multiLevelListItem.getItemText());\r
- buffer.append("\n");\r
- // and then an ArrayList whose elements encapsulate the text\r
- // for the lower level list items.\r
- lowerLevelItems = multiLevelListItem.getLowerLevelItems();\r
- if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) {\r
- for(String item : lowerLevelItems) {\r
- buffer.append(InCellLists.TAB);\r
- buffer.append(item);\r
- buffer.append("\n");\r
- }\r
- }\r
- }\r
- // The StringBuffer's contents are the source for the contents\r
- // of the cell.\r
- cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
- cell.setCellStyle(wrapStyle);\r
- }\r
-\r
- /**\r
- * Insert a multi-level list into a cell.\r
- *\r
- * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
- * cell.\r
- * @param multiLevelListItems An ArrayList whose elements contain instances\r
- * of the MultiLevelListItem class. Each element\r
- * encapsulates the text for the high level item\r
- * along with an ArrayList. Each element of this\r
- * ArrayList encapsulates the text for a lower\r
- * level item.\r
- * @param cell An instance of the HSSFCell class that encapsulates a\r
- * reference to the spreadsheet cell into which the list\r
- * will be written.\r
- * @param highLevelStartingValue A primitive int containing the number\r
- * for the first high level item in the list.\r
- * @param highLevelIncrement A primitive int containing the value that\r
- * should be used to calculate the number of\r
- * subsequent high level item.\r
- * @param lowLevelStartingValue A primitive int will containing the number\r
- * for the first low level item associated\r
- * with a high level item.\r
- * @param lowLevelIncrement A primitive int containing the value that\r
- * should be used to calculate the number of\r
- * subsequent low level item.\r
- */\r
- public void multiLevelNumberedListInCell(HSSFWorkbook workbook,\r
- ArrayList<MultiLevelListItem> multiLevelListItems,\r
- HSSFCell cell,\r
- int highLevelStartingValue,\r
- int highLevelIncrement,\r
- int lowLevelStartingValue,\r
- int lowLevelIncrement) {\r
- StringBuffer buffer = new StringBuffer();\r
- int highLevelItemNumber = highLevelStartingValue;\r
- int lowLevelItemNumber = 0;\r
- ArrayList<String> lowerLevelItems = null;\r
- // Note that again, an HSSFCellStye object is required and that\r
- // it's wrap text property should be set to 'true'\r
- HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
- wrapStyle.setWrapText(true);\r
- // Step through the ArrayList of MultilLevelListItem instances.\r
- for(MultiLevelListItem multiLevelListItem : multiLevelListItems) {\r
- // For each element in the ArrayList, get the text for the high\r
- // level list item......\r
- buffer.append(String.valueOf(highLevelItemNumber));\r
- buffer.append(". ");\r
- buffer.append(multiLevelListItem.getItemText());\r
- buffer.append("\n");\r
- // and then an ArrayList whose elements encapsulate the text\r
- // for the lower level list items.\r
- lowerLevelItems = multiLevelListItem.getLowerLevelItems();\r
- if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) {\r
- lowLevelItemNumber = lowLevelStartingValue;\r
- for(String item : lowerLevelItems) {\r
- buffer.append(InCellLists.TAB);\r
- buffer.append(String.valueOf(highLevelItemNumber));\r
- buffer.append(".");\r
- buffer.append(String.valueOf(lowLevelItemNumber));\r
- buffer.append(" ");\r
- buffer.append(item);\r
- buffer.append("\n");\r
- lowLevelItemNumber += lowLevelIncrement;\r
- }\r
- }\r
- highLevelItemNumber += highLevelIncrement;\r
- }\r
- // The StringBuffer's contents are the source for the contents\r
- // of the cell.\r
- cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
- cell.setCellStyle(wrapStyle);\r
- }\r
-\r
- /**\r
- * Insert a bulleted multi-level list into a cell.\r
- *\r
- * @param workbook A reference to the HSSFWorkbook that 'contains' the\r
- * cell.\r
- * @param multiLevelListItems An ArrayList whose elements contain instances\r
- * of the MultiLevelListItem class. Each element\r
- * encapsulates the text for the high level item\r
- * along with an ArrayList. Each element of this\r
- * ArrayList encapsulates the text for a lower\r
- * level item.\r
- * @param cell An instance of the HSSFCell class that encapsulates a\r
- * reference to the spreadsheet cell into which the list\r
- * will be written.\r
- */\r
- public void multiLevelBulletedListInCell(HSSFWorkbook workbook,\r
- ArrayList<MultiLevelListItem> multiLevelListItems,\r
- HSSFCell cell) {\r
- StringBuffer buffer = new StringBuffer();\r
- ArrayList<String> lowerLevelItems = null;\r
- // Note that again, an HSSFCellStye object is required and that\r
- // it's wrap text property should be set to 'true'\r
- HSSFCellStyle wrapStyle = workbook.createCellStyle();\r
- wrapStyle.setWrapText(true);\r
- // Step through the ArrayList of MultilLevelListItem instances.\r
- for(MultiLevelListItem multiLevelListItem : multiLevelListItems) {\r
- // For each element in the ArrayList, get the text for the high\r
- // level list item......\r
- buffer.append(InCellLists.BULLET_CHARACTER);\r
- buffer.append(" ");\r
- buffer.append(multiLevelListItem.getItemText());\r
- buffer.append("\n");\r
- // and then an ArrayList whose elements encapsulate the text\r
- // for the lower level list items.\r
- lowerLevelItems = multiLevelListItem.getLowerLevelItems();\r
- if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) {\r
- for(String item : lowerLevelItems) {\r
- buffer.append(InCellLists.TAB);\r
- buffer.append(InCellLists.BULLET_CHARACTER);\r
- buffer.append(" ");\r
- buffer.append(item);\r
- buffer.append("\n");\r
- }\r
- }\r
- }\r
- // The StringBuffer's contents are the source for the contents\r
- // of the cell.\r
- cell.setCellValue(new HSSFRichTextString(buffer.toString().trim()));\r
- cell.setCellStyle(wrapStyle);\r
- }\r
-\r
- /**\r
- * The main entry point to the program. Demonstrates how to call the method\r
- * that will create an Excel workbook containing many different sorts of\r
- * lists.\r
- *\r
- * @param args the command line arguments.\r
- */\r
- public static void main(String[] args) {\r
- new InCellLists().demonstrateMethodCalls("C:/temp/Latest In Cell List.xls");\r
- }\r
-\r
- /**\r
- * An instance of this inner class models an item or element in a\r
- * multi-level list. Each multi-level list item consists of the text for the\r
- * high level items and an ArrayList containing the text for each of the\r
- * associated lower level items. When written into a cell, each multi-level\r
- * list item will have this general appearance.\r
- *\r
- * Item One\r
- * Sub Item One.\r
- * Sub Item Two.\r
- * Item Two\r
- * Sub Item One.\r
- * Sub Item Two.\r
- * etc.\r
- *\r
- * It would be quite possible to modify this class to model much more\r
- * complex list structures descending through two, three or even more\r
- * levels.\r
- */\r
- public final class MultiLevelListItem {\r
-\r
- private String itemText = null;\r
- private ArrayList<String> lowerLevelItems = null;\r
-\r
- /**\r
- * Create a new instance of the MultiLevelListItem class using the\r
- * following parameters.\r
- *\r
- * @param itemText A String that encapsulates the text for the high\r
- * level list item.\r
- * @param lowerLevelItems An ArrayList whose elements encapsulate the\r
- * text for the associated lower level list\r
- * items.\r
- */\r
- public MultiLevelListItem(String itemText, ArrayList<String> lowerLevelItems) {\r
- this.itemText = itemText;\r
- this.lowerLevelItems = lowerLevelItems;\r
- }\r
-\r
- /**\r
- * Get the text for the high level list item.\r
- *\r
- * @return A String that encapsulates the text for the high level list\r
- * item.\r
- */\r
- public String getItemText() {\r
- return(this.itemText);\r
- }\r
-\r
- /**\r
- * Get the text for the associated lower level list items.\r
- *\r
- * @return An ArrayList whose elements each encapsulate the text for a\r
- * single associated lower level list item.\r
- */\r
- public ArrayList<String> getLowerLevelItems() {\r
- return(this.lowerLevelItems);\r
- }\r
- }\r
-}\r
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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 <fauzia.lala at wcom.com>
- */
-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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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);
- }
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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);
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
- }
-
-
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
- }
-
-
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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));
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.
- * <p/>
- * 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.
- * <p/>
- * 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
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<Integer,HSSFColor> 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]);
- }
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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());
- }
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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");
- }
-
-
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<Integer,HSSFColor> 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]);
- }
-}
+++ /dev/null
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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);
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<sheetCount;i++) {
- String sheetName = wb.getSheetName(i);
- //Add the new sheet to the tabbed pane
- sheetPane.addTab(sheetName, makeSheetView(wb.getSheetAt(i)));
- }
- setLayout(new BorderLayout());
- add(sheetPane, BorderLayout.CENTER);
- }
-
- protected JComponent makeSheetView(HSSFSheet sheet) {
- JTable sheetView = new JTable(new SVTableModel(sheet));
- sheetView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
- sheetView.setDefaultRenderer(HSSFCell.class, cellRenderer);
- if (allowEdits)
- sheetView.setDefaultEditor(HSSFCell.class, cellEditor);
- JTableHeader header = sheetView.getTableHeader();
- //Dont allow column reordering
- header.setReorderingAllowed(false);
- //Only allow column resizing if editing is allowed
- header.setResizingAllowed(allowEdits);
-
- //Set the columns the correct size
- TableColumnModel columns = sheetView.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);
- }
-
- //Set the rows to the correct size
- int rows = sheet.getPhysicalNumberOfRows();
- Insets insets = cellRenderer.getInsets();
- //Need to include the insets in the calculation of the row height to use.
- int extraHeight = insets.bottom+insets.top;
- for (int i=0; i< rows; i++) {
- HSSFRow row = sheet.getRow(i);
- if (row == null) {
- sheetView.setRowHeight(i, (int)sheet.getDefaultRowHeightInPoints()+extraHeight);
- } else {
- sheetView.setRowHeight(i, (int)row.getHeightInPoints()+extraHeight);
- }
- }
-
- //Add the row header to the sheet
- SVRowHeader rowHeader = new SVRowHeader(sheet, sheetView, extraHeight);
- JScrollPane scroll = new JScrollPane( sheetView );
- scroll.setRowHeaderView(rowHeader);
- return scroll;
- }
-
- public void paint(Graphics g) {
- //JMH I am only overriding this to get a picture of the time taken to paint
- long start = System.currentTimeMillis();
- super.paint(g);
- long elapsed = System.currentTimeMillis()-start;
- System.out.println("Paint time = "+elapsed);
- }
-
- protected MouseListener createTabListener() {
- return new TabListener();
- }
-
- /** This class defines the default MouseListener that listens to
- * mouse events in the tabbed pane
- *
- * The default is to popup a menu when the event occurs over a tab
- */
- private class TabListener implements MouseListener {
- public JPopupMenu popup;
- public TabListener() {
- popup = new JPopupMenu("Sheet");
- popup.add(createInsertSheetAction());
- popup.add(createDeleteSheetAction());
- popup.add(createRenameSheetAction());
- }
-
- protected Action createInsertSheetAction() {
- return new InsertSheetAction();
- }
-
- protected Action createDeleteSheetAction() {
- return new DeleteSheetAction();
- }
-
- protected Action createRenameSheetAction() {
- return new RenameSheetAction();
- }
-
-
- /** This method will display the popup if the mouseevent is a popup event
- * and the event occurred over a tab
- */
- protected void checkPopup(MouseEvent e) {
- if (e.isPopupTrigger()) {
- int tab = sheetPane.getUI().tabForCoordinate(sheetPane, e.getX(), e.getY());
- if (tab != -1) {
- popup.show(sheetPane, e.getX(), e.getY());
- }
- }
- }
-
- public void mouseClicked(MouseEvent e) {
- checkPopup(e);
- }
-
- public void mousePressed(MouseEvent e) {
- checkPopup(e);
- }
-
- public void mouseReleased(MouseEvent e) {
- checkPopup(e);
- }
-
- public void mouseEntered(MouseEvent e) {}
- public void mouseExited(MouseEvent e) {}
- }
-
- /** This class defines the action that is performed when the sheet is renamed*/
- private class RenameSheetAction extends AbstractAction {
- public RenameSheetAction() {
- super("Rename");
- }
-
- public void actionPerformed(ActionEvent e) {
- int tabIndex = sheetPane.getSelectedIndex();
- if (tabIndex != -1) {
- String newSheetName = JOptionPane.showInputDialog(sheetPane, "Enter a new Sheetname", "Rename Sheet", JOptionPane.QUESTION_MESSAGE);
- if (newSheetName != null) {
- wb.setSheetName(tabIndex, newSheetName);
- sheetPane.setTitleAt(tabIndex, newSheetName);
- }
- }
- }
- }
-
- /** This class defines the action that is performed when a sheet is inserted*/
- private class InsertSheetAction extends AbstractAction {
- public InsertSheetAction() {
- super("Insert");
- }
-
- public void actionPerformed(ActionEvent e) {
- //Create a new sheet then search for the sheet and make sure that the
- //sheetPane shows it.
- HSSFSheet newSheet = wb.createSheet();
- for (int i=0; i<wb.getNumberOfSheets();i++) {
- HSSFSheet sheet = wb.getSheetAt(i);
- if (newSheet == sheet) {
- sheetPane.insertTab(wb.getSheetName(i), null, makeSheetView(sheet), null, i);
- }
- }
- }
- }
-
- /** This class defines the action that is performed when the sheet is deleted*/
- private class DeleteSheetAction extends AbstractAction {
- public DeleteSheetAction() {
- super("Delete");
- }
-
- public void actionPerformed(ActionEvent e) {
- int tabIndex = sheetPane.getSelectedIndex();
- if (tabIndex != -1) {
- if (JOptionPane.showConfirmDialog(sheetPane, "Are you sure that you want to delete the selected sheet", "Delete Sheet?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
- wb.removeSheetAt(tabIndex);
- sheetPane.remove(tabIndex);
- }
- }
- }
- }
-
- public boolean isEditable() {
- return allowEdits;
- }
-
- /**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");
- }
- try {
- FileInputStream in = new FileInputStream(args[0]);
- HSSFWorkbook wb = new HSSFWorkbook(in);
- in.close();
-
- SViewerPanel p = new SViewerPanel(wb, true);
- JFrame frame;
- frame = new JFrame() {
- 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("Viewer Frame");
- frame.getContentPane().add(p, BorderLayout.CENTER);
- frame.setSize(800,640);
- Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
- frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
- frame.setVisible(true);
- } catch (IOException ex) {
- ex.printStackTrace();
- System.exit(1);
- }
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.brush;
-
-import java.awt.*;
-
-/**
- * This is a basic brush that just draws the line with the given parameters.
- * This is a {@link BasicStroke} object that can be used as a {@link Brush}.
- *
- * @author Ken Arnold, Industrious Media LLC
- * @see BasicStroke
- */
-public class BasicBrush extends BasicStroke implements Brush {
- /**
- * Creates a new basic brush with the given width. Invokes {@link
- * BasicStroke#BasicStroke(float)}
- *
- * @param width The brush width.
- *
- * @see BasicStroke#BasicStroke(float)
- */
- public BasicBrush(float width) {
- super(width);
- }
-
- /**
- * Creates a new basic brush with the given width, cap, and join. Invokes
- * {@link BasicStroke#BasicStroke(float,int,int)}
- *
- * @param width The brush width.
- * @param cap The capping style.
- * @param join The join style.
- *
- * @see BasicStroke#BasicStroke(float, int, int)
- */
- public BasicBrush(float width, int cap, int join) {
- super(width, cap, join);
- }
-
- /**
- * Creates a new basic brush with the given parameters. Invokes {@link
- * BasicStroke#BasicStroke(float,int,int,float,float[],float)} with a miter
- * limit of 11 (the normal default value).
- *
- * @param width The brush width.
- * @param cap The capping style.
- * @param join The join style.
- * @param dashes The dash intervals.
- * @param dashPos The intial dash position in the dash intervals.
- *
- * @see BasicStroke#BasicStroke(float, int, int, float, float[], float)
- */
- public BasicBrush(float width, int cap, int join, float[] dashes,
- int dashPos) {
- super(width, cap, join, 11.0f, dashes, dashPos);
- }
-}
\ No newline at end of file
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.brush;
-
-import java.awt.*;
-
-/**
- * This is the type you must implement to create a brush that will be used for a
- * spreadsheet border.
- *
- * @author Ken Arnold, Industrious Media LLC
- */
-public interface Brush extends Stroke {
- /** Returns the width of the brush. */
- float getLineWidth();
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.brush;
-
-import java.awt.*;
-
-/**
- * This Stroke implementation applies a BasicStroke to a shape twice. If you
- * draw with this Stroke, then instead of outlining the shape, you're outlining
- * the outline of the shape.
- *
- * @author Ken Arnold, Industrious Media LLC
- */
-public class DoubleStroke implements Brush {
- BasicStroke stroke1, stroke2; // the two strokes to use
-
- /**
- * Creates a new double-stroke brush. This surrounds a cell with a two
- * lines separated by white space between.
- *
- * @param width1 The width of the blank space in the middle
- * @param width2 The width of the each of the two drawn strokes.
- */
- public DoubleStroke(float width1, float width2) {
- stroke1 = new BasicStroke(width1); // Constructor arguments specify
- stroke2 = new BasicStroke(width2); // the line widths for the strokes
- }
-
- /**
- * Stroke the outline.
- *
- * @param s The shape in which to stroke.
- *
- * @return The created stroke as a new shape.
- */
- public Shape createStrokedShape(Shape s) {
- // Use the first stroke to create an outline of the shape
- Shape outline = stroke1.createStrokedShape(s);
- // Use the second stroke to create an outline of that outline.
- // It is this outline of the outline that will be filled in
- return stroke2.createStrokedShape(outline);
- }
-
- /** {@inheritDoc} */
- public float getLineWidth() {
- return stroke1.getLineWidth() + 2 * stroke2.getLineWidth();
- }
-}
\ No newline at end of file
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.brush;
-
-import javax.swing.*;
-import java.awt.*;
-import java.awt.geom.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This class is used to hold pending brush paintings. The model is that some
- * border drawing requires drawing strokes after all the cells have been
- * painted. The list of pending paintings can be put in this object during the
- * initial paint of the component, and then executed at the appropriate time,
- * such as at the end of the containing object's {@link
- * JComponent#paintChildren(Graphics)} method.
- * <p/>
- * 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<Painting> 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<Painting>();
- 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.)
- * <p/>
- * 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 <tt>null</tt>
- * 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
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<!--
- ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ====================================================================
--->
-<html>
-
-<body>
-This package contains some brushes that are used when drawing borders for Excel
-cells.
-</body>
-</html>
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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 ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
- _out.write ("<!DOCTYPE document PUBLIC \"-//APACHE//DTD Documentation V1.1//EN\" \"./dtd/document-v11.dtd\">\r\n");
- }
-
- public void openDocument ()
- throws IOException
- {
- _out.write ("<document>\r\n");
- }
- public void closeDocument ()
- throws IOException
- {
- _out.write ("</document>\r\n");
- }
-
-
- public void openBody ()
- throws IOException
- {
- _out.write ("<body>\r\n");
- }
-
- public void closeBody ()
- throws IOException
- {
- _out.write ("</body>\r\n");
- }
-
-
- public void openSection ()
- throws IOException
- {
- _out.write ("<section>");
-
- }
-
- public void closeSection ()
- throws IOException
- {
- _out.write ("</section>");
-
- }
-
- public void openTitle ()
- throws IOException
- {
- _out.write ("<title>");
- }
-
- public void closeTitle ()
- throws IOException
- {
- _out.write ("</title>");
- }
-
- public void writePlainText (String text)
- throws IOException
- {
- _out.write (text);
- }
-
- public void openParagraph ()
- throws IOException
- {
- _out.write ("<p>");
- }
-
- public void closeParagraph ()
- throws IOException
- {
- _out.write ("</p>");
- }
-
- public void openSource ()
- throws IOException
- {
- _out.write ("<source><![CDATA[");
- }
- public void closeSource ()
- throws IOException
- {
- _out.write ("]]></source>");
- }
-
-
- 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();
- }
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-
-
-/**
- * <p>Provides utility methods for encoding and decoding hexadecimal
- * data.</p>
- *
- * @author Rainer Klute (klute@rainer-klute.de) - with portions from Tomcat
- */
-public class Codec
-{
-
- /**
- * <p>The nibbles' hexadecimal values. A nibble is a half byte.</p>
- */
- 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'};
-
-
-
- /**
- * <p>Converts a string into its hexadecimal notation.</p>
- */
- public static String hexEncode(final String s)
- {
- return hexEncode(s.getBytes());
- }
-
-
-
- /**
- * <p>Converts a byte array into its hexadecimal notation.</p>
- */
- public static String hexEncode(final byte[] s)
- {
- return hexEncode(s, 0, s.length);
- }
-
-
-
- /**
- * <p>Converts a part of a byte array into its hexadecimal
- * notation.</p>
- */
- 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();
- }
-
-
-
- /**
- * <p>Converts a single byte into its hexadecimal notation.</p>
- */
- 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();
- }
-
-
-
- /**
- * <p>Converts a short value (16-bit) into its hexadecimal
- * notation.</p>
- */
- 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();
- }
-
-
-
- /**
- * <p>Converts an int value (32-bit) into its hexadecimal
- * notation.</p>
- */
- 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();
- }
-
-
-
- /**
- * <p>Converts a long value (64-bit) into its hexadecimal
- * notation.</p>
- */
- 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();
- }
-
-
-
- /**
- * <p>Converts a class ID into its hexadecimal notation.</p>
- */
- public static String hexEncode(final ClassID classID)
- {
- return hexEncode(classID.getBytes());
- }
-
-
-
- /**
- * <p>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'.</p>
- *
- * @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;
- }
-
-
-
- /**
- * <p>Decodes a nibble.</p>
- *
- * @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 <em>c</em> 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.");
- }
-
-
-
- /**
- * <p>For testing.</p>
- */
- 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);
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.*;
-
-/**
- * <p>Describes the most important (whatever that is) features of a
- * {@link POIFSDocument}.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class DocumentDescriptor
-{
- String name;
- POIFSDocumentPath path;
- DocumentInputStream stream;
-
- int size;
- byte[] bytes;
-
-
- /**
- * <p>Creates a {@link DocumentDescriptor}.</p>
- *
- * @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);
- }
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.*;
-
-/**
- * <p>{@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.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-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;
- }
-
-
- /**
- * <p>Renders {@link DocumentDescriptor} as a string.</p>
- */
- 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();
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.*;
-
-/**
- * <p>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.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class ExtendableTreeCellRenderer implements TreeCellRenderer
-{
-
- /**
- * <p>Maps classes to renderers.</p>
- */
- 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;
- }
- });
- }
-
-
-
- /**
- * <p>Registers a renderer for a class.</p>
- **/
- public void register(final Class c, final TreeCellRenderer renderer)
- {
- renderers.put(c, renderer);
- }
-
-
-
- /**
- * <p>Unregisters a renderer for a class. The renderer for the
- * {@link Object} class cannot be unregistered.</p>
- */
- public void unregister(final Class c)
- {
- if (c == Object.class)
- throw new IllegalArgumentException
- ("Renderer for Object cannot be unregistered.");
- renderers.put(c, null);
- }
-
-
-
- /**
- * <p>Renders an object in a tree cell depending of the object's
- * class.</p>
- *
- * @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);
- }
-
-
-
- /**
- * <p>Find the renderer for the specified class.</p>
- */
- 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;
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>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!</p>
- *
- * @see POIFSReader
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class POIBrowser extends JFrame
-{
-
- /**
- * <p>The tree's root node must be visible to all methods.</p>
- */
- protected MutableTreeNode rootNode;
-
-
-
- /**
- * <p>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}.</p>
- */
- 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);
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>Describes the most important (whatever that is) features of a
- * stream containing a {@link PropertySet}.</p>
- *
- * @author Rainer Klute (klute@rainer-klute.de)
- */
-public class PropertySetDescriptor extends DocumentDescriptor
-{
-
- protected PropertySet propertySet;
-
- /**
- * <p>Returns this {@link PropertySetDescriptor}'s {@link
- * PropertySet}.</p>
- */
- public PropertySet getPropertySet()
- {
- return propertySet;
- }
-
-
-
- /**
- * <p>Creates a {@link PropertySetDescriptor} by reading a {@link
- * PropertySet} from a {@link DocumentInputStream}.</p>
- *
- * @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);
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>Renders a {@link PropertySetDescriptor} by more or less dumping
- * the stuff into a {@link JTextArea}.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-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;
- }
-
-
-
- /**
- * <p>Returns a string representation of a list of {@link
- * Section}s.</p>
- */
- 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();
- }
-
-
-
- /**
- * <p>Returns a string representation of a {@link Section}.</p>
- * @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();
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-/**
- * <p>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.</p>
- *
- * <p>The root tree node should be the root tree node of a {@link
- * javax.swing.tree.TreeModel}.</p>
- *
- * <p>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.</p>
- *
- * <p>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.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class TreeReaderListener implements POIFSReaderListener
-{
-
- /**
- * <p>The tree's root node. POI filesystems get attached to this
- * node as children.</p>
- */
- protected MutableTreeNode rootNode;
-
- /**
- * <p>Maps filenames and POI document paths to their associated
- * tree nodes.</p>
- */
- protected Map pathToNode;
-
- /**
- * <p>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.</p>
- */
- protected String filename;
-
-
-
- /**
- * <p>Creates a {@link TreeReaderListener} which should then be
- * registered with a
- * {@link org.apache.poi.poifs.eventfilesystem.POIFSReader}.</p>
- *
- * @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.
- }
-
-
-
- /** <p>The number of bytes to dump.</p> */
- private int nrOfBytes = 50;
-
- public void setNrOfBytes(final int nrOfBytes)
- {
- this.nrOfBytes = nrOfBytes;
- }
-
- public int getNrOfBytes()
- {
- return nrOfBytes;
- }
-
-
-
- /**
- * <p>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.</p>
- */
- 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);
- }
-
-
-
- /**
- * <p>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.</p>
- *
- * @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;
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.*;
-
-/**
- * <p>Contains various (well, just one at the moment) static utility
- * methods.</p>
- *
- * @author Rainer Klute <a
- * href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
- */
-public class Util {
-
- /**
- * <p>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 <tt>c.setOpaque(true)</tt>.</p>
- */
- public static void invert(JComponent c) {
- Color invBackground = c.getForeground();
- Color invForeground = c.getBackground();
- c.setBackground(invBackground);
- c.setForeground(invForeground);
- }
-}
-
+++ /dev/null
-/* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
-==================================================================== */\r
-\r
-\r
-package org.apache.poi.ss.examples;\r
-\r
-import java.io.File;\r
-import java.io.FileNotFoundException;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-import java.net.URL;\r
-\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
-import org.apache.poi.hssf.usermodel.HSSFSheet;\r
-import org.apache.poi.ss.usermodel.ClientAnchor;\r
-import org.apache.poi.ss.usermodel.Drawing;\r
-import org.apache.poi.ss.usermodel.Row;\r
-import org.apache.poi.ss.usermodel.Sheet;\r
-import org.apache.poi.ss.usermodel.Workbook;\r
-import org.apache.poi.ss.util.CellReference;\r
-import org.apache.poi.util.IOUtils;\r
-\r
-\r
-/**\r
- * Demonstrates how to add an image to a worksheet and set that images size\r
- * to a specific number of millimetres irrespective of the width of the columns\r
- * or height of the rows. Overridden methods are provided so that the location\r
- * of the image - the cells row and column coordinates that define the top\r
- * left hand corners of the image - can be identified either in the familiar\r
- * Excel manner - A1 for instance - or using POI's methodology of a column and\r
- * row index where 0, 0 would indicate cell A1.\r
- *\r
- * The best way to make use of these techniques is to delay adding the image to\r
- * the sheet until all other work has been completed. That way, the sizes of\r
- * all rows and columns will have been adjusted - assuming that step was\r
- * necessary. Even though the anchors type is set to prevent the image moving\r
- * or re-sizing, this setting does not have any effect until the sheet is being\r
- * viewed using the Excel application.\r
- *\r
- * The key to the process is the ClientAnchor class. It defines methods that allow\r
- * us to define the location of an image by specifying the following;\r
- *\r
- * * How far - in terms of coordinate positions - the image should be inset\r
- * from the left hand border of a cell.\r
- * * How far - in terms of coordinate positions - the image should be inset\r
- * from the from the top of the cell.\r
- * * How far - in terms of coordinate positions - the right hand edge of\r
- * the image should protrude into a cell (measured from the cells left hand\r
- * edge to the images right hand edge).\r
- * * How far - in terms of coordinate positions - the bottom edge of the\r
- * image should protrude into a row (measured from the cells top edge to\r
- * the images bottom edge).\r
- * * The index of the column that contains the cell whose top left hand\r
- * corner should be aligned with the top left hand corner of the image.\r
- * * The index of the row that contains the cell whose top left hand corner\r
- * should be aligned with the images top left hand corner.\r
- * * The index of the column that contains the cell whose top left hand\r
- * corner should be aligned with the images bottom right hand corner\r
- * * The index number of the row that contains the cell whose top left\r
- * hand corner should be aligned with the images bottom right hand corner.\r
- *\r
- * It can be used to add an image into cell A1, for example, in the following\r
- * manner;\r
- *\r
- * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();\r
- *\r
- * anchor.setDx1(0);\r
- * anchor.setDy1(0);\r
- * anchor.setDx2(0);\r
- * anchor.setDy2(0);\r
- * anchor.setCol1(0);\r
- * anchor.setRow1(0);\r
- * anchor.setCol2(1);\r
- * anchor.setRow2(1);\r
- *\r
- * Taken together, the first four methods define the locations of the top left\r
- * and bottom right hand corners of the image if you imagine that the image is\r
- * represented by a simple rectangle. The setDx1() and setDy1() methods locate\r
- * the top left hand corner of the image while setDx2() and and Dy2() locate the\r
- * bottom right hand corner of the image. An individual image can be inserted\r
- * into a single cell or is can lie across many cells and the latter four methods\r
- * are used to define just where the image should be positioned. They do this by\r
- * again by identifying where the top left and bottom right hand corners of the\r
- * image should be located but this time in terms of the indexes of the cells\r
- * in which those corners should be located. The setCol1() and setRow1() methods\r
- * together identify the cell that should contain the top left hand corner of\r
- * the image while setCol2() and setRow2() do the same for the images bottom\r
- * right hand corner. \r
- *\r
- * Knowing that, it is possible to look again at the example above and to see\r
- * that the top left hand corner of the image will be located in cell A1 (0, 0)\r
- * and it will be aligned with the very top left hand corner of the cell. Likewise,\r
- * the bottom right hand corner of the image will be located in cell B2 (1, 1) and\r
- * it will again be aligned with the top left hand corner of the cell. This has the\r
- * effect of making the image seem to occupy the whole of cell A1. Interestingly, it\r
- * also has an effect on the images resizing behaviour because testing has \r
- * demonstrated that if the image is wholly contained within one cell and is not\r
- * 'attached' for want of a better word, to a neighbouring cell, then that image\r
- * will not increase in size in response to the user dragging the column wider\r
- * or the cell higher.\r
- *\r
- * The following example demonstrates a slightly different way to insert an\r
- * image into cell A1 and to ensure that it occupies the whole of the cell. This\r
- * is accomplished by specifying the the images bottom right hand corner should be\r
- * aligned with the bottom right hand corner of the cell. It is also a case\r
- * where the image will not increase in size if the user increases the size of\r
- * the enclosing cell - irrespective of the anchors type - but it will reduce in\r
- * size if the cell is made smaller.\r
- *\r
- * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();\r
- *\r
- * anchor.setDx1(0);\r
- * anchor.setDy1(0);\r
- * anchor.setDx2(1023);\r
- * anchor.setDy2(255);\r
- * anchor.setCol1(0);\r
- * anchor.setRow1(0);\r
- * anchor.setCol2(0);\r
- * anchor.setRow2(0);\r
- *\r
- * Note that the final four method calls all pass the same value and seem to\r
- * indicate that the images top left hand corner is aligned with the top left\r
- * hand corner of cell A1 and that it's bottom right hand corner is also\r
- * aligned with the top left hand corner of cell A1. Yet, running this code\r
- * would see the image fully occupying cell A1. That is the result of the\r
- * values passed to parameters three and four; these I have referred to as\r
- * determining the images coordinates within the cell. They indicate that the\r
- * image should occupy - in order - the full width of the column and the full\r
- * height of the row.\r
- *\r
- * The co-ordinate values shown are the maxima; and they are independent of\r
- * row height/column width and of the font used. Passing 255 will always result\r
- * in the image occupying the full height of the row and passing 1023 will\r
- * always result in the image occupying the full width of the column. They help\r
- * in situations where an image is larger than a column/row and must overlap\r
- * into the next column/row. Using them does mean, however, that it is often\r
- * necessary to perform conversions between Excels characters units, points,\r
- * pixels and millimetres in order to establish how many rows/columns an image\r
- * should occupy and just what the various insets ought to be.\r
- *\r
- * Note that the setDx1(int) and setDy1(int) methods of the ClientAchor class\r
- * are not made use of in the code that follows. It would be fairly trivial\r
- * however to extend this example further and provide methods that would centre\r
- * an image within a cell or allow the user to specify that a plain border a\r
- * fixed number of millimetres wide should wrap around the image. Those first\r
- * two parameters would make this sort of functionality perfectly possible.\r
- *\r
- * Owing to the various conversions used, the actual size of the image may vary\r
- * from that required; testing has so far found this to be in the region of\r
- * plus or minus two millimetres. Most likely by modifying the way the\r
- * calculations are performed - possibly using double(s) throughout and\r
- * rounding the values at the correct point - it is likely that these errors\r
- * could be reduced or removed.\r
- *\r
- * A note concerning Excels image resizing behaviour. The ClientAnchor\r
- * class contains a method called setAnchorType(int) which can be used to\r
- * determine how Excel will resize an image in response to the user increasing\r
- * or decreasing the dimensions of the cell containing the image. There are \r
- * three values that can be passed to this method; 0 = To move and size the \r
- * image with the cell, 2 = To move but don't size the image with the cell,\r
- * 3 = To prevent the image from moving or being resized along with the cell. If\r
- * an image is inserted using this class and placed into a single cell then if\r
- * the setAnchorType(int) method is called and a value of either 0 or 2 passed\r
- * to it, the resultant resizing behaviour may be a surprise. The image will not\r
- * grow in size of the column is made wider or the row higher but it will shrink\r
- * if the columns width or rows height are reduced.\r
- *\r
- * @author Mark Beardsley [msb at apache.org] and Mark Southern [southern at scripps.edu]\r
- * @version 1.00 5th August 2009.\r
- * 2.00 26th February 2010.\r
- * Ported to make use of the the SS usermodel classes.\r
- * Ability to reuse the Drawing Patriarch so that multiple images\r
- * can be inserted without unintentionally erasing earlier images.\r
- * Check on image type added; i.e. jpg, jpeg or png.\r
- * The String used to contain the files name is now converted\r
- * into a URL.\r
- * 2.10 17th May 2012\r
- * Corrected gross error that occurred when using the code with\r
- * XSSF or SXSSF workbooks. In short, the code did not correctly\r
- * calculate the size of the image(s) owing to the use of EMUs\r
- * within the OOXML file format. That problem has largely been\r
- * corrected although it should be mentioned that images are not\r
- * sized with the same level of accuracy. Discrepancies of up to\r
- * 2mm have been noted in testing. Further investigation will\r
- * continue to rectify this issue.\r
- */\r
-public class AddDimensionedImage {\r
-\r
- // Four constants that determine how - and indeed whether - the rows\r
- // and columns an image may overlie should be expanded to accomodate that\r
- // image.\r
- // Passing EXPAND_ROW will result in the height of a row being increased\r
- // to accomodate the image if it is not already larger. The image will\r
- // be layed across one or more columns.\r
- // Passing EXPAND_COLUMN will result in the width of the column being\r
- // increased to accomodate the image if it is not already larger. The image\r
- // will be layed across one or many rows.\r
- // Passing EXPAND_ROW_AND_COLUMN will result in the height of the row\r
- // bing increased along with the width of the column to accomdate the\r
- // image if either is not already larger.\r
- // Passing OVERLAY_ROW_AND_COLUMN will result in the image being layed\r
- // over one or more rows and columns. No row or column will be resized,\r
- // instead, code will determine how many rows and columns the image should\r
- // overlie.\r
- public static final int EXPAND_ROW = 1;\r
- public static final int EXPAND_COLUMN = 2;\r
- public static final int EXPAND_ROW_AND_COLUMN = 3;\r
- public static final int OVERLAY_ROW_AND_COLUMN = 7;\r
- \r
- // Modified to support EMU - English Metric Units - used within the OOXML\r
- // workbooks, this multoplier is used to convert between measurements in\r
- // millimetres and in EMUs\r
- private static final int EMU_PER_MM = 36000;\r
- \r
- /**\r
- * Add an image to a worksheet.\r
- *\r
- * @param cellNumber A String that contains the location of the cell whose\r
- * top left hand corner should be aligned with the top\r
- * left hand corner of the image; for example "A1", "A2"\r
- * etc. This is to support the familiar Excel syntax.\r
- * Whilst images are are not actually inserted into cells\r
- * this provides a convenient method of indicating where\r
- * the image should be positioned on the sheet.\r
- * @param sheet A reference to the sheet that contains the cell referenced\r
- * above.\r
- * @param drawing An instance of the DrawingPatriarch class. This is now\r
- * passed into the method where it was, previously, recovered\r
- * from the sheet in order to allow multiple pictures be\r
- * inserted. If the patriarch was not 'cached in this manner\r
- * each time it was created any previously positioned images\r
- * would be simply over-written.\r
- * @param imageFile An instance of the URL class that encapsulates the name\r
- * of and path to the image that is to be 'inserted into'\r
- * the sheet.\r
- * @param reqImageWidthMM A primitive double that contains the required\r
- * width of the image in millimetres.\r
- * @param reqImageHeightMM A primitive double that contains the required\r
- * height of the image in millimetres.\r
- * @param resizeBehaviour A primitive int whose value will determine how\r
- * the code should react if the image is larger than\r
- * the cell referenced by the cellNumber parameter.\r
- * Four constants are provided to determine what\r
- * should happen;\r
- * AddDimensionedImage.EXPAND_ROW\r
- * AddDimensionedImage.EXPAND_COLUMN\r
- * AddDimensionedImage.EXPAND_ROW_AND_COLUMN\r
- * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN\r
- * @throws java.io.FileNotFoundException If the file containing the image\r
- * cannot be located.\r
- * @throws java.io.IOException If a problem occurs whilst reading the file\r
- * of image data.\r
- * @throws java.lang.IllegalArgumentException If an invalid value is passed\r
- * to the resizeBehaviour\r
- * parameter.\r
- */\r
- public void addImageToSheet(String cellNumber, Sheet sheet, Drawing drawing,\r
- URL imageFile, double reqImageWidthMM, double reqImageHeightMM,\r
- int resizeBehaviour) throws IOException, IllegalArgumentException {\r
- // Convert the String into column and row indices then chain the\r
- // call to the overridden addImageToSheet() method.\r
- CellReference cellRef = new CellReference(cellNumber);\r
- this.addImageToSheet(cellRef.getCol(), cellRef.getRow(), sheet, drawing,\r
- imageFile, reqImageWidthMM, reqImageHeightMM,resizeBehaviour);\r
- }\r
-\r
- /**\r
- * Add an image to a worksheet.\r
- *\r
- * @param colNumber A primitive int that contains the index number of a\r
- * column on the worksheet; POI column indices are zero\r
- * based. Together with the rowNumber parameter's value,\r
- * this parameter identifies a cell on the worksheet. The\r
- * images top left hand corner will be aligned with the\r
- * top left hand corner of this cell.\r
- * @param rowNumber A primitive int that contains the index number of a row\r
- * on the worksheet; POI row indices are zero based.\r
- * Together with the rowNumber parameter's value, this\r
- * parameter identifies a cell on the worksheet. The\r
- * images top left hand corner will be aligned with the\r
- * top left hand corner of this cell.\r
- * @param sheet A reference to the sheet that contains the cell identified\r
- * by the two parameters above.\r
- * @param drawing An instance of the DrawingPatriarch class. This is now\r
- * passed into the method where it was, previously, recovered\r
- * from the sheet in order to allow multiple pictures be\r
- * inserted. If the patriarch was not 'cached in this manner\r
- * each time it was created any previously positioned images\r
- * would be simply over-written.\r
- * @param imageFile An instance of the URL class that encapsulates the name\r
- * of and path to the image that is to be 'inserted into'\r
- * the sheet.\r
- * @param reqImageWidthMM A primitive double that contains the required\r
- * width of the image in millimetres.\r
- * @param reqImageHeightMM A primitive double that contains the required\r
- * height of the image in millimetres.\r
- * @param resizeBehaviour A primitive int whose value will determine how\r
- * the code should react if the image is larger than\r
- * the cell referenced by the colNumber and\r
- * rowNumber parameters. Four constants are provided\r
- * to determine what should happen;\r
- * AddDimensionedImage.EXPAND_ROW\r
- * AddDimensionedImage.EXPAND_COLUMN\r
- * AddDimensionedImage.EXPAND_ROW_AND_COLUMN\r
- * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN\r
- * @throws java.io.FileNotFoundException If the file containing the image\r
- * cannot be located.\r
- * @throws java.io.IOException If a problem occurs whilst reading the file\r
- * of image data.\r
- * @throws java.lang.IllegalArgumentException If an invalid value is passed\r
- * to the resizeBehaviour\r
- * parameter or if the extension\r
- * of the image file indicates that\r
- * it is of a type that cannot\r
- * currently be added to the worksheet.\r
- */\r
- public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing drawing,\r
- URL imageFile, double reqImageWidthMM, double reqImageHeightMM,\r
- int resizeBehaviour) throws IOException,\r
- IllegalArgumentException {\r
- ClientAnchor anchor = null;\r
- ClientAnchorDetail rowClientAnchorDetail = null;\r
- ClientAnchorDetail colClientAnchorDetail = null;\r
- int imageType = 0;\r
-\r
- // Validate the resizeBehaviour parameter.\r
- if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&\r
- (resizeBehaviour != AddDimensionedImage.EXPAND_ROW) &&\r
- (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN) &&\r
- (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) {\r
- throw new IllegalArgumentException("Invalid value passed to the " +\r
- "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()");\r
- }\r
-\r
- // Call methods to calculate how the image and sheet should be\r
- // manipulated to accomodate the image; columns and then rows.\r
- colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber,\r
- reqImageWidthMM, resizeBehaviour);\r
- rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber,\r
- reqImageHeightMM, resizeBehaviour);\r
-\r
- // Having determined if and how to resize the rows, columns and/or the\r
- // image, create the ClientAnchor object to position the image on\r
- // the worksheet. Note how the two ClientAnchorDetail records are\r
- // interrogated to recover the row/column co-ordinates and any insets.\r
- // The first two parameters are not used currently but could be if the\r
- // need arose to extend the functionality of this code by adding the\r
- // ability to specify that a clear 'border' be placed around the image.\r
- anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();\r
-\r
- anchor.setDx1(0);\r
- anchor.setDy1(0);\r
- anchor.setDx2(colClientAnchorDetail.getInset());\r
- anchor.setDy2(rowClientAnchorDetail.getInset());\r
- anchor.setCol1(colClientAnchorDetail.getFromIndex());\r
- anchor.setRow1(rowClientAnchorDetail.getFromIndex());\r
- anchor.setCol2(colClientAnchorDetail.getToIndex());\r
- anchor.setRow2(rowClientAnchorDetail.getToIndex());\r
-\r
- // For now, set the anchor type to do not move or resize the\r
- // image as the size of the row/column is adjusted. This could easilly\r
- // become another parameter passed to the method. Please read the note\r
- // above regarding the behaviour of image resizing.\r
- anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE);\r
-\r
- // Now, add the picture to the workbook. Note that unlike the similar\r
- // method in the HSSF Examples section, the image type is checked. First,\r
- // the image files location is identified by interrogating the URL passed\r
- // to the method, the images type is identified before it is added to the\r
- // sheet.\r
- String sURL = imageFile.toString().toLowerCase();\r
- if( sURL.endsWith(".png") ) {\r
- imageType = Workbook.PICTURE_TYPE_PNG;\r
- }\r
- else if( sURL.endsWith("jpg") || sURL.endsWith(".jpeg") ) {\r
- imageType = Workbook.PICTURE_TYPE_JPEG;\r
- }\r
- else {\r
- throw new IllegalArgumentException("Invalid Image file : " +\r
- sURL);\r
- }\r
- int index = sheet.getWorkbook().addPicture(\r
- IOUtils.toByteArray(imageFile.openStream()), imageType);\r
- drawing.createPicture(anchor, index);\r
- }\r
-\r
- /**\r
- * Determines whether the sheets columns should be re-sized to accomodate\r
- * the image, adjusts the columns width if necessary and creates then\r
- * returns a ClientAnchorDetail object that facilitates construction of\r
- * an ClientAnchor that will fix the image on the sheet and establish\r
- * it's size.\r
- *\r
- * @param sheet A reference to the sheet that will 'contain' the image.\r
- * @param colNumber A primtive int that contains the index number of a\r
- * column on the sheet.\r
- * @param reqImageWidthMM A primitive double that contains the required\r
- * width of the image in millimetres\r
- * @param resizeBehaviour A primitive int whose value will indicate how the\r
- * width of the column should be adjusted if the\r
- * required width of the image is greater than the\r
- * width of the column.\r
- * @return An instance of the ClientAnchorDetail class that will contain\r
- * the index number of the column containing the cell whose top\r
- * left hand corner also defines the top left hand corner of the\r
- * image, the index number column containing the cell whose top\r
- * left hand corner also defines the bottom right hand corner of\r
- * the image and an inset that determines how far the right hand\r
- * edge of the image can protrude into the next column - expressed\r
- * as a specific number of coordinate positions.\r
- */\r
- private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber,\r
- double reqImageWidthMM, int resizeBehaviour) {\r
-\r
- double colWidthMM = 0.0D;\r
- double colCoordinatesPerMM = 0.0D;\r
- int pictureWidthCoordinates = 0;\r
- ClientAnchorDetail colClientAnchorDetail = null;\r
-\r
- // Get the colum's width in millimetres\r
- colWidthMM = ConvertImageUnits.widthUnits2Millimetres(\r
- (short)sheet.getColumnWidth(colNumber));\r
-\r
- // Check that the column's width will accomodate the image at the\r
- // required dimension. If the width of the column is LESS than the\r
- // required width of the image, decide how the application should\r
- // respond - resize the column or overlay the image across one or more\r
- // columns.\r
- if(colWidthMM < reqImageWidthMM) {\r
-\r
- // Should the column's width simply be expanded?\r
- if((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN) ||\r
- (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) {\r
- // Set the width of the column by converting the required image\r
- // width from millimetres into Excel's column width units.\r
- sheet.setColumnWidth(colNumber,\r
- ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM));\r
- // To make the image occupy the full width of the column, convert\r
- // the required width of the image into co-ordinates. This value\r
- // will become the inset for the ClientAnchorDetail class that\r
- // is then instantiated.\r
- if(sheet instanceof HSSFSheet) {\r
- colWidthMM = reqImageWidthMM;\r
- colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS /\r
- colWidthMM;\r
- pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM);\r
-\r
- }\r
- else {\r
- pictureWidthCoordinates = (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM;\r
- }\r
- colClientAnchorDetail = new ClientAnchorDetail(colNumber,\r
- colNumber, pictureWidthCoordinates);\r
- }\r
- // If the user has chosen to overlay both rows and columns or just\r
- // to expand ONLY the size of the rows, then calculate how to lay\r
- // the image out across one or more columns.\r
- else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) ||\r
- (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) {\r
- colClientAnchorDetail = this.calculateColumnLocation(sheet,\r
- colNumber, reqImageWidthMM);\r
- }\r
- }\r
- // If the column is wider than the image.\r
- else {\r
- if(sheet instanceof HSSFSheet) {\r
- // Mow many co-ordinate positions are there per millimetre?\r
- colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS /\r
- colWidthMM;\r
- // Given the width of the image, what should be it's co-ordinate?\r
- pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM);\r
- }\r
- else {\r
- pictureWidthCoordinates = (int)reqImageWidthMM *\r
- AddDimensionedImage.EMU_PER_MM;\r
- }\r
- colClientAnchorDetail = new ClientAnchorDetail(colNumber,\r
- colNumber, pictureWidthCoordinates);\r
- }\r
- return(colClientAnchorDetail);\r
- }\r
-\r
- /**\r
- * Determines whether the sheets row should be re-sized to accomodate\r
- * the image, adjusts the rows height if necessary and creates then\r
- * returns a ClientAnchorDetail object that facilitates construction of\r
- * a ClientAnchor that will fix the image on the sheet and establish\r
- * it's size.\r
- *\r
- * @param sheet A reference to the sheet that will 'contain' the image.\r
- * @param rowNumber A primitive int that contains the index number of a\r
- * row on the sheet.\r
- * @param reqImageHeightMM A primitive double that contains the required\r
- * height of the image in millimetres\r
- * @param resizeBehaviour A primitive int whose value will indicate how the\r
- * height of the row should be adjusted if the\r
- * required height of the image is greater than the\r
- * height of the row.\r
- * @return An instance of the ClientAnchorDetail class that will contain\r
- * the index number of the row containing the cell whose top\r
- * left hand corner also defines the top left hand corner of the\r
- * image, the index number of the row containing the cell whose\r
- * top left hand corner also defines the bottom right hand\r
- * corner of the image and an inset that determines how far the\r
- * bottom edge of the image can protrude into the next (lower)\r
- * row - expressed as a specific number of coordinate positions.\r
- */\r
- private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber,\r
- double reqImageHeightMM, int resizeBehaviour) {\r
- Row row = null;\r
- double rowHeightMM = 0.0D;\r
- double rowCoordinatesPerMM = 0.0D;\r
- int pictureHeightCoordinates = 0;\r
- ClientAnchorDetail rowClientAnchorDetail = null;\r
-\r
- // Get the row and it's height\r
- row = sheet.getRow(rowNumber);\r
- if(row == null) {\r
- // Create row if it does not exist.\r
- row = sheet.createRow(rowNumber);\r
- }\r
-\r
- // Get the row's height in millimetres\r
- rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE;\r
-\r
- // Check that the row's height will accomodate the image at the required\r
- // dimensions. If the height of the row is LESS than the required height\r
- // of the image, decide how the application should respond - resize the\r
- // row or overlay the image across a series of rows.\r
- if(rowHeightMM < reqImageHeightMM) {\r
- if((resizeBehaviour == AddDimensionedImage.EXPAND_ROW) ||\r
- (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) {\r
- row.setHeightInPoints((float)(reqImageHeightMM *\r
- ConvertImageUnits.POINTS_PER_MILLIMETRE));\r
- if(sheet instanceof HSSFSheet) { \r
- rowHeightMM = reqImageHeightMM;\r
- rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS /\r
- rowHeightMM;\r
- pictureHeightCoordinates = (int)(reqImageHeightMM *\r
- rowCoordinatesPerMM);\r
- }\r
- else {\r
- pictureHeightCoordinates = (int)(reqImageHeightMM *\r
- AddDimensionedImage.EMU_PER_MM);\r
- }\r
- rowClientAnchorDetail = new ClientAnchorDetail(rowNumber,\r
- rowNumber, pictureHeightCoordinates);\r
- }\r
- // If the user has chosen to overlay both rows and columns or just\r
- // to expand ONLY the size of the columns, then calculate how to lay\r
- // the image out ver one or more rows.\r
- else if((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) ||\r
- (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) {\r
- rowClientAnchorDetail = this.calculateRowLocation(sheet,\r
- rowNumber, reqImageHeightMM);\r
- }\r
- }\r
- // Else, if the image is smaller than the space available\r
- else {\r
- if(sheet instanceof HSSFSheet) {\r
- rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS /\r
- rowHeightMM;\r
- pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM);\r
- }\r
- else {\r
- pictureHeightCoordinates = (int)(reqImageHeightMM *\r
- AddDimensionedImage.EMU_PER_MM);\r
- }\r
- rowClientAnchorDetail = new ClientAnchorDetail(rowNumber,\r
- rowNumber, pictureHeightCoordinates);\r
- }\r
- return(rowClientAnchorDetail);\r
- }\r
-\r
- /**\r
- * If the image is to overlie more than one column, calculations need to be\r
- * performed to determine how many columns and whether the image will\r
- * overlie just a part of one column in order to be presented at the\r
- * required size.\r
- *\r
- * @param sheet The sheet that will 'contain' the image.\r
- * @param startingColumn A primitive int whose value is the index of the\r
- * column that contains the cell whose top left hand\r
- * corner should be aligned with the top left hand\r
- * corner of the image.\r
- * @param reqImageWidthMM A primitive double whose value will indicate the\r
- * required width of the image in millimetres.\r
- * @return An instance of the ClientAnchorDetail class that will contain\r
- * the index number of the column containing the cell whose top\r
- * left hand corner also defines the top left hand corner of the\r
- * image, the index number column containing the cell whose top\r
- * left hand corner also defines the bottom right hand corner of\r
- * the image and an inset that determines how far the right hand\r
- * edge of the image can protrude into the next column - expressed\r
- * as a specific number of coordinate positions.\r
- */\r
- private ClientAnchorDetail calculateColumnLocation(Sheet sheet,\r
- int startingColumn,\r
- double reqImageWidthMM) {\r
- ClientAnchorDetail anchorDetail = null;\r
- double totalWidthMM = 0.0D;\r
- double colWidthMM = 0.0D;\r
- double overlapMM = 0.0D;\r
- double coordinatePositionsPerMM = 0.0D;\r
- int toColumn = startingColumn;\r
- int inset = 0;\r
-\r
- // Calculate how many columns the image will have to\r
- // span in order to be presented at the required size.\r
- while(totalWidthMM < reqImageWidthMM) {\r
- colWidthMM = ConvertImageUnits.widthUnits2Millimetres(\r
- (short)(sheet.getColumnWidth(toColumn)));\r
- // Note use of the cell border width constant. Testing with an image\r
- // declared to fit exactly into one column demonstrated that it's\r
- // width was greater than the width of the column the POI returned.\r
- // Further, this difference was a constant value that I am assuming\r
- // related to the cell's borders. Either way, that difference needs\r
- // to be allowed for in this calculation.\r
- totalWidthMM += (colWidthMM + ConvertImageUnits.CELL_BORDER_WIDTH_MILLIMETRES);\r
- toColumn++;\r
- }\r
- // De-crement by one the last column value.\r
- toColumn--;\r
- // Highly unlikely that this will be true but, if the width of a series\r
- // of columns is exactly equal to the required width of the image, then\r
- // simply build a ClientAnchorDetail object with an inset equal to the\r
- // total number of co-ordinate positions available in a column, a\r
- // from column co-ordinate (top left hand corner) equal to the value\r
- // of the startingColumn parameter and a to column co-ordinate equal\r
- // to the toColumn variable.\r
- //\r
- // Convert both values to ints to perform the test.\r
- if((int)totalWidthMM == (int)reqImageWidthMM) {\r
- // A problem could occur if the image is sized to fit into one or\r
- // more columns. If that occurs, the value in the toColumn variable\r
- // will be in error. To overcome this, there are two options, to\r
- // ibcrement the toColumn variable's value by one or to pass the\r
- // total number of co-ordinate positions to the third paramater\r
- // of the ClientAnchorDetail constructor. For no sepcific reason,\r
- // the latter option is used below.\r
- if(sheet instanceof HSSFSheet) {\r
- anchorDetail = new ClientAnchorDetail(startingColumn,\r
- toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS);\r
- }\r
- else {\r
- anchorDetail = new ClientAnchorDetail(startingColumn,\r
- toColumn, (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM);\r
- }\r
- }\r
- // In this case, the image will overlap part of another column and it is\r
- // necessary to calculate just how much - this will become the inset\r
- // for the ClientAnchorDetail object.\r
- else {\r
- // Firstly, claculate how much of the image should overlap into\r
- // the next column.\r
- overlapMM = reqImageWidthMM - (totalWidthMM - colWidthMM);\r
-\r
- // When the required size is very close indded to the column size,\r
- // the calcaulation above can produce a negative value. To prevent\r
- // problems occuring in later caculations, this is simply removed\r
- // be setting the overlapMM value to zero.\r
- if(overlapMM < 0) {\r
- overlapMM = 0.0D;\r
- }\r
-\r
- if(sheet instanceof HSSFSheet) {\r
- // Next, from the columns width, calculate how many co-ordinate\r
- // positons there are per millimetre\r
- coordinatePositionsPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS /\r
- colWidthMM;\r
- // From this figure, determine how many co-ordinat positions to\r
- // inset the left hand or bottom edge of the image.\r
- inset = (int)(coordinatePositionsPerMM * overlapMM);\r
- }\r
- else {\r
- inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM;\r
- }\r
-\r
- // Now create the ClientAnchorDetail object, setting the from and to\r
- // columns and the inset.\r
- anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, inset);\r
- }\r
- return(anchorDetail);\r
- }\r
-\r
- /**\r
- * If the image is to overlie more than one rows, calculations need to be\r
- * performed to determine how many rows and whether the image will\r
- * overlie just a part of one row in order to be presented at the\r
- * required size.\r
- *\r
- * @param sheet The sheet that will 'contain' the image.\r
- * @param startingRow A primitive int whose value is the index of the row\r
- * that contains the cell whose top left hand corner\r
- * should be aligned with the top left hand corner of\r
- * the image.\r
- * @param reqImageHeightMM A primitive double whose value will indicate the\r
- * required height of the image in millimetres.\r
- * @return An instance of the ClientAnchorDetail class that will contain\r
- * the index number of the row containing the cell whose top\r
- * left hand corner also defines the top left hand corner of the\r
- * image, the index number of the row containing the cell whose top\r
- * left hand corner also defines the bottom right hand corner of\r
- * the image and an inset that determines how far the bottom edge\r
- * can protrude into the next (lower) row - expressed as a specific\r
- * number of co-ordinate positions.\r
- */\r
- private ClientAnchorDetail calculateRowLocation(Sheet sheet,\r
- int startingRow, double reqImageHeightMM) {\r
- ClientAnchorDetail clientAnchorDetail = null;\r
- Row row = null;\r
- double rowHeightMM = 0.0D;\r
- double totalRowHeightMM = 0.0D;\r
- double overlapMM = 0.0D;\r
- double rowCoordinatesPerMM = 0.0D;\r
- int toRow = startingRow;\r
- int inset = 0;\r
-\r
- // Step through the rows in the sheet and accumulate a total of their\r
- // heights.\r
- while(totalRowHeightMM < reqImageHeightMM) {\r
- row = sheet.getRow(toRow);\r
- // Note, if the row does not already exist on the sheet then create\r
- // it here.\r
- if(row == null) {\r
- row = sheet.createRow(toRow);\r
- }\r
- // Get the row's height in millimetres and add to the running total.\r
- rowHeightMM = row.getHeightInPoints() /\r
- ConvertImageUnits.POINTS_PER_MILLIMETRE;\r
- totalRowHeightMM += rowHeightMM;\r
- toRow++;\r
- }\r
- // Owing to the way the loop above works, the rowNumber will have been\r
- // incremented one row too far. Undo that here.\r
- toRow--;\r
- // Check to see whether the image should occupy an exact number of\r
- // rows. If so, build the ClientAnchorDetail record to point\r
- // to those rows and with an inset of the total number of co-ordinate\r
- // position in the row.\r
- //\r
- // To overcome problems that can occur with comparing double values for\r
- // equality, cast both to int(s) to truncate the value; VERY crude and\r
- // I do not really like it!!\r
- if((int)totalRowHeightMM == (int)reqImageHeightMM) {\r
- if(sheet instanceof HSSFSheet) {\r
- clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow,\r
- ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS);\r
- }\r
- else {\r
- clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow,\r
- (int)reqImageHeightMM * AddDimensionedImage.EMU_PER_MM);\r
- }\r
- }\r
- else {\r
- // Calculate how far the image will project into the next row. Note\r
- // that the height of the last row assessed is subtracted from the\r
- // total height of all rows assessed so far.\r
- overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM);\r
-\r
- // To prevent an exception being thrown when the required width of\r
- // the image is very close indeed to the column size.\r
- if(overlapMM < 0) {\r
- overlapMM = 0.0D;\r
- }\r
-\r
- if(sheet instanceof HSSFSheet) {\r
- rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS /\r
- rowHeightMM;\r
- inset = (int)(overlapMM * rowCoordinatesPerMM);\r
- }\r
- else {\r
- inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM;\r
- }\r
- clientAnchorDetail = new ClientAnchorDetail(startingRow,\r
- toRow, inset);\r
- }\r
- return(clientAnchorDetail);\r
- }\r
-\r
- /**\r
- * The main entry point to the program. It contains code that demonstrates\r
- * one way to use the program.\r
- *\r
- * Note, the code is not restricted to use on new workbooks only. If an\r
- * image is to be inserted into an existing workbook. just open that\r
- * workbook, gat a reference to a sheet and pass that;\r
- *\r
- * AddDimensionedImage addImage = new AddDimensionedImage();\r
- *\r
- * File file = new File("....... Existing Workbook .......");\r
- * FileInputStream fis = new FileInputStream(file);\r
- * Workbook workbook = new HSSFWorkbook(fis);\r
- * HSSFSheet sheet = workbook.getSheetAt(0);\r
- * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20,\r
- * AddDimensionedImage.EXPAND.ROW);\r
- *\r
- * @param args the command line arguments\r
- */\r
- public static void main(String[] args) {\r
- String imageFile = null;\r
- String outputFile = null;\r
- FileOutputStream fos = null;\r
- Workbook workbook = null;\r
- Sheet sheet = null;\r
- try {\r
- if(args.length < 2){\r
- System.err.println("Usage: AddDimensionedImage imageFile outputFile");\r
- return;\r
- }\r
- workbook = new HSSFWorkbook(); // OR XSSFWorkbook\r
- sheet = workbook.createSheet("Picture Test");\r
- imageFile = args[0];\r
- outputFile = args[1];\r
- new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),\r
- new File(imageFile).toURI().toURL(), 100, 40,\r
- AddDimensionedImage.EXPAND_ROW_AND_COLUMN);\r
- fos = new FileOutputStream(outputFile);\r
- workbook.write(fos);\r
- }\r
- catch(FileNotFoundException fnfEx) {\r
- System.out.println("Caught an: " + fnfEx.getClass().getName());\r
- System.out.println("Message: " + fnfEx.getMessage());\r
- System.out.println("Stacktrace follows...........");\r
- fnfEx.printStackTrace(System.out);\r
- }\r
- catch(IOException ioEx) {\r
- System.out.println("Caught an: " + ioEx.getClass().getName());\r
- System.out.println("Message: " + ioEx.getMessage());\r
- System.out.println("Stacktrace follows...........");\r
- ioEx.printStackTrace(System.out);\r
- }\r
- finally {\r
- if(fos != null) {\r
- try {\r
- fos.close();\r
- fos = null;\r
- }\r
- catch(IOException ioEx) {\r
- // I G N O R E\r
- }\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * The HSSFClientAnchor class accepts eight arguments. In order, these are;\r
- *\r
- * * How far the left hand edge of the image is inset from the left hand\r
- * edge of the cell\r
- * * How far the top edge of the image is inset from the top of the cell\r
- * * How far the right hand edge of the image is inset from the left\r
- * hand edge of the cell\r
- * * How far the bottom edge of the image is inset from the top of the\r
- * cell.\r
- * * Together, arguments five and six determine the column and row\r
- * coordinates of the cell whose top left hand corner will be aligned\r
- * with the images top left hand corner.\r
- * * Together, arguments seven and eight determine the column and row\r
- * coordinates of the cell whose top left hand corner will be aligned\r
- * with the images bottom right hand corner.\r
- *\r
- * An instance of the ClientAnchorDetail class provides three of the eight\r
- * parameters, one of the coordinates for the images top left hand corner,\r
- * one of the coordinates for the images bottom right hand corner and\r
- * either how far the image should be inset from the top or the left hand\r
- * edge of the cell.\r
- *\r
- * @author Mark Beardsley [msb at apache.org]\r
- * @version 1.00 5th August 2009.\r
- */\r
- public class ClientAnchorDetail {\r
-\r
- public int fromIndex = 0;\r
- public int toIndex = 0;\r
- public int inset = 0;\r
-\r
- /**\r
- * Create a new instance of the ClientAnchorDetail class using the\r
- * following parameters.\r
- *\r
- * @param fromIndex A primitive int that contains one of the\r
- * coordinates (row or column index) for the top left\r
- * hand corner of the image.\r
- * @param toIndex A primitive int that contains one of the\r
- * coordinates (row or column index) for the bottom\r
- * right hand corner of the image.\r
- * @param inset A primitive int that contains a value which indicates\r
- * how far the image should be inset from the top or the\r
- * left hand edge of a cell.\r
- */\r
- public ClientAnchorDetail(int fromIndex, int toIndex, int inset) {\r
- this.fromIndex = fromIndex;\r
- this.toIndex = toIndex;\r
- this.inset = inset;\r
- }\r
-\r
- /**\r
- * Get one of the number of the column or row that contains the cell\r
- * whose top left hand corner will be aligned with the top left hand\r
- * corner of the image.\r
- *\r
- * @return The value - row or column index - for one of the coordinates\r
- * of the top left hand corner of the image.\r
- */\r
- public int getFromIndex() {\r
- return(this.fromIndex);\r
- }\r
-\r
- /**\r
- * Get one of the number of the column or row that contains the cell\r
- * whose top left hand corner will be aligned with the bottom right hand\r
- * corner of the image.\r
- *\r
- * @return The value - row or column index - for one of the coordinates\r
- * of the bottom right hand corner of the image.\r
- */\r
- public int getToIndex() {\r
- return(this.toIndex);\r
- }\r
-\r
- /**\r
- * Get the images offset from the edge of a cell.\r
- *\r
- * @return How far either the right hand or bottom edge of the image is\r
- * inset from the left hand or top edge of a cell.\r
- */\r
- public int getInset() {\r
- return(this.inset);\r
- }\r
- }\r
-\r
- /**\r
- * Utility methods used to convert Excels character based column and row\r
- * size measurements into pixels and/or millimetres. The class also contains\r
- * various constants that are required in other calculations.\r
- *\r
- * @author xio[darjino@hotmail.com]\r
- * @version 1.01 30th July 2009.\r
- * Added by Mark Beardsley [msb at apache.org].\r
- * Additional constants.\r
- * widthUnits2Millimetres() and millimetres2Units() methods.\r
- */\r
- public static class ConvertImageUnits {\r
-\r
- // Each cell conatins a fixed number of co-ordinate points; this number\r
- // does not vary with row height or column width or with font. These two\r
- // constants are defined below.\r
- public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB\r
- public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB\r
- // The resoultion of an image can be expressed as a specific number\r
- // of pixels per inch. Displays and printers differ but 96 pixels per\r
- // inch is an acceptable standard to beging with.\r
- public static final int PIXELS_PER_INCH = 96; // MB\r
- // Cnstants that defines how many pixels and points there are in a\r
- // millimetre. These values are required for the conversion algorithm.\r
- public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB\r
- public static final double POINTS_PER_MILLIMETRE = 2.83; // MB\r
- // The column width returned by HSSF and the width of a picture when\r
- // positioned to exactly cover one cell are different by almost exactly\r
- // 2mm - give or take rounding errors. This constant allows that\r
- // additional amount to be accounted for when calculating how many\r
- // celles the image ought to overlie.\r
- public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB\r
- public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;\r
- public static final int UNIT_OFFSET_LENGTH = 7;\r
- public static final int[] UNIT_OFFSET_MAP = new int[]\r
- { 0, 36, 73, 109, 146, 182, 219 };\r
-\r
- /**\r
- * pixel units to excel width units(units of 1/256th of a character width)\r
- * @param pxs\r
- * @return\r
- */\r
- public static short pixel2WidthUnits(int pxs) {\r
- short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR *\r
- (pxs / UNIT_OFFSET_LENGTH));\r
- widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];\r
- return widthUnits;\r
- }\r
-\r
- /**\r
- * excel width units(units of 1/256th of a character width) to pixel\r
- * units.\r
- *\r
- * @param widthUnits\r
- * @return\r
- */\r
- public static int widthUnits2Pixel(short widthUnits) {\r
- int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR)\r
- * UNIT_OFFSET_LENGTH;\r
- int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;\r
- pixels += Math.round(offsetWidthUnits /\r
- ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));\r
- return pixels;\r
- }\r
-\r
- /**\r
- * Convert Excels width units into millimetres.\r
- *\r
- * @param widthUnits The width of the column or the height of the\r
- * row in Excels units.\r
- * @return A primitive double that contains the columns width or rows\r
- * height in millimetres.\r
- */\r
- public static double widthUnits2Millimetres(short widthUnits) {\r
- return(ConvertImageUnits.widthUnits2Pixel(widthUnits) /\r
- ConvertImageUnits.PIXELS_PER_MILLIMETRES);\r
- }\r
-\r
- /**\r
- * Convert into millimetres Excels width units..\r
- *\r
- * @param millimetres A primitive double that contains the columns\r
- * width or rows height in millimetres.\r
- * @return A primitive int that contains the columns width or rows\r
- * height in Excels units.\r
- */\r
- public static int millimetres2WidthUnits(double millimetres) {\r
- return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres *\r
- ConvertImageUnits.PIXELS_PER_MILLIMETRES)));\r
- }\r
- \r
- public static int pointsToPixels(double points) {\r
- return (int) Math.round(points / 72D * PIXELS_PER_INCH);\r
- }\r
- \r
- public static double pointsToMillimeters(double points) {\r
- return points / 72D * 25.4;\r
- }\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/* ====================================================================\r
-Licensed to the Apache Software Foundation (ASF) under one or more\r
-contributor license agreements. See the NOTICE file distributed with\r
-this work for additional information regarding copyright ownership.\r
-The ASF licenses this file to You under the Apache License, Version 2.0\r
-(the "License"); you may not use this file except in compliance with\r
-the License. You may obtain a copy of the License at\r
-\r
-http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-Unless required by applicable law or agreed to in writing, software\r
-distributed under the License is distributed on an "AS IS" BASIS,\r
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-See the License for the specific language governing permissions and\r
-limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.ss.examples;\r
-\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-import org.apache.poi.ss.usermodel.*;\r
-import org.apache.poi.xssf.usermodel.*;\r
-\r
-/**\r
- * Shows how various alignment options work.\r
- */\r
-public class AligningCells {\r
-\r
- public static void main(String[] args) throws IOException {\r
- Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();\r
-\r
- Sheet sheet = wb.createSheet();\r
- Row row = sheet.createRow((short) 2);\r
- row.setHeightInPoints(30);\r
- for (int i = 0; i < 8; i++) {\r
- //column width is set in units of 1/256th of a character width\r
- sheet.setColumnWidth(i, 256 * 15);\r
- }\r
-\r
- createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);\r
- createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);\r
- createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);\r
- createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);\r
- createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);\r
- createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);\r
- createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);\r
-\r
- // Write the output to a file\r
- FileOutputStream fileOut = new FileOutputStream("ss-example-align.xlsx");\r
- wb.write(fileOut);\r
- fileOut.close();\r
- }\r
-\r
- /**\r
- * Creates a cell and aligns it a certain way.\r
- *\r
- * @param wb the workbook\r
- * @param row the row to create the cell in\r
- * @param column the column number to create the cell in\r
- * @param halign the horizontal alignment for the cell.\r
- */\r
- private static void createCell(Workbook wb, Row row, short column, short halign, short valign) {\r
- CreationHelper ch = wb.getCreationHelper();\r
- Cell cell = row.createCell(column);\r
- cell.setCellValue(ch.createRichTextString("Align It"));\r
- CellStyle cellStyle = wb.createCellStyle();\r
- cellStyle.setAlignment(halign);\r
- cellStyle.setVerticalAlignment(valign);\r
- cell.setCellStyle(cellStyle);\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb){
- Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
- 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;
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.
- * <pre>
- * Usage:
- * CalendarDemo -xls|xlsx <year>
- * </pre>
- *
- * @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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb){
- Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
-
- 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;
- }
-}
+++ /dev/null
-/* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.ss.examples;\r
-\r
-import java.io.File;\r
-\r
-import org.apache.poi.hssf.usermodel.HSSFFont;\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
-import org.apache.poi.hssf.util.HSSFColor;\r
-import org.apache.poi.ss.usermodel.Cell;\r
-import org.apache.poi.ss.usermodel.CellStyle;\r
-import org.apache.poi.ss.usermodel.Color;\r
-import org.apache.poi.ss.usermodel.DataFormatter;\r
-import org.apache.poi.ss.usermodel.Font;\r
-import org.apache.poi.ss.usermodel.Row;\r
-import org.apache.poi.ss.usermodel.Sheet;\r
-import org.apache.poi.ss.usermodel.Workbook;\r
-import org.apache.poi.ss.usermodel.WorkbookFactory;\r
-import org.apache.poi.ss.util.CellReference;\r
-import org.apache.poi.xssf.usermodel.XSSFColor;\r
-import org.apache.poi.xssf.usermodel.XSSFFont;\r
-\r
-/**\r
- * Demonstrates how to read excel styles for cells\r
- */\r
-public class CellStyleDetails {\r
- public static void main(String[] args) throws Exception {\r
- if(args.length == 0) {\r
- throw new IllegalArgumentException("Filename must be given");\r
- }\r
- \r
- Workbook wb = WorkbookFactory.create(new File(args[0]));\r
- DataFormatter formatter = new DataFormatter();\r
- \r
- for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {\r
- Sheet sheet = wb.getSheetAt(sn);\r
- System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());\r
- \r
- for(Row row : sheet) {\r
- System.out.println(" Row " + row.getRowNum());\r
- \r
- for(Cell cell : row) {\r
- CellReference ref = new CellReference(cell);\r
- System.out.print(" " + ref.formatAsString());\r
- System.out.print(" (" + cell.getColumnIndex() + ") ");\r
- \r
- CellStyle style = cell.getCellStyle();\r
- System.out.print("Format=" + style.getDataFormatString() + " ");\r
- System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");\r
- System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");\r
- \r
- Font font = wb.getFontAt( style.getFontIndex() );\r
- System.out.print("Font=" + font.getFontName() + " ");\r
- System.out.print("FontColor=");\r
- if(font instanceof HSSFFont) {\r
- System.out.print( renderColor( ((HSSFFont)font).getHSSFColor((HSSFWorkbook)wb)) );\r
- }\r
- if(font instanceof XSSFFont) {\r
- System.out.print( renderColor( ((XSSFFont)font).getXSSFColor()) );\r
- }\r
- \r
- System.out.println();\r
- System.out.println(" " + formatter.formatCellValue(cell));\r
- }\r
- }\r
- \r
- System.out.println();\r
- }\r
- }\r
- \r
- private static String renderColor(Color color) {\r
- if(color instanceof HSSFColor) {\r
- return ((HSSFColor)color).getHexString();\r
- } else if(color instanceof XSSFColor) {\r
- return ((XSSFColor)color).getARGBHex();\r
- } else {\r
- return "(none)";\r
- }\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ====================================================================\r
- */\r
-\r
-package org.apache.poi.ss.examples;\r
-\r
-import org.apache.poi.hssf.usermodel.*;\r
-import org.apache.poi.ss.usermodel.*;\r
-import org.apache.poi.ss.util.CellRangeAddress;\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
-\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-/**\r
- * Excel Conditional Formatting -- Examples\r
- *\r
- * <p>\r
- * Based on the code snippets from http://www.contextures.com/xlcondformat03.html\r
- * </p>\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class ConditionalFormats {\r
-\r
- public static void main(String[] args) throws IOException {\r
- Workbook wb;\r
-\r
- if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook();\r
- else wb = new XSSFWorkbook();\r
-\r
- sameCell(wb.createSheet("Same Cell"));\r
- multiCell(wb.createSheet("MultiCell"));\r
- errors(wb.createSheet("Errors"));\r
- hideDupplicates(wb.createSheet("Hide Dups"));\r
- formatDuplicates(wb.createSheet("Duplicates"));\r
- inList(wb.createSheet("In List"));\r
- expiry(wb.createSheet("Expiry"));\r
- shadeAlt(wb.createSheet("Shade Alt"));\r
- shadeBands(wb.createSheet("Shade Bands"));\r
-\r
- // Write the output to a file\r
- String file = "cf-poi.xls";\r
- if(wb instanceof XSSFWorkbook) file += "x";\r
- FileOutputStream out = new FileOutputStream(file);\r
- wb.write(out);\r
- out.close();\r
-\r
- }\r
-\r
- /**\r
- * Highlight cells based on their values\r
- */\r
- static void sameCell(Sheet sheet) {\r
- sheet.createRow(0).createCell(0).setCellValue(84);\r
- sheet.createRow(1).createCell(0).setCellValue(74);\r
- sheet.createRow(2).createCell(0).setCellValue(50);\r
- sheet.createRow(3).createCell(0).setCellValue(51);\r
- sheet.createRow(4).createCell(0).setCellValue(49);\r
- sheet.createRow(5).createCell(0).setCellValue(41);\r
-\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- // Condition 1: Cell Value Is greater than 70 (Blue Fill)\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.GT, "70");\r
- PatternFormatting fill1 = rule1.createPatternFormatting();\r
- fill1.setFillBackgroundColor(IndexedColors.BLUE.index);\r
- fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
-\r
- // Condition 2: Cell Value Is less than 50 (Green Fill)\r
- ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.LT, "50");\r
- PatternFormatting fill2 = rule2.createPatternFormatting();\r
- fill2.setFillBackgroundColor(IndexedColors.GREEN.index);\r
- fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A1:A6")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1, rule2);\r
-\r
- sheet.getRow(0).createCell(2).setCellValue("<== Condition 1: Cell Value Is greater than 70 (Blue Fill)");\r
- sheet.getRow(4).createCell(2).setCellValue("<== Condition 2: Cell Value Is less than 50 (Green Fill)");\r
- }\r
-\r
- /**\r
- * Highlight multiple cells based on a formula\r
- */\r
- static void multiCell(Sheet sheet) {\r
- // header row\r
- Row row0 = sheet.createRow(0);\r
- row0.createCell(0).setCellValue("Units");\r
- row0.createCell(1).setCellValue("Cost");\r
- row0.createCell(2).setCellValue("Total");\r
-\r
- Row row1 = sheet.createRow(1);\r
- row1.createCell(0).setCellValue(71);\r
- row1.createCell(1).setCellValue(29);\r
- row1.createCell(2).setCellValue(2059);\r
-\r
- Row row2 = sheet.createRow(2);\r
- row2.createCell(0).setCellValue(85);\r
- row2.createCell(1).setCellValue(29);\r
- row2.createCell(2).setCellValue(2059);\r
-\r
- Row row3 = sheet.createRow(3);\r
- row3.createCell(0).setCellValue(71);\r
- row3.createCell(1).setCellValue(29);\r
- row3.createCell(2).setCellValue(2059);\r
-\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- // Condition 1: Formula Is =$B2>75 (Blue Fill)\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("$A2>75");\r
- PatternFormatting fill1 = rule1.createPatternFormatting();\r
- fill1.setFillBackgroundColor(IndexedColors.BLUE.index);\r
- fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A2:C4")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1);\r
-\r
- sheet.getRow(2).createCell(4).setCellValue("<== Condition 1: Formula Is =$B2>75 (Blue Fill)");\r
- }\r
-\r
- /**\r
- * Use Excel conditional formatting to check for errors,\r
- * and change the font colour to match the cell colour.\r
- * In this example, if formula result is #DIV/0! then it will have white font colour.\r
- */\r
- static void errors(Sheet sheet) {\r
- sheet.createRow(0).createCell(0).setCellValue(84);\r
- sheet.createRow(1).createCell(0).setCellValue(0);\r
- sheet.createRow(2).createCell(0).setCellFormula("ROUND(A1/A2,0)");\r
- sheet.createRow(3).createCell(0).setCellValue(0);\r
- sheet.createRow(4).createCell(0).setCellFormula("ROUND(A6/A4,0)");\r
- sheet.createRow(5).createCell(0).setCellValue(41);\r
-\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- // Condition 1: Formula Is =ISERROR(C2) (White Font)\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("ISERROR(A1)");\r
- FontFormatting font = rule1.createFontFormatting();\r
- font.setFontColorIndex(IndexedColors.WHITE.index);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A1:A6")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1);\r
-\r
- sheet.getRow(2).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)");\r
- sheet.getRow(4).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)");\r
- }\r
-\r
- /**\r
- * Use Excel conditional formatting to hide the duplicate values,\r
- * and make the list easier to read. In this example, when the table is sorted by Region,\r
- * the second (and subsequent) occurences of each region name will have white font colour.\r
- */\r
- static void hideDupplicates(Sheet sheet) {\r
- sheet.createRow(0).createCell(0).setCellValue("City");\r
- sheet.createRow(1).createCell(0).setCellValue("Boston");\r
- sheet.createRow(2).createCell(0).setCellValue("Boston");\r
- sheet.createRow(3).createCell(0).setCellValue("Chicago");\r
- sheet.createRow(4).createCell(0).setCellValue("Chicago");\r
- sheet.createRow(5).createCell(0).setCellValue("New York");\r
-\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- // Condition 1: Formula Is =A2=A1 (White Font)\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("A2=A1");\r
- FontFormatting font = rule1.createFontFormatting();\r
- font.setFontColorIndex(IndexedColors.WHITE.index);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A2:A6")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1);\r
-\r
- sheet.getRow(1).createCell(1).setCellValue("<== the second (and subsequent) " +\r
- "occurences of each region name will have white font colour. " +\r
- "Condition: Formula Is =A2=A1 (White Font)");\r
- }\r
-\r
- /**\r
- * Use Excel conditional formatting to highlight duplicate entries in a column.\r
- */\r
- static void formatDuplicates(Sheet sheet) {\r
- sheet.createRow(0).createCell(0).setCellValue("Code");\r
- sheet.createRow(1).createCell(0).setCellValue(4);\r
- sheet.createRow(2).createCell(0).setCellValue(3);\r
- sheet.createRow(3).createCell(0).setCellValue(6);\r
- sheet.createRow(4).createCell(0).setCellValue(3);\r
- sheet.createRow(5).createCell(0).setCellValue(5);\r
- sheet.createRow(6).createCell(0).setCellValue(8);\r
- sheet.createRow(7).createCell(0).setCellValue(0);\r
- sheet.createRow(8).createCell(0).setCellValue(2);\r
- sheet.createRow(9).createCell(0).setCellValue(8);\r
- sheet.createRow(10).createCell(0).setCellValue(6);\r
-\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- // Condition 1: Formula Is =A2=A1 (White Font)\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($A$2:$A$11,A2)>1");\r
- FontFormatting font = rule1.createFontFormatting();\r
- font.setFontStyle(false, true);\r
- font.setFontColorIndex(IndexedColors.BLUE.index);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A2:A11")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1);\r
-\r
- sheet.getRow(2).createCell(1).setCellValue("<== Duplicates numbers in the column are highlighted. " +\r
- "Condition: Formula Is =COUNTIF($A$2:$A$11,A2)>1 (Blue Font)");\r
- }\r
-\r
- /**\r
- * Use Excel conditional formatting to highlight items that are in a list on the worksheet.\r
- */\r
- static void inList(Sheet sheet) {\r
- sheet.createRow(0).createCell(0).setCellValue("Codes");\r
- sheet.createRow(1).createCell(0).setCellValue("AA");\r
- sheet.createRow(2).createCell(0).setCellValue("BB");\r
- sheet.createRow(3).createCell(0).setCellValue("GG");\r
- sheet.createRow(4).createCell(0).setCellValue("AA");\r
- sheet.createRow(5).createCell(0).setCellValue("FF");\r
- sheet.createRow(6).createCell(0).setCellValue("XX");\r
- sheet.createRow(7).createCell(0).setCellValue("CC");\r
-\r
- sheet.getRow(0).createCell(2).setCellValue("Valid");\r
- sheet.getRow(1).createCell(2).setCellValue("AA");\r
- sheet.getRow(2).createCell(2).setCellValue("BB");\r
- sheet.getRow(3).createCell(2).setCellValue("CC");\r
-\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- // Condition 1: Formula Is =A2=A1 (White Font)\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($C$2:$C$4,A2)");\r
- PatternFormatting fill1 = rule1.createPatternFormatting();\r
- fill1.setFillBackgroundColor(IndexedColors.LIGHT_BLUE.index);\r
- fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A2:A8")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1);\r
-\r
- sheet.getRow(2).createCell(3).setCellValue("<== Use Excel conditional formatting to highlight items that are in a list on the worksheet");\r
- }\r
-\r
- /**\r
- * Use Excel conditional formatting to highlight payments that are due in the next thirty days.\r
- * In this example, Due dates are entered in cells A2:A4.\r
- */\r
- static void expiry(Sheet sheet) {\r
- CellStyle style = sheet.getWorkbook().createCellStyle();\r
- style.setDataFormat((short)BuiltinFormats.getBuiltinFormat("d-mmm"));\r
-\r
- sheet.createRow(0).createCell(0).setCellValue("Date");\r
- sheet.createRow(1).createCell(0).setCellFormula("TODAY()+29");\r
- sheet.createRow(2).createCell(0).setCellFormula("A2+1");\r
- sheet.createRow(3).createCell(0).setCellFormula("A3+1");\r
-\r
- for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style);\r
-\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- // Condition 1: Formula Is =A2=A1 (White Font)\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("AND(A2-TODAY()>=0,A2-TODAY()<=30)");\r
- FontFormatting font = rule1.createFontFormatting();\r
- font.setFontStyle(false, true);\r
- font.setFontColorIndex(IndexedColors.BLUE.index);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A2:A4")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1);\r
-\r
- sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted");\r
- }\r
-\r
- /**\r
- * Use Excel conditional formatting to shade alternating rows on the worksheet\r
- */\r
- static void shadeAlt(Sheet sheet) {\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- // Condition 1: Formula Is =A2=A1 (White Font)\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)");\r
- PatternFormatting fill1 = rule1.createPatternFormatting();\r
- fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);\r
- fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A1:Z100")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1);\r
-\r
- sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows");\r
- sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),2) (Light Green Fill)");\r
- }\r
-\r
- /**\r
- * You can use Excel conditional formatting to shade bands of rows on the worksheet. \r
- * In this example, 3 rows are shaded light grey, and 3 are left with no shading.\r
- * In the MOD function, the total number of rows in the set of banded rows (6) is entered.\r
- */\r
- static void shadeBands(Sheet sheet) {\r
- SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
-\r
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),6)<3");\r
- PatternFormatting fill1 = rule1.createPatternFormatting();\r
- fill1.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index);\r
- fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);\r
-\r
- CellRangeAddress[] regions = {\r
- CellRangeAddress.valueOf("A1:Z100")\r
- };\r
-\r
- sheetCF.addConditionalFormatting(regions, rule1);\r
-\r
- sheet.createRow(0).createCell(1).setCellValue("Shade Bands of Rows");\r
- sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),6)<2 (Light Grey Fill)");\r
- }\r
-}\r
+++ /dev/null
- /* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
- ==================================================================== */\r
-\r
-package org.apache.poi.ss.examples;\r
-import java.io.*;\r
-import org.apache.poi.xssf.usermodel.*;\r
-import org.apache.poi.hssf.usermodel.*;\r
-import org.apache.poi.ss.usermodel.*;\r
-import org.apache.poi.ss.util.CellRangeAddressList;\r
-\r
-/**\r
- * Demonstrates one technique that may be used to create linked or dependent\r
- * drop down lists. This refers to a situation in which the selection made\r
- * in one drop down list affects the options that are displayed in the second\r
- * or subsequent drop down list(s). In this example, the value the user selects\r
- * from the down list in cell A1 will affect the values displayed in the linked\r
- * drop down list in cell B1. For the sake of simplicity, the data for the drop\r
- * down lists is included on the same worksheet but this does not have to be the\r
- * case; the data could appear on a separate sheet. If this were done, then the\r
- * names for the regions would have to be different, they would have to include\r
- * the name of the sheet.\r
- * \r
- * There are two keys to this technique. The first is the use of named area or \r
- * regions of cells to hold the data for the drop down lists and the second is\r
- * making use of the INDIRECT() function to convert a name into the addresses\r
- * of the cells it refers to.\r
- * \r
- * Note that whilst this class builds just two linked drop down lists, there is\r
- * nothing to prevent more being created. Quite simply, use the value selected\r
- * by the user in one drop down list to determine what is shown in another and the\r
- * value selected in that drop down list to determine what is shown in a third,\r
- * and so on. Also, note that the data for the drop down lists is contained on\r
- * contained on the same sheet as the validations themselves. This is done simply\r
- * for simplicity and there is nothing to prevent a separate sheet being created\r
- * and used to hold the data. If this is done then problems may be encountered\r
- * if the sheet is opened with OpenOffice Calc. To prevent these problems, it is\r
- * better to include the name of the sheet when calling the setRefersToFormula()\r
- * method.\r
- *\r
- * @author Mark Beardsley [msb at apache.org]\r
- * @version 1.00 30th March 2012\r
- */\r
-public class LinkedDropDownLists {\r
-\r
- LinkedDropDownLists(String workbookName) {\r
- File file = null;\r
- FileOutputStream fos = null;\r
- Workbook workbook = null;\r
- Sheet sheet = null;\r
- DataValidationHelper dvHelper = null;\r
- DataValidationConstraint dvConstraint = null;\r
- DataValidation validation = null;\r
- CellRangeAddressList addressList = null;\r
- try {\r
-\r
- // Using the ss.usermodel allows this class to support both binary\r
- // and xml based workbooks. The choice of which one to create is\r
- // made by checking the file extension.\r
- if (workbookName.endsWith(".xlsx")) {\r
- workbook = new XSSFWorkbook();\r
- } else {\r
- workbook = new HSSFWorkbook();\r
- }\r
- \r
- // Build the sheet that will hold the data for the validations. This\r
- // must be done first as it will create names that are referenced \r
- // later.\r
- sheet = workbook.createSheet("Linked Validations");\r
- LinkedDropDownLists.buildDataSheet(sheet);\r
-\r
- // Build the first data validation to occupy cell A1. Note\r
- // that it retrieves it's data from the named area or region called\r
- // CHOICES. Further information about this can be found in the\r
- // static buildDataSheet() method below.\r
- addressList = new CellRangeAddressList(0, 0, 0, 0);\r
- dvHelper = sheet.getDataValidationHelper();\r
- dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");\r
- validation = dvHelper.createValidation(dvConstraint, addressList);\r
- sheet.addValidationData(validation);\r
- \r
- // Now, build the linked or dependent drop down list that will\r
- // occupy cell B1. The key to the whole process is the use of the\r
- // INDIRECT() function. In the buildDataSheet(0 method, a series of\r
- // named regions are created and the names of three of them mirror\r
- // the options available to the user in the first drop down list\r
- // (in cell A1). Using the INDIRECT() function makes it possible\r
- // to convert the selection the user makes in that first drop down\r
- // into the addresses of a named region of cells and then to use\r
- // those cells to populate the second drop down list.\r
- addressList = new CellRangeAddressList(0, 0, 1, 1);\r
- dvConstraint = dvHelper.createFormulaListConstraint(\r
- "INDIRECT(UPPER($A$1))");\r
- validation = dvHelper.createValidation(dvConstraint, addressList);\r
- sheet.addValidationData(validation);\r
- \r
- file = new File(workbookName);\r
- fos = new FileOutputStream(file);\r
- workbook.write(fos);\r
- } catch (IOException ioEx) {\r
- System.out.println("Caught a: " + ioEx.getClass().getName());\r
- System.out.println("Message: " + ioEx.getMessage());\r
- System.out.println("Stacktrace follws:.....");\r
- ioEx.printStackTrace(System.out);\r
- } finally {\r
- try {\r
- if (fos != null) {\r
- fos.close();\r
- fos = null;\r
- }\r
- } catch (IOException ioEx) {\r
- System.out.println("Caught a: " + ioEx.getClass().getName());\r
- System.out.println("Message: " + ioEx.getMessage());\r
- System.out.println("Stacktrace follws:.....");\r
- ioEx.printStackTrace(System.out);\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Called to populate the named areas/regions. The contents of the cells on\r
- * row one will be used to populate the first drop down list. The contents of\r
- * the cells on rows two, three and four will be used to populate the second\r
- * drop down list, just which row will be determined by the choice the user\r
- * makes in the first drop down list.\r
- * \r
- * In all cases, the approach is to create a row, create and populate cells\r
- * with data and then specify a name that identifies those cells. With the\r
- * exception of the first range, the names that are chosen for each range\r
- * of cells are quite important. In short, each of the options the user \r
- * could select in the first drop down list is used as the name for another\r
- * range of cells. Thus, in this example, the user can select either \r
- * 'Animal', 'Vegetable' or 'Mineral' in the first drop down and so the\r
- * sheet contains ranges named 'ANIMAL', 'VEGETABLE' and 'MINERAL'.\r
- * \r
- * @param dataSheet An instance of a class that implements the Sheet Sheet\r
- * interface (HSSFSheet or XSSFSheet).\r
- */\r
- private static final void buildDataSheet(Sheet dataSheet) {\r
- Row row = null;\r
- Cell cell = null;\r
- Name name = null;\r
-\r
- // The first row will hold the data for the first validation.\r
- row = dataSheet.createRow(10);\r
- cell = row.createCell(0);\r
- cell.setCellValue("Animal");\r
- cell = row.createCell(1);\r
- cell.setCellValue("Vegetable");\r
- cell = row.createCell(2);\r
- cell.setCellValue("Mineral");\r
- name = dataSheet.getWorkbook().createName();\r
- name.setRefersToFormula("$A$11:$C$11");\r
- name.setNameName("CHOICES");\r
-\r
- // The next three rows will hold the data that will be used to\r
- // populate the second, or linked, drop down list.\r
- row = dataSheet.createRow(11);\r
- cell = row.createCell(0);\r
- cell.setCellValue("Lion");\r
- cell = row.createCell(1);\r
- cell.setCellValue("Tiger");\r
- cell = row.createCell(2);\r
- cell.setCellValue("Leopard");\r
- cell = row.createCell(3);\r
- cell.setCellValue("Elephant");\r
- cell = row.createCell(4);\r
- cell.setCellValue("Eagle");\r
- cell = row.createCell(5);\r
- cell.setCellValue("Horse");\r
- cell = row.createCell(6);\r
- cell.setCellValue("Zebra");\r
- name = dataSheet.getWorkbook().createName();\r
- name.setRefersToFormula("$A$12:$G$12");\r
- name.setNameName("ANIMAL");\r
-\r
- row = dataSheet.createRow(12);\r
- cell = row.createCell(0);\r
- cell.setCellValue("Cabbage");\r
- cell = row.createCell(1);\r
- cell.setCellValue("Cauliflower");\r
- cell = row.createCell(2);\r
- cell.setCellValue("Potato");\r
- cell = row.createCell(3);\r
- cell.setCellValue("Onion");\r
- cell = row.createCell(4);\r
- cell.setCellValue("Beetroot");\r
- cell = row.createCell(5);\r
- cell.setCellValue("Asparagus");\r
- cell = row.createCell(6);\r
- cell.setCellValue("Spinach");\r
- cell = row.createCell(7);\r
- cell.setCellValue("Chard");\r
- name = dataSheet.getWorkbook().createName();\r
- name.setRefersToFormula("$A$13:$H$13");\r
- name.setNameName("VEGETABLE");\r
-\r
- row = dataSheet.createRow(13);\r
- cell = row.createCell(0);\r
- cell.setCellValue("Bauxite");\r
- cell = row.createCell(1);\r
- cell.setCellValue("Quartz");\r
- cell = row.createCell(2);\r
- cell.setCellValue("Feldspar");\r
- cell = row.createCell(3);\r
- cell.setCellValue("Shist");\r
- cell = row.createCell(4);\r
- cell.setCellValue("Shale");\r
- cell = row.createCell(5);\r
- cell.setCellValue("Mica");\r
- name = dataSheet.getWorkbook().createName();\r
- name.setRefersToFormula("$A$14:$F$14");\r
- name.setNameName("MINERAL");\r
- }\r
-}\r
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb){
- Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
-
- 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)");
- }
-}
+++ /dev/null
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF 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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb) {
- Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
- 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;
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<String, CellStyle> 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<String, CellStyle> createStyles(Workbook wb){
- Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
- 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;
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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 <em>one</em> way to convert an Excel spreadsheet into a CSV
- * file. This class makes the following assumptions;
- * <list>
- * <li>1. Where the Excel workbook contains more that one worksheet, then a single
- * CSV file will contain the data from all of the worksheets.</li>
- * <li>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 - ,,.</li>
- * <li>3. Empty fields will represent missing cells.</li>
- * <li>4. A record consisting of empty fields will be used to represent an empty row
- * in the Excel workbook.</li>
- * </list>
- * Therefore, if the worksheet looked like this;
- *
- * <pre>
- * ___________________________________________
- * | | | | | |
- * | A | B | C | D | E |
- * ___|_______|_______|_______|_______|_______|
- * | | | | | |
- * 1 | 1 | 2 | 3 | 4 | 5 |
- * ___|_______|_______|_______|_______|_______|
- * | | | | | |
- * 2 | | | | | |
- * ___|_______|_______|_______|_______|_______|
- * | | | | | |
- * 3 | | A | | B | |
- * ___|_______|_______|_______|_______|_______|
- * | | | | | |
- * 4 | | | | | Z |
- * ___|_______|_______|_______|_______|_______|
- * | | | | | |
- * 5 | 1,400 | | 250 | | |
- * ___|_______|_______|_______|_______|_______|
- *
- * </pre>
- *
- * Then, the resulting CSV file will contain the following lines (records);
- * <pre>
- * 1,2,3,4,5
- * ,,,,
- * ,A,,B,
- * ,,,,Z
- * "1,400",,250,,
- * </pre><p>
- * 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.
- * </p><p>
- * 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.
- * </p><p>
- * 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.
- * </p><p>
- * 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".
- * </p><p>
- * 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.
- * </p>
- * @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<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<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<String> 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<String> csvLine = new ArrayList<String>();
-
- // 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 <em>"Hello" he said</em> then it should be modified
- * to appear as <em>"""Hello"" he said"</em>. Furthermore, if the field
- * contains either embedded separator or EOL characters, it should also
- * be surrounded with speech marks. As a result <em>1,400</em> would become
- * <em>"1,400"</em> 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"));
- }
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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 <tt>result</tt> is <tt>NaN</> or <tt>Infinity</tt>
- */
- private void checkValue(double result) throws EvaluationException {
- if (Double.isNaN(result) || Double.isInfinite(result)) {
- throw new EvaluationException(ErrorEval.NUM_ERROR);
- }
- }
-}
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ====================================================================\r
- */\r
-\r
-package org.apache.poi.ss.examples.formula;\r
-\r
-import org.apache.poi.ss.formula.OperationEvaluationContext;\r
-import org.apache.poi.ss.formula.eval.ErrorEval;\r
-import org.apache.poi.ss.formula.eval.ValueEval;\r
-import org.apache.poi.ss.formula.functions.FreeRefFunction;\r
-import org.apache.poi.ss.formula.udf.UDFFinder;\r
-import org.apache.poi.ss.usermodel.Row;\r
-import org.apache.poi.ss.usermodel.Sheet;\r
-import org.apache.poi.ss.usermodel.Workbook;\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
-\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-/**\r
- * Demonstrates how to use functions provided by third-party add-ins, e.g. Bloomberg Excel Add-in.\r
- *\r
- * There can be situations when you are not interested in formula evaluation,\r
- * you just need to set the formula and the workbook will be evaluation by the client.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class SettingExternalFunction {\r
-\r
- /**\r
- * wrap external functions in a plugin\r
- */\r
- public static class BloombergAddIn implements UDFFinder {\r
- private final Map<String, FreeRefFunction> _functionsByName;\r
-\r
- public BloombergAddIn() {\r
- // dummy function that returns NA\r
- // don't care about the implementation, we are not interested in evaluation\r
- // and this method will never be called\r
- FreeRefFunction NA = new FreeRefFunction() {\r
- public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {\r
- return ErrorEval.NA;\r
- }\r
- };\r
- _functionsByName = new HashMap<String, FreeRefFunction>();\r
- _functionsByName.put("BDP", NA);\r
- _functionsByName.put("BDH", NA);\r
- _functionsByName.put("BDS", NA);\r
- }\r
-\r
- public FreeRefFunction findFunction(String name) {\r
- return _functionsByName.get(name.toUpperCase());\r
- }\r
-\r
- }\r
-\r
- public static void main( String[] args ) throws IOException {\r
-\r
- Workbook wb = new XSSFWorkbook(); // or new HSSFWorkbook()\r
-\r
- // register the add-in\r
- wb.addToolPack(new BloombergAddIn());\r
-\r
- Sheet sheet = wb.createSheet();\r
- Row row = sheet.createRow(0);\r
- row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100");\r
- row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") ");\r
- row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") ");\r
-\r
- FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx");\r
- wb.write(out);\r
- out.close();\r
-\r
- }\r
-\r
-}\r
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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);
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<Short, String> 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<Short, String> VERTICAL_ALIGN = mapFor(
- VERTICAL_BOTTOM, "bottom", VERTICAL_CENTER, "middle", VERTICAL_TOP,
- "top");
-
- private static final Map<Short, String> 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 <K, V> Map<K, V> mapFor(Object... mapping) {
- Map<K, V> map = new HashMap<K, V>();
- 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 "<tt>.xlsx</tt>" 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(
- "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>%n");
- out.format("<html>%n");
- out.format("<head>%n");
- out.format("</head>%n");
- out.format("<body>%n");
- }
-
- print();
-
- if (completeHTML) {
- out.format("</body>%n");
- out.format("</html>%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("<link href=\"excelStyle.css\" rel=\"stylesheet\" type=\"text/css\">%n");
- out.format("<style type=\"text/css\">%n");
- printStyles();
- out.format("</style>%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<CellStyle> seen = new HashSet<CellStyle>();
- for (int i = 0; i < wb.getNumberOfSheets(); i++) {
- Sheet sheet = wb.getSheetAt(i);
- Iterator<Row> 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 <K> void styleOut(String attr, K key, Map<K, String> 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("<table class=%s>%n", DEFAULTS_CLASS);
- printCols(sheet);
- printSheetContent(sheet);
- out.format("</table>%n");
- }
-
- private void printCols(Sheet sheet) {
- out.format("<col/>%n");
- ensureColumnBounds(sheet);
- for (int i = firstColumn; i < endColumn; i++) {
- out.format("<col/>%n");
- }
- }
-
- private void ensureColumnBounds(Sheet sheet) {
- if (gotBounds)
- return;
-
- Iterator<Row> 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("<thead>%n");
- out.format(" <tr class=%s>%n", COL_HEAD_CLASS);
- out.format(" <th class=%s>◊</th>%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(" <th class=%s>%s</th>%n", COL_HEAD_CLASS, colName);
- }
- out.format(" </tr>%n");
- out.format("</thead>%n");
- }
-
- private void printSheetContent(Sheet sheet) {
- printColumnHeads();
-
- out.format("<tbody>%n");
- Iterator<Row> rows = sheet.rowIterator();
- while (rows.hasNext()) {
- Row row = rows.next();
-
- out.format(" <tr>%n");
- out.format(" <td class=%s>%d</td>%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(" <td class=%s %s>%s</td>%n", styleName(style),
- attrs, content);
- }
- out.format(" </tr>%n");
- }
- out.format("</tbody>%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
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<Integer,HSSFColor> 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
+++ /dev/null
-/*
- ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT 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;
-}
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<!--
- ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ====================================================================
--->
-<html>
-<head>
-</head>
-<body>
-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.
-</body>
-</html>
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-\r
-import java.awt.*;\r
-import java.awt.geom.Rectangle2D;\r
-import java.io.FileInputStream;\r
-import java.io.InputStream;\r
-import java.util.List;\r
-\r
-/**\r
- * Demonstrates how you can extract data from a .pptx file\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public final class DataExtraction {\r
-\r
- public static void main(String args[]) throws Exception {\r
-\r
- if (args.length == 0) {\r
- System.out.println("Input file is required");\r
- return;\r
- }\r
-\r
- FileInputStream is = new FileInputStream(args[0]);\r
- XMLSlideShow ppt = new XMLSlideShow(is);\r
- is.close();\r
-\r
- // Get the document's embedded files.\r
- List<PackagePart> embeds = ppt.getAllEmbedds();\r
- for (PackagePart p : embeds) {\r
- String type = p.getContentType();\r
- String name = p.getPartName().getName(); //typically file name\r
- \r
- InputStream pIs = p.getInputStream();\r
- // make sense of the part data\r
- pIs.close();\r
- \r
- }\r
-\r
- // Get the document's embedded files.\r
- List<XSLFPictureData> images = ppt.getAllPictures();\r
- for (XSLFPictureData data : images) {\r
- PackagePart p = data.getPackagePart();\r
-\r
- String type = p.getContentType();\r
- String name = data.getFileName();\r
-\r
- InputStream pIs = p.getInputStream();\r
- // make sense of the image data\r
- pIs.close();\r
-\r
-\r
-\r
- }\r
-\r
- Dimension pageSize = ppt.getPageSize(); // size of the canvas in points\r
- for(XSLFSlide slide : ppt.getSlides()) {\r
- for(XSLFShape shape : slide){\r
- Rectangle2D anchor = shape.getAnchor(); // position on the canvas\r
- if(shape instanceof XSLFTextShape) {\r
- XSLFTextShape txShape = (XSLFTextShape)shape;\r
- System.out.println(txShape.getText());\r
- } else if (shape instanceof XSLFPictureShape){\r
- XSLFPictureShape pShape = (XSLFPictureShape)shape;\r
- XSLFPictureData pData = pShape.getPictureData();\r
- System.out.println(pData.getFileName());\r
- } else {\r
- System.out.println("Process me: " + shape.getClass());\r
- }\r
- }\r
- }\r
- }\r
-\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import java.io.FileInputStream;\r
-import java.io.FileOutputStream;\r
-\r
-/**\r
- * Merge multiple pptx presentations together\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public final class MergePresentations {\r
-\r
- public static void main(String args[]) throws Exception {\r
- XMLSlideShow ppt = new XMLSlideShow();\r
-\r
- for(String arg : args){\r
- FileInputStream is = new FileInputStream(arg);\r
- XMLSlideShow src = new XMLSlideShow(is);\r
- is.close();\r
-\r
- for(XSLFSlide srcSlide : src.getSlides()){\r
- ppt.createSlide().importContent(srcSlide);\r
- }\r
- }\r
-\r
- FileOutputStream out = new FileOutputStream("merged.pptx");\r
- ppt.write(out);\r
- out.close();\r
- }\r
-\r
-}\r
+++ /dev/null
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF 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 <pptx file>");
- }
-
- 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());
- }
- }
-
- }
-}
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ====================================================================\r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import org.apache.poi.POIXMLDocumentPart;\r
-import org.apache.poi.ss.util.CellRangeAddress;\r
-import org.apache.poi.ss.util.CellReference;\r
-import org.apache.poi.xssf.usermodel.XSSFRow;\r
-import org.apache.poi.xssf.usermodel.XSSFSheet;\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieChart;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieSer;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData;\r
-import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal;\r
-\r
-import java.io.BufferedReader;\r
-import java.io.FileInputStream;\r
-import java.io.FileOutputStream;\r
-import java.io.FileReader;\r
-import java.io.OutputStream;\r
-\r
-/**\r
- * Build a pie chart from a template pptx\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class PieChartDemo {\r
- private static void usage(){\r
- System.out.println("Usage: PieChartDemo <pie-chart-template.pptx> <pie-chart-data.txt>");\r
- System.out.println(" pie-chart-template.pptx template with a pie chart");\r
- System.out.println(" pie-chart-data.txt the model to set. First line is chart title, " +\r
- "then go pairs {axis-label value}");\r
- }\r
-\r
- public static void main(String[] args) throws Exception {\r
- if(args.length < 2) {\r
- usage();\r
- return;\r
- }\r
-\r
- BufferedReader modelReader = new BufferedReader(new FileReader(args[1]));\r
-\r
- String chartTitle = modelReader.readLine(); // first line is chart title\r
-\r
- XMLSlideShow pptx = new XMLSlideShow(new FileInputStream(args[0]));\r
- XSLFSlide slide = pptx.getSlides()[0];\r
-\r
- // find chart in the slide\r
- XSLFChart chart = null;\r
- for(POIXMLDocumentPart part : slide.getRelations()){\r
- if(part instanceof XSLFChart){\r
- chart = (XSLFChart) part;\r
- break;\r
- }\r
- }\r
-\r
- if(chart == null) throw new IllegalStateException("chart not found in the template");\r
-\r
- // embedded Excel workbook that holds the chart data\r
- POIXMLDocumentPart xlsPart = chart.getRelations().get(0);\r
- XSSFWorkbook wb = new XSSFWorkbook();\r
- XSSFSheet sheet = wb.createSheet();\r
-\r
- CTChart ctChart = chart.getCTChart();\r
- CTPlotArea plotArea = ctChart.getPlotArea();\r
-\r
- CTPieChart pieChart = plotArea.getPieChartArray(0);\r
- //Pie Chart Series\r
- CTPieSer ser = pieChart.getSerArray(0);\r
-\r
- // Series Text\r
- CTSerTx tx = ser.getTx();\r
- tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle);\r
- sheet.createRow(0).createCell(1).setCellValue(chartTitle);\r
- String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString();\r
- tx.getStrRef().setF(titleRef);\r
-\r
-\r
- // Category Axis Data\r
- CTAxDataSource cat = ser.getCat();\r
- CTStrData strData = cat.getStrRef().getStrCache();\r
-\r
- // Values\r
- CTNumDataSource val = ser.getVal();\r
- CTNumData numData = val.getNumRef().getNumCache();\r
-\r
- strData.setPtArray(null); // unset old axis text\r
- numData.setPtArray(null); // unset old values\r
-\r
-\r
- // set model\r
- int idx = 0;\r
- int rownum = 1;\r
- String ln;\r
- while((ln = modelReader.readLine()) != null){\r
- String[] vals = ln.split("\\s+");\r
- CTNumVal numVal = numData.addNewPt();\r
- numVal.setIdx(idx);\r
- numVal.setV(vals[1]);\r
-\r
- CTStrVal sVal = strData.addNewPt();\r
- sVal.setIdx(idx);\r
- sVal.setV(vals[0]);\r
-\r
- idx++;\r
- XSSFRow row = sheet.createRow(rownum++);\r
- row.createCell(0).setCellValue(vals[0]);\r
- row.createCell(1).setCellValue(Double.valueOf(vals[1]));\r
- }\r
- numData.getPtCount().setVal(idx);\r
- strData.getPtCount().setVal(idx);\r
-\r
- String numDataRange = new CellRangeAddress(1, rownum-1, 1, 1).formatAsString(sheet.getSheetName(), true);\r
- val.getNumRef().setF(numDataRange);\r
- String axisDataRange = new CellRangeAddress(1, rownum-1, 0, 0).formatAsString(sheet.getSheetName(), true);\r
- cat.getStrRef().setF(axisDataRange);\r
-\r
- // updated the embedded workbook with the data\r
- OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream();\r
- wb.write(xlsOut);\r
- xlsOut.close();\r
-\r
- // save the result\r
- FileOutputStream out = new FileOutputStream("pie-chart-demo-output.pptx");\r
- pptx.write(out);\r
- out.close();\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-/**\r
- * Demonstrates how to create slides with predefined layout\r
- * and fill the placeholder shapes\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class Tutorial1 {\r
-\r
- public static void main(String[] args) throws IOException{\r
- XMLSlideShow ppt = new XMLSlideShow();\r
-\r
- // XSLFSlide#createSlide() with no arguments creates a blank slide\r
- XSLFSlide blankSlide = ppt.createSlide();\r
-\r
- \r
- XSLFSlideMaster master = ppt.getSlideMasters()[0];\r
-\r
- XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);\r
- XSLFSlide slide1 = ppt.createSlide(layout1) ;\r
- XSLFTextShape[] ph1 = slide1.getPlaceholders();\r
- XSLFTextShape titlePlaceholder1 = ph1[0];\r
- titlePlaceholder1.setText("This is a title");\r
- XSLFTextShape subtitlePlaceholder1 = ph1[1];\r
- subtitlePlaceholder1.setText("this is a subtitle");\r
-\r
- XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);\r
- XSLFSlide slide2 = ppt.createSlide(layout2) ;\r
- XSLFTextShape[] ph2 = slide2.getPlaceholders();\r
- XSLFTextShape titlePlaceholder2 = ph2[0];\r
- titlePlaceholder2.setText("This is a title");\r
- XSLFTextShape bodyPlaceholder = ph2[1];\r
- // we are going to add text by paragraphs. Clear the default placehoder text before that\r
- bodyPlaceholder.clearText();\r
- XSLFTextParagraph p1 = bodyPlaceholder.addNewTextParagraph();\r
- p1.setLevel(0);\r
- p1.addNewTextRun().setText("Level1 text");\r
- XSLFTextParagraph p2 = bodyPlaceholder.addNewTextParagraph();\r
- p2.setLevel(1);\r
- p2.addNewTextRun().setText("Level2 text");\r
- XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph();\r
- p3.setLevel(3);\r
- p3.addNewTextRun().setText("Level3 text");\r
-\r
- FileOutputStream out = new FileOutputStream("slides.pptx");\r
- ppt.write(out);\r
- out.close();\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import java.awt.*;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-/**\r
- * Basic paragraph and text formatting\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class Tutorial2 {\r
-\r
- public static void main(String[] args) throws IOException{\r
- XMLSlideShow ppt = new XMLSlideShow();\r
-\r
- XSLFSlide slide1 = ppt.createSlide();\r
- XSLFTextBox shape1 = slide1.createTextBox();\r
- // initial height of the text box is 100 pt but\r
- Rectangle anchor = new Rectangle(10, 100, 300, 100);\r
- shape1.setAnchor(anchor);\r
-\r
- XSLFTextParagraph p1 = shape1.addNewTextParagraph();\r
- XSLFTextRun r1 = p1.addNewTextRun();\r
- r1.setText("Paragraph Formatting");\r
- r1.setFontSize(24);\r
- r1.setFontColor(new Color(85, 142, 213));\r
-\r
- XSLFTextParagraph p2 = shape1.addNewTextParagraph();\r
- // If spaceBefore >= 0, then space is a percentage of normal line height.\r
- // If spaceBefore < 0, the absolute value of linespacing is the spacing in points\r
- p2.setSpaceBefore(-20); // 20 pt from the previous paragraph\r
- p2.setSpaceAfter(300); // 3 lines after the paragraph\r
- XSLFTextRun r2 = p2.addNewTextRun();\r
- r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph.");\r
- r2.setFontSize(16);\r
-\r
- XSLFTextParagraph p3 = shape1.addNewTextParagraph();\r
-\r
- XSLFTextRun r3 = p3.addNewTextRun();\r
- r3.setText("Run Formatting");\r
- r3.setFontSize(24);\r
- r3.setFontColor(new Color(85, 142, 213));\r
-\r
- XSLFTextParagraph p4 = shape1.addNewTextParagraph();\r
- p4.setSpaceBefore(-20); // 20 pt from the previous paragraph\r
- p4.setSpaceAfter(300); // 3 lines after the paragraph\r
- XSLFTextRun r4 = p4.addNewTextRun();\r
- r4.setFontSize(16);\r
- r4.setText(\r
- "Run level formatting is the most granular property level and allows " +\r
- "for the specifying of all low level text properties. The text run is " +\r
- "what all paragraphs are derived from and thus specifying various " +\r
- "properties per run will allow for a diversely formatted text paragraph.");\r
-\r
- // resize the shape to fit text\r
- shape1.resizeToFitText();\r
-\r
- FileOutputStream out = new FileOutputStream("text.pptx");\r
- ppt.write(out);\r
- out.close();\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import java.awt.*;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-/**\r
- * How to set slide title\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class Tutorial3 {\r
-\r
- public static void main(String[] args) throws IOException{\r
- XMLSlideShow ppt = new XMLSlideShow();\r
-\r
- XSLFSlide slide = ppt.createSlide();\r
-\r
- XSLFTextShape titleShape = slide.createTextBox();\r
- titleShape.setPlaceholder(Placeholder.TITLE);\r
- titleShape.setText("This is a slide title");\r
- titleShape.setAnchor(new Rectangle(50, 50, 400, 100));\r
-\r
- FileOutputStream out = new FileOutputStream("title.pptx");\r
- ppt.write(out);\r
- out.close();\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import java.awt.*;\r
-import java.awt.geom.Rectangle2D;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-/**\r
- * PPTX Tables\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class Tutorial4 {\r
-\r
- public static void main(String[] args) throws IOException{\r
- XMLSlideShow ppt = new XMLSlideShow();\r
-\r
- // XSLFSlide#createSlide() with no arguments creates a blank slide\r
- XSLFSlide slide = ppt.createSlide();\r
-\r
- XSLFTable tbl = slide.createTable();\r
- tbl.setAnchor(new Rectangle2D.Double(50, 50, 450, 300));\r
-\r
- int numColumns = 3;\r
- int numRows = 5;\r
- XSLFTableRow headerRow = tbl.addRow();\r
- headerRow.setHeight(50);\r
- // header\r
- for(int i = 0; i < numColumns; i++) {\r
- XSLFTableCell th = headerRow.addCell();\r
- XSLFTextParagraph p = th.addNewTextParagraph();\r
- p.setTextAlign(TextAlign.CENTER);\r
- XSLFTextRun r = p.addNewTextRun();\r
- r.setText("Header " + (i+1));\r
- r.setBold(true);\r
- r.setFontColor(Color.white);\r
- th.setFillColor(new Color(79, 129, 189));\r
- th.setBorderBottom(2);\r
- th.setBorderBottomColor(Color.white);\r
-\r
- tbl.setColumnWidth(i, 150); // all columns are equally sized\r
- }\r
- \r
- // rows\r
- \r
- for(int rownum = 0; rownum < numRows; rownum ++){\r
- XSLFTableRow tr = tbl.addRow();\r
- tr.setHeight(50);\r
- // header\r
- for(int i = 0; i < numColumns; i++) {\r
- XSLFTableCell cell = tr.addCell();\r
- XSLFTextParagraph p = cell.addNewTextParagraph();\r
- XSLFTextRun r = p.addNewTextRun();\r
-\r
- r.setText("Cell " + (i+1));\r
- if(rownum % 2 == 0)\r
- cell.setFillColor(new Color(208, 216, 232));\r
- else\r
- cell.setFillColor(new Color(233, 247, 244));\r
-\r
- }\r
- \r
- }\r
-\r
-\r
- FileOutputStream out = new FileOutputStream("table.pptx");\r
- ppt.write(out);\r
- out.close();\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import org.apache.poi.util.IOUtils;\r
-\r
-import java.io.File;\r
-import java.io.FileInputStream;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-/**\r
- * Images\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class Tutorial5 {\r
-\r
- public static void main(String[] args) throws IOException{\r
- XMLSlideShow ppt = new XMLSlideShow();\r
-\r
- XSLFSlide slide = ppt.createSlide();\r
- File img = new File(System.getProperty("POI.testdata.path"), "slideshow/clock.jpg");\r
- byte[] data = IOUtils.toByteArray(new FileInputStream(img));\r
- int pictureIndex = ppt.addPicture(data, XSLFPictureData.PICTURE_TYPE_PNG);\r
-\r
- XSLFPictureShape shape = slide.createPicture(pictureIndex);\r
-\r
- FileOutputStream out = new FileOutputStream("images.pptx");\r
- ppt.write(out);\r
- out.close();\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import java.awt.*;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-/**\r
- * Hyperlinks\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class Tutorial6 {\r
-\r
- public static void main(String[] args) throws IOException{\r
- XMLSlideShow ppt = new XMLSlideShow();\r
-\r
- XSLFSlide slide1 = ppt.createSlide();\r
- XSLFSlide slide2 = ppt.createSlide();\r
-\r
- XSLFTextBox shape1 = slide1.createTextBox();\r
- shape1.setAnchor(new Rectangle(50, 50, 200, 50));\r
- XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun();\r
- XSLFHyperlink link1 = r1.createHyperlink();\r
- r1.setText("http://poi.apache.org"); // visible text\r
- link1.setAddress("http://poi.apache.org"); // link address\r
-\r
- XSLFTextBox shape2 = slide1.createTextBox();\r
- shape2.setAnchor(new Rectangle(300, 50, 200, 50));\r
- XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun();\r
- XSLFHyperlink link2 = r2.createHyperlink();\r
- r2.setText("Go to the second slide"); // visible text\r
- link2.setAddress(slide2); // link address\r
-\r
-\r
-\r
- FileOutputStream out = new FileOutputStream("hyperlinks.pptx");\r
- ppt.write(out);\r
- out.close();\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ==================================================================== \r
- */\r
-\r
-package org.apache.poi.xslf.usermodel;\r
-\r
-import java.awt.*;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-/**\r
- * Bullets and numbering\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class Tutorial7 {\r
-\r
- public static void main(String[] args) throws IOException{\r
- XMLSlideShow ppt = new XMLSlideShow();\r
-\r
- XSLFSlide slide = ppt.createSlide();\r
- XSLFTextBox shape = slide.createTextBox();\r
- shape.setAnchor(new Rectangle(50, 50, 400, 200));\r
-\r
- XSLFTextParagraph p1 = shape.addNewTextParagraph();\r
- p1.setLevel(0);\r
- p1.setBullet(true);\r
- XSLFTextRun r1 = p1.addNewTextRun();\r
- r1.setText("Bullet1");\r
-\r
- XSLFTextParagraph p2 = shape.addNewTextParagraph();\r
- // indentation before text\r
- p2.setLeftMargin(60);\r
- // the bullet is set 40 pt before the text\r
- p2.setIndent(-40);\r
- p2.setBullet(true);\r
- // customize bullets\r
- p2.setBulletFontColor(Color.red);\r
- p2.setBulletFont("Wingdings");\r
- p2.setBulletCharacter("\u0075");\r
- p2.setLevel(1);\r
- XSLFTextRun r2 = p2.addNewTextRun();\r
- r2.setText("Bullet2");\r
-\r
- // the next three paragraphs form an auto-numbered list\r
- XSLFTextParagraph p3 = shape.addNewTextParagraph();\r
- p3.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 1);\r
- p3.setLevel(2);\r
- XSLFTextRun r3 = p3.addNewTextRun();\r
- r3.setText("Numbered List Item - 1");\r
-\r
- XSLFTextParagraph p4 = shape.addNewTextParagraph();\r
- p4.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 2);\r
- p4.setLevel(2);\r
- XSLFTextRun r4 = p4.addNewTextRun();\r
- r4.setText("Numbered List Item - 2");\r
-\r
- XSLFTextParagraph p5 = shape.addNewTextParagraph();\r
- p5.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 3);\r
- p5.setLevel(2);\r
- XSLFTextRun r5 = p5.addNewTextRun();\r
- r5.setText("Numbered List Item - 3");\r
-\r
- shape.resizeToFitText();\r
-\r
- FileOutputStream out = new FileOutputStream("list.pptx");\r
- ppt.write(out);\r
- out.close();\r
- }\r
-}\r
+++ /dev/null
-My Chart\r
-First 1.0\r
-Second 3.0\r
-Third 4.0
\ No newline at end of file
+++ /dev/null
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF 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());
- }
- }
- }
- }
- }
- }
-}
+++ /dev/null
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.
- * <p/>
- * 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.
- * <p/>
- * 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
- * <p/>
- * Also see Standard ECMA-376, 1st edition, part 4, pages 1928ff, at
- * http://www.ecma-international.org/publications/standards/Ecma-376.htm
- * <p/>
- * 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 <xlsx file> [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();
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<InputStream> 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]);
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
-http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF 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
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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
- *
- * <p>
- * 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.
- * </p>
- * See <a "http://poi.apache.org/spreadsheet/how-to.html#sxssf">
- * http://poi.apache.org/spreadsheet/how-to.html#sxssf</a>.
-
- *
- * @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<String, XSSFCellStyle> 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<String, XSSFCellStyle> createStyles(XSSFWorkbook wb){
- Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();
- 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<String, XSSFCellStyle> 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<ZipEntry> en = (Enumeration<ZipEntry>) 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("<?xml version=\"1.0\" encoding=\""+XML_ENCODING+"\"?>" +
- "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" );
- _out.write("<sheetData>\n");
- }
-
- public void endSheet() throws IOException {
- _out.write("</sheetData>");
- _out.write("</worksheet>");
- }
-
- /**
- * Insert a new row
- *
- * @param rownum 0-based row number
- */
- public void insertRow(int rownum) throws IOException {
- _out.write("<row r=\""+(rownum+1)+"\">\n");
- this._rownum = rownum;
- }
-
- /**
- * Insert row end marker
- */
- public void endRow() throws IOException {
- _out.write("</row>\n");
- }
-
- public void createCell(int columnIndex, String value, int styleIndex) throws IOException {
- String ref = new CellReference(_rownum, columnIndex).formatAsString();
- _out.write("<c r=\""+ref+"\" t=\"inlineStr\"");
- if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
- _out.write(">");
- _out.write("<is><t>"+value+"</t></is>");
- _out.write("</c>");
- }
-
- 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("<c r=\""+ref+"\" t=\"n\"");
- if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
- _out.write(">");
- _out.write("<v>"+value+"</v>");
- _out.write("</c>");
- }
-
- 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);
- }
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.
- *
- * <pre>
- * Usage:
- * CalendarDemo <year>
- * </pre>
- *
- * @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<String, XSSFCellStyle> 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<String, XSSFCellStyle> createStyles(XSSFWorkbook wb){
- Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();
-
- 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;
- }
-}
+++ /dev/null
-/* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel.examples;\r
-\r
-import org.apache.poi.ss.usermodel.*;\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
-\r
-import java.io.IOException;\r
-import java.io.FileOutputStream;\r
-\r
-/**\r
- * Demonstrates how to work with excel cell comments.\r
- *\r
- * <p>\r
- * Excel comment is a kind of a text shape,\r
- * so inserting a comment is very similar to placing a text box in a worksheet\r
- * </p>\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class CellComments {\r
- public static void main(String[] args) throws IOException {\r
- Workbook wb = new XSSFWorkbook();\r
-\r
- CreationHelper factory = wb.getCreationHelper();\r
-\r
- Sheet sheet = wb.createSheet();\r
-\r
- Cell cell1 = sheet.createRow(3).createCell(5);\r
- cell1.setCellValue("F4");\r
-\r
- Drawing drawing = sheet.createDrawingPatriarch();\r
-\r
- ClientAnchor anchor = factory.createClientAnchor();\r
-\r
- Comment comment1 = drawing.createCellComment(anchor);\r
- RichTextString str1 = factory.createRichTextString("Hello, World!");\r
- comment1.setString(str1);\r
- comment1.setAuthor("Apache POI");\r
- cell1.setCellComment(comment1);\r
-\r
- Cell cell2 = sheet.createRow(2).createCell(2);\r
- cell2.setCellValue("C3");\r
-\r
- Comment comment2 = drawing.createCellComment(anchor);\r
- RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");\r
- //apply custom font to the text in the comment\r
- Font font = wb.createFont();\r
- font.setFontName("Arial");\r
- font.setFontHeightInPoints((short)14);\r
- font.setBoldweight(Font.BOLDWEIGHT_BOLD);\r
- font.setColor(IndexedColors.RED.getIndex());\r
- str2.applyFont(font);\r
-\r
- comment2.setString(str2);\r
- comment2.setAuthor("Apache POI");\r
- comment2.setColumn(2);\r
- comment2.setRow(2);\r
-\r
- String fname = "comments.xlsx";\r
- FileOutputStream out = new FileOutputStream(fname);\r
- wb.write(out);\r
- out.close();\r
-\r
- }\r
-}\r
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-
-}
+++ /dev/null
-/* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel.examples;\r
-\r
-import org.apache.poi.openxml4j.opc.OPCPackage;\r
-import org.apache.poi.xssf.extractor.XSSFExportToXml;\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
-import org.apache.poi.xssf.usermodel.XSSFMap;\r
-\r
-import java.io.ByteArrayOutputStream;\r
-\r
-/**\r
- * Print all custom XML mappings registered in the given workbook\r
- */\r
-public class CustomXMLMapping {\r
-\r
- public static void main(String[] args) throws Exception {\r
- OPCPackage pkg = OPCPackage.open(args[0]);\r
- XSSFWorkbook wb = new XSSFWorkbook(pkg);\r
-\r
- for (XSSFMap map : wb.getCustomXMLMappings()) {\r
- XSSFExportToXml exporter = new XSSFExportToXml(map);\r
-\r
- ByteArrayOutputStream os = new ByteArrayOutputStream();\r
- exporter.exportToXML(os, true);\r
- String xml = os.toString("UTF-8");\r
- System.out.println(xml);\r
- }\r
- pkg.close();\r
- }\r
-}\r
+++ /dev/null
-/* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel.examples;\r
-\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
-import org.apache.poi.openxml4j.opc.OPCPackage;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
-import org.apache.poi.hslf.HSLFSlideShow;\r
-import org.apache.poi.hwpf.HWPFDocument;\r
-import org.apache.poi.xslf.XSLFSlideShow;\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
-\r
-import java.io.InputStream;\r
-\r
-/**\r
- * Demonstrates how you can extract embedded data from a .xlsx file\r
- */\r
-public class EmbeddedObjects {\r
- public static void main(String[] args) throws Exception {\r
- OPCPackage pkg = OPCPackage.open(args[0]);\r
- XSSFWorkbook workbook = new XSSFWorkbook(pkg);\r
- for (PackagePart pPart : workbook.getAllEmbedds()) {\r
- String contentType = pPart.getContentType();\r
- // Excel Workbook - either binary or OpenXML\r
- if (contentType.equals("application/vnd.ms-excel")) {\r
- HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());\r
- }\r
- // Excel Workbook - OpenXML file format\r
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {\r
- XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());\r
- }\r
- // Word Document - binary (OLE2CDF) file format\r
- else if (contentType.equals("application/msword")) {\r
- HWPFDocument document = new HWPFDocument(pPart.getInputStream());\r
- }\r
- // Word Document - OpenXML file format\r
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {\r
- XWPFDocument document = new XWPFDocument(pPart.getInputStream());\r
- }\r
- // PowerPoint Document - binary file format\r
- else if (contentType.equals("application/vnd.ms-powerpoint")) {\r
- HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream());\r
- }\r
- // PowerPoint Document - OpenXML file format\r
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {\r
- OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());\r
- XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);\r
- }\r
- // Any other type of embedded object.\r
- else {\r
- System.out.println("Unknown Embedded Document: " + contentType);\r
- InputStream inputStream = pPart.getInputStream();\r
- }\r
- }\r
- pkg.close();\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();\r
-\r
- //cell style for hyperlinks\r
- //by default hyperlinks are blue and underlined\r
- CellStyle hlink_style = wb.createCellStyle();\r
- Font hlink_font = wb.createFont();\r
- hlink_font.setUnderline(Font.U_SINGLE);\r
- 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();
-
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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());
- }
- }
- }
- }
-}
+++ /dev/null
-/* ====================================================================\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
-\r
- http://www.apache.org/licenses/LICENSE-2.0\r
-\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel.examples;\r
-\r
-import org.apache.poi.ss.usermodel.*;\r
-import org.apache.poi.ss.usermodel.charts.*;\r
-import org.apache.poi.ss.util.CellRangeAddress;\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
-\r
-import java.io.FileOutputStream;\r
-\r
-/**\r
- * Line chart example.\r
- *\r
- * @author Martin Andersson\r
- */\r
-public class LineChart {\r
-\r
- public static void main(String[] args) throws Exception {\r
- Workbook wb = new XSSFWorkbook();\r
- Sheet sheet = wb.createSheet("linechart");\r
- final int NUM_OF_ROWS = 3;\r
- final int NUM_OF_COLUMNS = 10;\r
-\r
- // Create a row and put some cells in it. Rows are 0 based.\r
- Row row;\r
- Cell cell;\r
- for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {\r
- row = sheet.createRow((short) rowIndex);\r
- for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {\r
- cell = row.createCell((short) colIndex);\r
- cell.setCellValue(colIndex * (rowIndex + 1));\r
- }\r
- }\r
-\r
- Drawing drawing = sheet.createDrawingPatriarch();\r
- ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);\r
-\r
- Chart chart = drawing.createChart(anchor);\r
- ChartLegend legend = chart.getOrCreateLegend();\r
- legend.setPosition(LegendPosition.TOP_RIGHT);\r
-\r
- LineChartData data = chart.getChartDataFactory().createLineChartData();\r
-\r
- // Use a category axis for the bottom axis.\r
- ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);\r
- ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);\r
- leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);\r
-\r
- ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));\r
- ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));\r
- ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));\r
-\r
-\r
- data.addSerie(xs, ys1);\r
- data.addSerie(xs, ys2);\r
-\r
- chart.plot(data, bottomAxis, leftAxis);\r
-\r
- // Write the output to a file\r
- FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx");\r
- wb.write(fileOut);\r
- fileOut.close();\r
- }\r
-}\r
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF 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<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
- ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
- ChartDataSource<Number> 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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();
-
- }
-}
+++ /dev/null
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF 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();
- }
-
-
-}
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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<XWPFTableRow> 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<XWPFTableCell> 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();
- }
-
-}
+++ /dev/null
-/*\r
- * ====================================================================\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ====================================================================\r
- */\r
-\r
-package org.apache.poi.xwpf.usermodel;\r
-\r
-import java.io.File;\r
-import java.io.FileInputStream;\r
-import java.io.FileOutputStream;\r
-import java.io.FileNotFoundException;\r
-import java.io.IOException;\r
-import java.util.List;\r
-import java.util.Iterator;\r
-\r
-import junit.framework.Assert;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.ss.usermodel.WorkbookFactory;\r
-import org.apache.poi.ss.usermodel.Workbook;\r
-import org.apache.poi.ss.usermodel.Sheet;\r
-import org.apache.poi.ss.usermodel.Row;\r
-import org.apache.poi.ss.usermodel.Cell;\r
-\r
-/**\r
- * Tests whether it is possible to successfully update an Excel workbook that is\r
- * embedded into a WordprocessingML document. Note that the test has currently\r
- * only been conducted with a binary Excel workbook and NOT yet with a\r
- * SpreadsheetML workbook embedded into the document.\r
- *\r
- * <p>\r
- * This code was successfully tested with the following file from the POI test collection:\r
- * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx\r
- * </p>\r
- *\r
- * @author Mark B\r
- */\r
-public class UpdateEmbeddedDoc {\r
-\r
- private XWPFDocument doc = null;\r
- private File docFile = null;\r
-\r
- private static final int SHEET_NUM = 0;\r
- private static final int ROW_NUM = 0;\r
- private static final int CELL_NUM = 0;\r
- private static final double NEW_VALUE = 100.98D;\r
- private static final String BINARY_EXTENSION = "xls";\r
- private static final String OPENXML_EXTENSION = "xlsx";\r
-\r
- /**\r
- * Create a new instance of the UpdateEmbeddedDoc class using the following\r
- * parameters;\r
- *\r
- * @param filename An instance of the String class that encapsulates the name\r
- * of and path to a WordprocessingML Word document that contains an\r
- * embedded binary Excel workbook.\r
- * @throws java.io.FileNotFoundException Thrown if the file cannot be found\r
- * on the underlying file system.\r
- * @throws java.io.IOException Thrown if a problem occurs in the underlying\r
- * file system.\r
- */\r
- public UpdateEmbeddedDoc(String filename) throws FileNotFoundException, IOException {\r
- this.docFile = new File(filename);\r
- FileInputStream fis = null;\r
- if (!this.docFile.exists()) {\r
- throw new FileNotFoundException("The Word dcoument " +\r
- filename +\r
- " does not exist.");\r
- }\r
- try {\r
-\r
- // Open the Word document file and instantiate the XWPFDocument\r
- // class.\r
- fis = new FileInputStream(this.docFile);\r
- this.doc = new XWPFDocument(fis);\r
- } finally {\r
- if (fis != null) {\r
- try {\r
- fis.close();\r
- fis = null;\r
- } catch (IOException ioEx) {\r
- System.out.println("IOException caught trying to close " +\r
- "FileInputStream in the constructor of " +\r
- "UpdateEmbeddedDoc.");\r
- }\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Called to update the embedded Excel workbook. As the format and structire\r
- * of the workbook are known in advance, all this code attempts to do is\r
- * write a new value into the first cell on the first row of the first\r
- * worksheet. Prior to executing this method, that cell will contain the\r
- * value 1.\r
- *\r
- * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException\r
- * Rather\r
- * than use the specific classes (HSSF/XSSF) to handle the embedded\r
- * workbook this method uses those defeined in the SS stream. As\r
- * a result, it might be the case that a SpreadsheetML file is\r
- * opened for processing, throwing this exception if that file is\r
- * invalid.\r
- * @throws java.io.IOException Thrown if a problem occurs in the underlying\r
- * file system.\r
- */\r
- public void updateEmbeddedDoc() throws OpenXML4JException, IOException {\r
- Workbook workbook = null;\r
- Sheet sheet = null;\r
- Row row = null;\r
- Cell cell = null;\r
- PackagePart pPart = null;\r
- Iterator<PackagePart> pIter = null;\r
- List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();\r
- if (embeddedDocs != null && !embeddedDocs.isEmpty()) {\r
- pIter = embeddedDocs.iterator();\r
- while (pIter.hasNext()) {\r
- pPart = pIter.next();\r
- if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||\r
- pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {\r
-\r
- // Get an InputStream from the pacage part and pass that\r
- // to the create method of the WorkbookFactory class. Update\r
- // the resulting Workbook and then stream that out again\r
- // using an OutputStream obtained from the same PackagePart.\r
- workbook = WorkbookFactory.create(pPart.getInputStream());\r
- sheet = workbook.getSheetAt(SHEET_NUM);\r
- row = sheet.getRow(ROW_NUM);\r
- cell = row.getCell(CELL_NUM);\r
- cell.setCellValue(NEW_VALUE);\r
- workbook.write(pPart.getOutputStream());\r
- }\r
- }\r
-\r
- // Finally, write the newly modified Word document out to file.\r
- this.doc.write(new FileOutputStream(this.docFile));\r
- }\r
- }\r
-\r
- /**\r
- * Called to test whether or not the embedded workbook was correctly\r
- * updated. This method simply recovers the first cell from the first row\r
- * of the first workbook and tests the value it contains.\r
- * <p/>\r
- * Note that execution will not continue up to the assertion as the\r
- * embedded workbook is now corrupted and causes an IllegalArgumentException\r
- * with the following message\r
- * <p/>\r
- * <em>java.lang.IllegalArgumentException: Your InputStream was neither an\r
- * OLE2 stream, nor an OOXML stream</em>\r
- * <p/>\r
- * to be thrown when the WorkbookFactory.createWorkbook(InputStream) method\r
- * is executed.\r
- *\r
- * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException\r
- * Rather\r
- * than use the specific classes (HSSF/XSSF) to handle the embedded\r
- * workbook this method uses those defeined in the SS stream. As\r
- * a result, it might be the case that a SpreadsheetML file is\r
- * opened for processing, throwing this exception if that file is\r
- * invalid.\r
- * @throws java.io.IOException Thrown if a problem occurs in the underlying\r
- * file system.\r
- */\r
- public void checkUpdatedDoc() throws OpenXML4JException, IOException {\r
- Workbook workbook = null;\r
- Sheet sheet = null;\r
- Row row = null;\r
- Cell cell = null;\r
- PackagePart pPart = null;\r
- Iterator<PackagePart> pIter = null;\r
- List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();\r
- if (embeddedDocs != null && !embeddedDocs.isEmpty()) {\r
- pIter = embeddedDocs.iterator();\r
- while (pIter.hasNext()) {\r
- pPart = pIter.next();\r
- if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||\r
- pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {\r
- workbook = WorkbookFactory.create(pPart.getInputStream());\r
- sheet = workbook.getSheetAt(SHEET_NUM);\r
- row = sheet.getRow(ROW_NUM);\r
- cell = row.getCell(CELL_NUM);\r
- Assert.assertEquals(cell.getNumericCellValue(), NEW_VALUE);\r
- }\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Code to test updating of the embedded Excel workbook.\r
- *\r
- * @param args\r
- */\r
- public static void main(String[] args) {\r
- try {\r
- UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]);\r
- ued.updateEmbeddedDoc();\r
- ued.checkUpdatedDoc();\r
- } catch (Exception ex) {\r
- System.out.println(ex.getClass().getName());\r
- System.out.println(ex.getMessage());\r
- ex.printStackTrace(System.out);\r
- }\r
- }\r
-}\r