fix more LGTM alerts, in tests

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1843557 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Alain Béarez 2018-10-11 14:50:27 +00:00
parent fcbed10cfc
commit 5a53f36391
11 changed files with 438 additions and 380 deletions

View File

@ -17,7 +17,25 @@
package org.apache.poi.ooxml.util; package org.apache.poi.ooxml.util;
import junit.framework.TestCase; import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
import org.apache.poi.util.StringUtil; import org.apache.poi.util.StringUtil;
import org.apache.poi.util.SuppressForbidden; import org.apache.poi.util.SuppressForbidden;
@ -29,19 +47,7 @@ import org.junit.runner.JUnitCore;
import org.junit.runner.Result; import org.junit.runner.Result;
import org.reflections.Reflections; import org.reflections.Reflections;
import java.io.File; import junit.framework.TestCase;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
/** /**
* Build a 'lite' version of the ooxml-schemas.jar * Build a 'lite' version of the ooxml-schemas.jar
@ -74,12 +80,12 @@ public final class OOXMLLite {
} }
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
System.out.println("Free memory (bytes): " + System.out.println("Free memory (bytes): " +
Runtime.getRuntime().freeMemory()); Runtime.getRuntime().freeMemory());
long maxMemory = Runtime.getRuntime().maxMemory(); long maxMemory = Runtime.getRuntime().maxMemory();
System.out.println("Maximum memory (bytes): " + System.out.println("Maximum memory (bytes): " +
(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory)); (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
System.out.println("Total memory (bytes): " + System.out.println("Total memory (bytes): " +
Runtime.getRuntime().totalMemory()); Runtime.getRuntime().totalMemory());
String dest = null, test = null, ooxml = null; String dest = null, test = null, ooxml = null;
@ -87,13 +93,13 @@ public final class OOXMLLite {
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {
switch (args[i]) { switch (args[i]) {
case "-dest": case "-dest":
dest = args[++i]; dest = args[++i]; // lgtm[java/index-out-of-bounds]
break; break;
case "-test": case "-test":
test = args[++i]; test = args[++i]; // lgtm[java/index-out-of-bounds]
break; break;
case "-ooxml": case "-ooxml":
ooxml = args[++i]; ooxml = args[++i]; // lgtm[java/index-out-of-bounds]
break; break;
} }
} }
@ -248,7 +254,7 @@ public final class OOXMLLite {
return true; return true;
} }
} }
// also check super classes // also check super classes
if(testclass.getSuperclass() != null) { if(testclass.getSuperclass() != null) {
for (Method m : testclass.getSuperclass().getDeclaredMethods()) { for (Method m : testclass.getSuperclass().getDeclaredMethods()) {
@ -257,7 +263,7 @@ public final class OOXMLLite {
} }
} }
} }
System.out.println("Class " + testclass.getName() + " does not derive from TestCase and does not have a @Test annotation"); System.out.println("Class " + testclass.getName() + " does not derive from TestCase and does not have a @Test annotation");
// Should we also look at superclasses to find cases // Should we also look at superclasses to find cases
@ -286,8 +292,12 @@ public final class OOXMLLite {
String path = arg.getAbsolutePath(); String path = arg.getAbsolutePath();
String prefix = root.getAbsolutePath(); String prefix = root.getAbsolutePath();
String cls = path.substring(prefix.length() + 1).replace(File.separator, "."); String cls = path.substring(prefix.length() + 1).replace(File.separator, ".");
if(!cls.matches(ptrn)) return; if(!cls.matches(ptrn)) {
if (cls.matches(exclude)) return; return;
}
if (cls.matches(exclude)) {
return;
}
//ignore inner classes defined in tests //ignore inner classes defined in tests
if (cls.indexOf('$') != -1) { if (cls.indexOf('$') != -1) {
System.out.println("Inner class " + cls + " not included"); System.out.println("Inner class " + cls + " not included");
@ -315,10 +325,11 @@ public final class OOXMLLite {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static Set<Class<?>> getLoadedClasses(String ptrn) { private static Set<Class<?>> getLoadedClasses(String ptrn) {
// make the field accessible, we defer this from static initialization to here to // make the field accessible, we defer this from static initialization to here to
// allow JDKs which do not have this field (e.g. IBM JDK) to at least load the class // allow JDKs which do not have this field (e.g. IBM JDK) to at least load the class
// without failing, see https://issues.apache.org/bugzilla/show_bug.cgi?id=56550 // without failing, see https://issues.apache.org/bugzilla/show_bug.cgi?id=56550
final Field _classes = AccessController.doPrivileged(new PrivilegedAction<Field>() { final Field _classes = AccessController.doPrivileged(new PrivilegedAction<Field>() {
@Override
@SuppressForbidden("TODO: Reflection works until Java 8 on Oracle/Sun JDKs, but breaks afterwards (different classloader types, access checks)") @SuppressForbidden("TODO: Reflection works until Java 8 on Oracle/Sun JDKs, but breaks afterwards (different classloader types, access checks)")
public Field run() { public Field run() {
try { try {
@ -339,11 +350,17 @@ public final class OOXMLLite {
for (Class<?> cls : classes) { for (Class<?> cls : classes) {
// e.g. proxy-classes, ... // e.g. proxy-classes, ...
ProtectionDomain pd = cls.getProtectionDomain(); ProtectionDomain pd = cls.getProtectionDomain();
if (pd == null) continue; if (pd == null) {
continue;
}
CodeSource cs = pd.getCodeSource(); CodeSource cs = pd.getCodeSource();
if (cs == null) continue; if (cs == null) {
continue;
}
URL loc = cs.getLocation(); URL loc = cs.getLocation();
if (loc == null) continue; if (loc == null) {
continue;
}
String jar = loc.toString(); String jar = loc.toString();
if (jar.contains(ptrn)) { if (jar.contains(ptrn)) {

View File

@ -30,7 +30,6 @@ import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import junit.framework.AssertionFailedError;
import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
@ -44,125 +43,130 @@ import org.xmlunit.diff.Diff;
import org.xmlunit.diff.DifferenceEvaluator; import org.xmlunit.diff.DifferenceEvaluator;
import org.xmlunit.diff.ElementSelectors; import org.xmlunit.diff.ElementSelectors;
import junit.framework.AssertionFailedError;
/** /**
* Compare the contents of 2 zip files. * Compare the contents of 2 zip files.
*/ */
public final class ZipFileAssert { public final class ZipFileAssert {
private ZipFileAssert() { private ZipFileAssert() {
} }
private static void equals( private static void equals(
TreeMap<String, ByteArrayOutputStream> file1, TreeMap<String, ByteArrayOutputStream> file1,
TreeMap<String, ByteArrayOutputStream> file2) { TreeMap<String, ByteArrayOutputStream> file2) {
Set<String> listFile1 = file1.keySet(); Set<String> listFile1 = file1.keySet();
Assert.assertEquals("not the same number of files in zip:", listFile1.size(), file2.keySet().size()); Assert.assertEquals("not the same number of files in zip:", listFile1.size(), file2.keySet().size());
for (String fileName : listFile1) {
// extract the contents for both
ByteArrayOutputStream contain1 = file1.get(fileName);
ByteArrayOutputStream contain2 = file2.get(fileName);
assertNotNull(fileName + " not found in 2nd zip", contain2); for (String fileName : listFile1) {
// no need to check for contain1. The key come from it // extract the contents for both
ByteArrayOutputStream contain1 = file1.get(fileName);
ByteArrayOutputStream contain2 = file2.get(fileName);
if (fileName.matches(".*\\.(xml|rels)$")) { assertNotNull(fileName + " not found in 2nd zip", contain2);
// we have a xml file // no need to check for contain1. The key come from it
final Diff diff = DiffBuilder.
compare(Input.fromByteArray(contain1.toByteArray())). if (fileName.matches(".*\\.(xml|rels)$")) {
withTest(Input.fromByteArray(contain2.toByteArray())). // we have a xml file
ignoreWhitespace(). final Diff diff = DiffBuilder.
checkForSimilar(). compare(Input.fromByteArray(contain1.toByteArray())).
withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()). withTest(Input.fromByteArray(contain2.toByteArray())).
withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)). ignoreWhitespace().
build(); checkForSimilar().
assertFalse(fileName+": "+diff.toString(), diff.hasDifferences()); withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()).
withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)).
build();
assertFalse(fileName+": "+diff.toString(), diff.hasDifferences());
} else { } else {
// not xml, may be an image or other binary format // not xml, may be an image or other binary format
Assert.assertEquals(fileName + " does not have the same size in both zip:", contain1.size(), contain2.size()); Assert.assertEquals(fileName + " does not have the same size in both zip:", contain1.size(), contain2.size());
assertArrayEquals("contents differ", contain1.toByteArray(), contain2.toByteArray()); assertArrayEquals("contents differ", contain1.toByteArray(), contain2.toByteArray());
} }
} }
} }
private static TreeMap<String, ByteArrayOutputStream> decompress( private static TreeMap<String, ByteArrayOutputStream> decompress(
File filename) throws IOException { File filename) throws IOException {
// store the zip content in memory // store the zip content in memory
// let s assume it is not Go ;-) // let s assume it is not Go ;-)
TreeMap<String, ByteArrayOutputStream> zipContent = new TreeMap<>(); TreeMap<String, ByteArrayOutputStream> zipContent = new TreeMap<>();
/* Open file to decompress */ try (
FileInputStream file_decompress = new FileInputStream(filename); /* Open file to decompress */
FileInputStream file_decompress = new FileInputStream(filename);
/* Create a buffer for the decompressed files */ /* Create a buffer for the decompressed files */
BufferedInputStream buffi = new BufferedInputStream(file_decompress); BufferedInputStream buffi = new BufferedInputStream(file_decompress);
/* Open the file with the buffer */ /* Open the file with the buffer */
ZipArchiveInputStream zis = new ZipArchiveInputStream(buffi); ZipArchiveInputStream zis = new ZipArchiveInputStream(buffi);
) {
/* Processing entries of the zip file */ /* Processing entries of the zip file */
ArchiveEntry entree; ArchiveEntry entree;
while ((entree = zis.getNextEntry()) != null) { while ((entree = zis.getNextEntry()) != null) {
/* Create a array for the current entry */ /* Create a array for the current entry */
ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
IOUtils.copy(zis, byteArray); IOUtils.copy(zis, byteArray);
zipContent.put(entree.getName(), byteArray); zipContent.put(entree.getName(), byteArray);
} }
zis.close(); }
return zipContent; return zipContent;
} }
/** /**
* Asserts that two files are equal. Throws an <tt>AssertionFailedError</tt> * Asserts that two files are equal. Throws an <tt>AssertionFailedError</tt>
* if they are not. * if they are not.
* <p> * <p>
* *
*/ */
public static void assertEquals(File expected, File actual) { public static void assertEquals(File expected, File actual) {
assertNotNull(expected); assertNotNull(expected);
assertNotNull(actual); assertNotNull(actual);
assertTrue("File does not exist [" + expected.getAbsolutePath() assertTrue("File does not exist [" + expected.getAbsolutePath()
+ "]", expected.exists()); + "]", expected.exists());
assertTrue("File does not exist [" + actual.getAbsolutePath() assertTrue("File does not exist [" + actual.getAbsolutePath()
+ "]", actual.exists()); + "]", actual.exists());
assertTrue("Expected file not readable", expected.canRead()); assertTrue("Expected file not readable", expected.canRead());
assertTrue("Actual file not readable", actual.canRead()); assertTrue("Actual file not readable", actual.canRead());
try { try {
TreeMap<String, ByteArrayOutputStream> file1 = decompress(expected); TreeMap<String, ByteArrayOutputStream> file1 = decompress(expected);
TreeMap<String, ByteArrayOutputStream> file2 = decompress(actual); TreeMap<String, ByteArrayOutputStream> file2 = decompress(actual);
equals(file1, file2); equals(file1, file2);
} catch (IOException e) { } catch (IOException e) {
throw new AssertionFailedError(e.toString()); throw new AssertionFailedError(e.toString());
} }
} }
private static class IgnoreXMLDeclEvaluator implements DifferenceEvaluator { private static class IgnoreXMLDeclEvaluator implements DifferenceEvaluator {
public ComparisonResult evaluate(final Comparison comparison, final ComparisonResult outcome) { @Override
if (outcome != ComparisonResult.EQUAL) { public ComparisonResult evaluate(final Comparison comparison, final ComparisonResult outcome) {
// only evaluate differences if (outcome != ComparisonResult.EQUAL) {
switch (comparison.getType()) { // only evaluate differences
case CHILD_NODELIST_SEQUENCE: switch (comparison.getType()) {
case XML_STANDALONE: case CHILD_NODELIST_SEQUENCE:
case NAMESPACE_PREFIX: case XML_STANDALONE:
return ComparisonResult.SIMILAR; case NAMESPACE_PREFIX:
case TEXT_VALUE: return ComparisonResult.SIMILAR;
switch (comparison.getControlDetails().getTarget().getParentNode().getNodeName()) { case TEXT_VALUE:
case "dcterms:created": switch (comparison.getControlDetails().getTarget().getParentNode().getNodeName()) {
case "dc:creator": case "dcterms:created":
return ComparisonResult.SIMILAR; case "dc:creator":
} return ComparisonResult.SIMILAR;
break; }
default: break;
break; default:
} break;
} }
}
return outcome; return outcome;
} }
} }
} }

View File

@ -47,22 +47,22 @@ public class TestXSLFTextParagraph {
DrawTextParagraphProxy(XSLFTextParagraph p) { DrawTextParagraphProxy(XSLFTextParagraph p) {
super(p); super(p);
} }
@Override @Override
public void breakText(Graphics2D graphics) { public void breakText(Graphics2D graphics) {
super.breakText(graphics); super.breakText(graphics);
} }
@Override @Override
public double getWrappingWidth(boolean firstLine, Graphics2D graphics) { public double getWrappingWidth(boolean firstLine, Graphics2D graphics) {
return super.getWrappingWidth(firstLine, graphics); return super.getWrappingWidth(firstLine, graphics);
} }
public List<DrawTextFragment> getLines() { public List<DrawTextFragment> getLines() {
return lines; return lines;
} }
} }
@Test @Test
public void testWrappingWidth() throws IOException { public void testWrappingWidth() throws IOException {
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
@ -78,11 +78,11 @@ public class TestXSLFTextParagraph {
Rectangle2D anchor = new Rectangle2D.Double(50, 50, 300, 200); Rectangle2D anchor = new Rectangle2D.Double(50, 50, 300, 200);
sh.setAnchor(anchor); sh.setAnchor(anchor);
DrawTextParagraphProxy dtp = new DrawTextParagraphProxy(p); DrawTextParagraphProxy dtp = new DrawTextParagraphProxy(p);
Double leftInset = sh.getLeftInset(); double leftInset = sh.getLeftInset();
Double rightInset = sh.getRightInset(); double rightInset = sh.getRightInset();
assertEquals(7.2, leftInset, 0); assertEquals(7.2, leftInset, 0);
assertEquals(7.2, rightInset, 0); assertEquals(7.2, rightInset, 0);
@ -142,13 +142,13 @@ public class TestXSLFTextParagraph {
indent = p.getIndent(); indent = p.getIndent();
assertEquals(-72.0, indent, 0); assertEquals(-72.0, indent, 0);
expectedWidth = anchor.getWidth() - leftInset - rightInset; expectedWidth = anchor.getWidth() - leftInset - rightInset;
assertEquals(280.0, expectedWidth, 0); // 300 - 10 - 10 assertEquals(280.0, expectedWidth, 0); // 300 - 10 - 10
assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); // first line is NOT indented assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); // first line is NOT indented
// other lines are indented by leftMargin (the value of indent is not used) // other lines are indented by leftMargin (the value of indent is not used)
expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin;
assertEquals(244.0, expectedWidth, 0); // 300 - 10 - 10 - 36 assertEquals(244.0, expectedWidth, 0); // 300 - 10 - 10 - 36
assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0);
ppt.close(); ppt.close();
} }
@ -294,13 +294,13 @@ public class TestXSLFTextParagraph {
assertEquals(-20.0, p.getBulletFontSize(), 0); assertEquals(-20.0, p.getBulletFontSize(), 0);
assertEquals(72.0, p.getDefaultTabSize(), 0); assertEquals(72.0, p.getDefaultTabSize(), 0);
assertNull(p.getIndent()); assertNull(p.getIndent());
p.setIndent(72.0); p.setIndent(72.0);
assertEquals(72.0, p.getIndent(), 0); assertEquals(72.0, p.getIndent(), 0);
p.setIndent(-1d); // the value of -1.0 resets to the defaults (not any more ...) p.setIndent(-1d); // the value of -1.0 resets to the defaults (not any more ...)
assertEquals(-1d, p.getIndent(), 0); assertEquals(-1d, p.getIndent(), 0);
p.setIndent(null); p.setIndent(null);
assertNull(p.getIndent()); assertNull(p.getIndent());
assertEquals(0.0, p.getLeftMargin(), 0); assertEquals(0.0, p.getLeftMargin(), 0);

View File

@ -28,13 +28,12 @@ import java.io.InputStream;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* Centralises logic for finding/opening sample files in the test-data/spreadsheet folder. * Centralises logic for finding/opening sample files in the test-data/spreadsheet folder.
* *
* @author Josh Micich * @author Josh Micich
*/ */
public class XSSFTestDataSamples { public class XSSFTestDataSamples {
@ -63,7 +62,7 @@ public class XSSFTestDataSamples {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/** /**
* Write out workbook <code>wb</code> to {@link #TEST_OUTPUT_DIR}/testName.xlsx * Write out workbook <code>wb</code> to {@link #TEST_OUTPUT_DIR}/testName.xlsx
* (or create a temporary file if <code>TEST_OUTPUT_DIR</code> is not defined). * (or create a temporary file if <code>TEST_OUTPUT_DIR</code> is not defined).
@ -78,11 +77,13 @@ public class XSSFTestDataSamples {
writeOut(wb, file); writeOut(wb, file);
return file; return file;
} }
private static <R extends Workbook> void writeOut(R wb, File file) throws IOException { private static <R extends Workbook> void writeOut(R wb, File file) throws IOException {
IOUtils.write(wb, new FileOutputStream(file)); try (FileOutputStream out = new FileOutputStream(file)) {
wb.write(out);
}
} }
// Anticipates the location of where a workbook will be written to // Anticipates the location of where a workbook will be written to
// Note that if TEST_OUTPUT_DIR is not set, this will create temporary files // Note that if TEST_OUTPUT_DIR is not set, this will create temporary files
// with unique names. Subsequent calls with the same argument may return a different file. // with unique names. Subsequent calls with the same argument may return a different file.
@ -107,7 +108,7 @@ public class XSSFTestDataSamples {
} }
return file; return file;
} }
/** /**
* Write out workbook <code>wb</code> to a memory buffer * Write out workbook <code>wb</code> to a memory buffer
* *
@ -120,18 +121,18 @@ public class XSSFTestDataSamples {
wb.write(out); wb.write(out);
return out; return out;
} }
/** /**
* Write out the workbook then closes the workbook. * Write out the workbook then closes the workbook.
* This should be used when there is insufficient memory to have * This should be used when there is insufficient memory to have
* both workbooks open. * both workbooks open.
* *
* Make sure there are no references to any objects in the workbook * Make sure there are no references to any objects in the workbook
* so that garbage collection may free the workbook. * so that garbage collection may free the workbook.
* *
* After calling this method, null the reference to <code>wb</code>, * After calling this method, null the reference to <code>wb</code>,
* then call {@link #readBack(File)} or {@link #readBackAndDelete(File)} to re-read the file. * then call {@link #readBack(File)} or {@link #readBackAndDelete(File)} to re-read the file.
* *
* Alternatively, use {@link #writeOutAndClose(Workbook)} to use a ByteArrayOutputStream/ByteArrayInputStream * Alternatively, use {@link #writeOutAndClose(Workbook)} to use a ByteArrayOutputStream/ByteArrayInputStream
* to avoid creating a temporary file. However, this may complicate the calling * to avoid creating a temporary file. However, this may complicate the calling
* code to avoid having the workbook, BAOS, and BAIS open at the same time. * code to avoid having the workbook, BAOS, and BAIS open at the same time.
@ -152,8 +153,8 @@ public class XSSFTestDataSamples {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/** /**
* Write out workbook <code>wb</code> to a memory buffer, * Write out workbook <code>wb</code> to a memory buffer,
* then close the workbook * then close the workbook
@ -173,7 +174,7 @@ public class XSSFTestDataSamples {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/** /**
* Read back a workbook that was written out to a file with * Read back a workbook that was written out to a file with
* {@link #writeOut(Workbook, String))} or {@link #writeOutAndClose(Workbook, String)}. * {@link #writeOut(Workbook, String))} or {@link #writeOutAndClose(Workbook, String)}.
@ -186,11 +187,11 @@ public class XSSFTestDataSamples {
*/ */
public static XSSFWorkbook readBackAndDelete(File file) throws IOException { public static XSSFWorkbook readBackAndDelete(File file) throws IOException {
XSSFWorkbook wb = readBack(file); XSSFWorkbook wb = readBack(file);
// do not delete the file if there's an error--might be helpful for debugging // do not delete the file if there's an error--might be helpful for debugging
file.delete(); file.delete();
return wb; return wb;
} }
/** /**
* Read back a workbook that was written out to a file with * Read back a workbook that was written out to a file with
* {@link #writeOut(Workbook, String)} or {@link #writeOutAndClose(Workbook, String)}. * {@link #writeOut(Workbook, String)} or {@link #writeOutAndClose(Workbook, String)}.
@ -208,12 +209,12 @@ public class XSSFTestDataSamples {
in.close(); in.close();
} }
} }
/** /**
* Read back a workbook that was written out to a memory buffer with * Read back a workbook that was written out to a memory buffer with
* {@link #writeOut(Workbook)} or {@link #writeOutAndClose(Workbook)}. * {@link #writeOut(Workbook)} or {@link #writeOutAndClose(Workbook)}.
* *
* @param file the workbook file to read * @param out the output stream to read back from
* @return the read back workbook * @return the read back workbook
* @throws IOException * @throws IOException
*/ */
@ -227,15 +228,15 @@ public class XSSFTestDataSamples {
is.close(); is.close();
} }
} }
/** /**
* Write out and read back using a memory buffer to avoid disk I/O. * Write out and read back using a memory buffer to avoid disk I/O.
* If there is not enough memory to have two workbooks open at the same time, * If there is not enough memory to have two workbooks open at the same time,
* consider using: * consider using:
* *
* Workbook wb = new XSSFWorkbook(); * Workbook wb = new XSSFWorkbook();
* String testName = "example"; * String testName = "example";
* *
* <code> * <code>
* File file = writeOutAndClose(wb, testName); * File file = writeOutAndClose(wb, testName);
* // clear all references that would prevent the workbook from getting garbage collected * // clear all references that would prevent the workbook from getting garbage collected
@ -257,7 +258,7 @@ public class XSSFTestDataSamples {
R r = (R) result; R r = (R) result;
return r; return r;
} }
/** /**
* Write out, close, and read back the workbook using a memory buffer to avoid disk I/O. * Write out, close, and read back the workbook using a memory buffer to avoid disk I/O.
* *
@ -274,18 +275,18 @@ public class XSSFTestDataSamples {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
R r = (R) result; R r = (R) result;
return r; return r;
} }
/** /**
* Writes the Workbook either into a file or into a byte array, depending on presence of * Writes the Workbook either into a file or into a byte array, depending on presence of
* the system property {@value #TEST_OUTPUT_DIR}, and reads it in a new instance of the Workbook back. * the system property {@value #TEST_OUTPUT_DIR}, and reads it in a new instance of the Workbook back.
* If TEST_OUTPUT_DIR is set, the file will NOT be deleted at the end of this function. * If TEST_OUTPUT_DIR is set, the file will NOT be deleted at the end of this function.
* @param wb workbook to write * @param wb workbook to write
* @param testName file name to be used if writing into a file. The old file with the same name will be overridden. * @param testName file name to be used if writing into a file. The old file with the same name will be overridden.
* @return new instance read from the stream written by the wb parameter. * @return new instance read from the stream written by the wb parameter.
*/ */
public static <R extends Workbook> R writeOutAndReadBack(R wb, String testName) { public static <R extends Workbook> R writeOutAndReadBack(R wb, String testName) {
if (System.getProperty(TEST_OUTPUT_DIR) == null) { if (System.getProperty(TEST_OUTPUT_DIR) == null) {
return writeOutAndReadBack(wb); return writeOutAndReadBack(wb);

View File

@ -47,15 +47,15 @@ import java.util.TreeMap;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.ooxml.POIXMLProperties;
import org.apache.poi.common.usermodel.HyperlinkType; import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.ooxml.POIXMLProperties;
import org.apache.poi.ooxml.util.DocumentHelper; import org.apache.poi.ooxml.util.DocumentHelper;
import org.apache.poi.ooxml.util.SAXHelper; import org.apache.poi.ooxml.util.SAXHelper;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
@ -82,7 +82,31 @@ import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.NumberEval; import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.functions.Function; import org.apache.poi.ss.formula.functions.Function;
import org.apache.poi.ss.formula.ptg.Ptg; import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.SheetConditionalFormatting;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
@ -2261,7 +2285,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
* problems when deleting columns, conditionally to stop recursion * problems when deleting columns, conditionally to stop recursion
*/ */
private static final String FORMULA1 = private static final String FORMULA1 =
"IF( INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) = 0, 0," "IF( INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) = 0, 0, "
+ "INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) ) + 2"; + "INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) ) + 2";
/** /**
@ -2269,7 +2293,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
* problems when deleting rows, conditionally to stop recursion * problems when deleting rows, conditionally to stop recursion
*/ */
private static final String FORMULA2 = private static final String FORMULA2 =
"IF( INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) = 0, 0," "IF( INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) = 0, 0, "
+ "INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) ) + 2"; + "INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) ) + 2";
/** /**
@ -2847,7 +2871,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test @Test
public void test57236() throws IOException { public void test57236() throws IOException {
// Having very small numbers leads to different formatting, Excel uses the scientific notation, but POI leads to "0" // Having very small numbers leads to different formatting, Excel uses the scientific notation, but POI leads to "0"
/* /*
DecimalFormat format = new DecimalFormat("#.##########", new DecimalFormatSymbols(Locale.getDefault())); DecimalFormat format = new DecimalFormat("#.##########", new DecimalFormatSymbols(Locale.getDefault()));
double d = 3.0E-104; double d = 3.0E-104;
@ -3290,7 +3314,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
wb.close(); wb.close();
} }
/** /**
* Auto column sizing failed when there were loads of fonts with * Auto column sizing failed when there were loads of fonts with
* errors like ArrayIndexOutOfBoundsException: -32765 * errors like ArrayIndexOutOfBoundsException: -32765
@ -3300,7 +3324,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0); XSSFRow row = sheet.createRow(0);
// Create lots of fonts // Create lots of fonts
XSSFDataFormat formats = wb.createDataFormat(); XSSFDataFormat formats = wb.createDataFormat();
XSSFFont[] fonts = new XSSFFont[50000]; XSSFFont[] fonts = new XSSFFont[50000];
@ -3309,23 +3333,23 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
font.setFontHeight(i); font.setFontHeight(i);
fonts[i] = font; fonts[i] = font;
} }
// Create a moderate number of columns, which use // Create a moderate number of columns, which use
// fonts from the start and end of the font list // fonts from the start and end of the font list
final int numCols = 125; final int numCols = 125;
for (int i=0; i<numCols; i++) { for (int i=0; i<numCols; i++) {
XSSFCellStyle cs = wb.createCellStyle(); XSSFCellStyle cs = wb.createCellStyle();
cs.setDataFormat(formats.getFormat("'Test "+i+"' #,###")); cs.setDataFormat(formats.getFormat("'Test "+i+"' #,###"));
XSSFFont font = fonts[i]; XSSFFont font = fonts[i];
if (i%2==1) { font = fonts[fonts.length-i]; } if (i%2==1) { font = fonts[fonts.length-i]; }
cs.setFont(font); cs.setFont(font);
XSSFCell c = row.createCell(i); XSSFCell c = row.createCell(i);
c.setCellValue(i); c.setCellValue(i);
c.setCellStyle(cs); c.setCellStyle(cs);
} }
// Do the auto-size // Do the auto-size
for (int i=0; i<numCols; i++) { for (int i=0; i<numCols; i++) {
sheet.autoSizeColumn(i); sheet.autoSizeColumn(i);

View File

@ -33,20 +33,20 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
* Test asserts the POI produces &lt;cols&gt; element that could be read and properly interpreted by the MS Excel. * Test asserts the POI produces &lt;cols&gt; element that could be read and properly interpreted by the MS Excel.
* For specification of the "cols" element see the chapter 3.3.1.16 of the "Office Open XML Part 4 - Markup Language Reference.pdf". * For specification of the "cols" element see the chapter 3.3.1.16 of the "Office Open XML Part 4 - Markup Language Reference.pdf".
* The specification can be downloaded at http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip. * The specification can be downloaded at http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip.
* *
* <p><em> * <p><em>
* The test saves xlsx file on a disk if the system property is set: * The test saves xlsx file on a disk if the system property is set:
* -Dpoi.test.xssf.output.dir=${workspace_loc}/poi/build/xssf-output * -Dpoi.test.xssf.output.dir=${workspace_loc}/poi/build/xssf-output
* </em> * </em>
* *
*/ */
public class TestXSSFColGrouping { public class TestXSSFColGrouping {
private static final POILogger logger = POILogFactory.getLogger(TestXSSFColGrouping.class); private static final POILogger logger = POILogFactory.getLogger(TestXSSFColGrouping.class);
/** /**
* Tests that POI doesn't produce "col" elements without "width" attribute. * Tests that POI doesn't produce "col" elements without "width" attribute.
* POI-52186 * POI-52186
*/ */
@Test @Test
@ -56,25 +56,25 @@ public class TestXSSFColGrouping {
sheet.setColumnWidth(4, 5000); sheet.setColumnWidth(4, 5000);
sheet.setColumnWidth(5, 5000); sheet.setColumnWidth(5, 5000);
sheet.groupColumn((short) 4, (short) 7); sheet.groupColumn((short) 4, (short) 7);
sheet.groupColumn((short) 9, (short) 12); sheet.groupColumn((short) 9, (short) 12);
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGrouping"); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGrouping");
sheet = wb2.getSheet("test"); sheet = wb2.getSheet("test");
CTCols cols = sheet.getCTWorksheet().getColsArray(0); CTCols cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "test52186/cols:" + cols); logger.log(POILogger.DEBUG, "test52186/cols:" + cols);
for (CTCol col : cols.getColArray()) { for (CTCol col : cols.getColArray()) {
assertTrue("Col width attribute is unset: " + col, col.isSetWidth()); assertTrue("Col width attribute is unset: " + col, col.isSetWidth());
} }
wb2.close(); wb2.close();
wb1.close(); wb1.close();
} }
/** /**
* Tests that POI doesn't produce "col" elements without "width" attribute. * Tests that POI doesn't produce "col" elements without "width" attribute.
* POI-52186 * POI-52186
*/ */
@Test @Test
@ -84,17 +84,17 @@ public class TestXSSFColGrouping {
sheet.setColumnWidth(4, 5000); sheet.setColumnWidth(4, 5000);
sheet.setColumnWidth(5, 5000); sheet.setColumnWidth(5, 5000);
sheet.groupColumn((short) 4, (short) 5); sheet.groupColumn((short) 4, (short) 5);
sheet.setColumnGroupCollapsed(4, true); sheet.setColumnGroupCollapsed(4, true);
CTCols cols = sheet.getCTWorksheet().getColsArray(0); CTCols cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "test52186_2/cols:" + cols); logger.log(POILogger.DEBUG, "test52186_2/cols:" + cols);
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGroupingAndCollapsing"); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGroupingAndCollapsing");
sheet = wb2.getSheet("test"); sheet = wb2.getSheet("test");
for (int i = 4; i <= 5; i++) { for (int i = 4; i <= 5; i++) {
assertEquals("Unexpected width of column "+ i, 5000, sheet.getColumnWidth(i)); assertEquals("Unexpected width of column "+ i, 5000, sheet.getColumnWidth(i));
} }
@ -105,7 +105,7 @@ public class TestXSSFColGrouping {
wb2.close(); wb2.close();
wb1.close(); wb1.close();
} }
/** /**
* Test the cols element is correct in case of NumericRanges.OVERLAPS_2_WRAPS * Test the cols element is correct in case of NumericRanges.OVERLAPS_2_WRAPS
*/ */
@ -122,10 +122,10 @@ public class TestXSSFColGrouping {
col.setCustomWidth(true); col.setCustomWidth(true);
sheet.groupColumn((short) 2, (short) 3); sheet.groupColumn((short) 2, (short) 3);
sheet.getCTWorksheet().getColsArray(0); sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_WRAPS/cols:" + cols); logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_WRAPS/cols:" + cols);
assertEquals(0, cols.getColArray(0).getOutlineLevel()); assertEquals(0, cols.getColArray(0).getOutlineLevel());
assertEquals(2, cols.getColArray(0).getMin()); // 1 based assertEquals(2, cols.getColArray(0).getMin()); // 1 based
assertEquals(2, cols.getColArray(0).getMax()); // 1 based assertEquals(2, cols.getColArray(0).getMax()); // 1 based
@ -133,23 +133,23 @@ public class TestXSSFColGrouping {
assertEquals(1, cols.getColArray(1).getOutlineLevel()); assertEquals(1, cols.getColArray(1).getOutlineLevel());
assertEquals(3, cols.getColArray(1).getMin()); // 1 based assertEquals(3, cols.getColArray(1).getMin()); // 1 based
assertEquals(4, cols.getColArray(1).getMax()); // 1 based assertEquals(4, cols.getColArray(1).getMax()); // 1 based
assertEquals(true, cols.getColArray(1).getCustomWidth()); assertEquals(true, cols.getColArray(1).getCustomWidth());
assertEquals(0, cols.getColArray(2).getOutlineLevel()); assertEquals(0, cols.getColArray(2).getOutlineLevel());
assertEquals(5, cols.getColArray(2).getMin()); // 1 based assertEquals(5, cols.getColArray(2).getMin()); // 1 based
assertEquals(5, cols.getColArray(2).getMax()); // 1 based assertEquals(5, cols.getColArray(2).getMax()); // 1 based
assertEquals(true, cols.getColArray(2).getCustomWidth()); assertEquals(true, cols.getColArray(2).getCustomWidth());
assertEquals(3, cols.sizeOfColArray()); assertEquals(3, cols.sizeOfColArray());
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_WRAPS"); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_WRAPS");
sheet = wb2.getSheet("test"); sheet = wb2.getSheet("test");
for (int i = 1; i <= 4; i++) { for (int i = 1; i <= 4; i++) {
assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i));
} }
wb2.close(); wb2.close();
wb1.close(); wb1.close();
} }
@ -170,10 +170,10 @@ public class TestXSSFColGrouping {
col.setCustomWidth(true); col.setCustomWidth(true);
sheet.groupColumn((short) 1, (short) 5); sheet.groupColumn((short) 1, (short) 5);
cols = sheet.getCTWorksheet().getColsArray(0); cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_WRAPS/cols:" + cols); logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_WRAPS/cols:" + cols);
assertEquals(1, cols.getColArray(0).getOutlineLevel()); assertEquals(1, cols.getColArray(0).getOutlineLevel());
assertEquals(2, cols.getColArray(0).getMin()); // 1 based assertEquals(2, cols.getColArray(0).getMin()); // 1 based
assertEquals(2, cols.getColArray(0).getMax()); // 1 based assertEquals(2, cols.getColArray(0).getMax()); // 1 based
@ -181,23 +181,23 @@ public class TestXSSFColGrouping {
assertEquals(1, cols.getColArray(1).getOutlineLevel()); assertEquals(1, cols.getColArray(1).getOutlineLevel());
assertEquals(3, cols.getColArray(1).getMin()); // 1 based assertEquals(3, cols.getColArray(1).getMin()); // 1 based
assertEquals(5, cols.getColArray(1).getMax()); // 1 based assertEquals(5, cols.getColArray(1).getMax()); // 1 based
assertEquals(true, cols.getColArray(1).getCustomWidth()); assertEquals(true, cols.getColArray(1).getCustomWidth());
assertEquals(1, cols.getColArray(2).getOutlineLevel()); assertEquals(1, cols.getColArray(2).getOutlineLevel());
assertEquals(6, cols.getColArray(2).getMin()); // 1 based assertEquals(6, cols.getColArray(2).getMin()); // 1 based
assertEquals(6, cols.getColArray(2).getMax()); // 1 based assertEquals(6, cols.getColArray(2).getMax()); // 1 based
assertEquals(false, cols.getColArray(2).getCustomWidth()); assertEquals(false, cols.getColArray(2).getCustomWidth());
assertEquals(3, cols.sizeOfColArray()); assertEquals(3, cols.sizeOfColArray());
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_WRAPS"); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_WRAPS");
sheet = wb2.getSheet("test"); sheet = wb2.getSheet("test");
for (int i = 2; i <= 4; i++) { for (int i = 2; i <= 4; i++) {
assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i));
} }
wb2.close(); wb2.close();
wb1.close(); wb1.close();
} }
@ -218,7 +218,7 @@ public class TestXSSFColGrouping {
col.setCustomWidth(true); col.setCustomWidth(true);
sheet.groupColumn((short) 3, (short) 5); sheet.groupColumn((short) 3, (short) 5);
cols = sheet.getCTWorksheet().getColsArray(0); cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_MINOR/cols:" + cols); logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_MINOR/cols:" + cols);
@ -229,24 +229,24 @@ public class TestXSSFColGrouping {
assertEquals(1, cols.getColArray(1).getOutlineLevel()); assertEquals(1, cols.getColArray(1).getOutlineLevel());
assertEquals(4, cols.getColArray(1).getMin()); // 1 based assertEquals(4, cols.getColArray(1).getMin()); // 1 based
assertEquals(5, cols.getColArray(1).getMax()); // 1 based assertEquals(5, cols.getColArray(1).getMax()); // 1 based
assertEquals(true, cols.getColArray(1).getCustomWidth()); assertEquals(true, cols.getColArray(1).getCustomWidth());
assertEquals(1, cols.getColArray(2).getOutlineLevel()); assertEquals(1, cols.getColArray(2).getOutlineLevel());
assertEquals(6, cols.getColArray(2).getMin()); // 1 based assertEquals(6, cols.getColArray(2).getMin()); // 1 based
assertEquals(6, cols.getColArray(2).getMax()); // 1 based assertEquals(6, cols.getColArray(2).getMax()); // 1 based
assertEquals(false, cols.getColArray(2).getCustomWidth()); assertEquals(false, cols.getColArray(2).getCustomWidth());
assertEquals(3, cols.sizeOfColArray()); assertEquals(3, cols.sizeOfColArray());
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_MINOR"); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_MINOR");
sheet = wb2.getSheet("test"); sheet = wb2.getSheet("test");
for (int i = 2; i <= 4; i++) { for (int i = 2; i <= 4; i++) {
assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); assertEquals("Unexpected width of column "+ i, 20 * 256L, sheet.getColumnWidth(i));
} }
assertEquals("Unexpected width of column "+ 5, sheet.getDefaultColumnWidth() * 256, sheet.getColumnWidth(5)); assertEquals("Unexpected width of column "+ 5, sheet.getDefaultColumnWidth() * 256L, sheet.getColumnWidth(5));
wb2.close(); wb2.close();
wb1.close(); wb1.close();
} }
@ -267,7 +267,7 @@ public class TestXSSFColGrouping {
col.setCustomWidth(true); col.setCustomWidth(true);
sheet.groupColumn((short) 1, (short) 3); sheet.groupColumn((short) 1, (short) 3);
cols = sheet.getCTWorksheet().getColsArray(0); cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_MINOR/cols:" + cols); logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_MINOR/cols:" + cols);
@ -278,24 +278,24 @@ public class TestXSSFColGrouping {
assertEquals(1, cols.getColArray(1).getOutlineLevel()); assertEquals(1, cols.getColArray(1).getOutlineLevel());
assertEquals(3, cols.getColArray(1).getMin()); // 1 based assertEquals(3, cols.getColArray(1).getMin()); // 1 based
assertEquals(4, cols.getColArray(1).getMax()); // 1 based assertEquals(4, cols.getColArray(1).getMax()); // 1 based
assertEquals(true, cols.getColArray(1).getCustomWidth()); assertEquals(true, cols.getColArray(1).getCustomWidth());
assertEquals(0, cols.getColArray(2).getOutlineLevel()); assertEquals(0, cols.getColArray(2).getOutlineLevel());
assertEquals(5, cols.getColArray(2).getMin()); // 1 based assertEquals(5, cols.getColArray(2).getMin()); // 1 based
assertEquals(5, cols.getColArray(2).getMax()); // 1 based assertEquals(5, cols.getColArray(2).getMax()); // 1 based
assertEquals(true, cols.getColArray(2).getCustomWidth()); assertEquals(true, cols.getColArray(2).getCustomWidth());
assertEquals(3, cols.sizeOfColArray()); assertEquals(3, cols.sizeOfColArray());
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_MINOR"); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_MINOR");
sheet = wb2.getSheet("test"); sheet = wb2.getSheet("test");
for (int i = 2; i <= 4; i++) { for (int i = 2; i <= 4; i++) {
assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); assertEquals("Unexpected width of column "+ i, 20 * 256L, sheet.getColumnWidth(i));
} }
assertEquals("Unexpected width of column "+ 1, sheet.getDefaultColumnWidth() * 256, sheet.getColumnWidth(1)); assertEquals("Unexpected width of column "+ 1, sheet.getDefaultColumnWidth() * 256L, sheet.getColumnWidth(1));
wb2.close(); wb2.close();
wb1.close(); wb1.close();
} }

View File

@ -23,7 +23,6 @@ import java.math.BigDecimal;
import java.util.List; import java.util.List;
import org.apache.poi.ss.formula.DataValidationEvaluator; import org.apache.poi.ss.formula.DataValidationEvaluator;
import org.apache.poi.ss.formula.WorkbookEvaluator;
import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.usermodel.BaseTestDataValidation; import org.apache.poi.ss.usermodel.BaseTestDataValidation;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
@ -57,16 +56,16 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
/** /**
* For each validation type, there are two cells with the same validation. This tests * For each validation type, there are two cells with the same validation. This tests
* application of a single validation definition to multiple cells. * application of a single validation definition to multiple cells.
* *
* For list ( 3 validations for explicit and 3 for formula ) * For list ( 3 validations for explicit and 3 for formula )
* - one validation that allows blank. * - one validation that allows blank.
* - one that does not allow blank. * - one that does not allow blank.
* - one that does not show the drop down arrow. * - one that does not show the drop down arrow.
* = 2 * = 2
* *
* For number validations ( integer/decimal and text length ) with 8 different types of operators. * For number validations ( integer/decimal and text length ) with 8 different types of operators.
* = 50 * = 50
* *
* = 52 ( Total ) * = 52 ( Total )
*/ */
assertEquals(52,dataValidations.size()); assertEquals(52,dataValidations.size());
@ -140,7 +139,7 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
cell_10.setCellValue(XSSFDataValidation.operatorTypeMappings.get(operatorType).toString()); cell_10.setCellValue(XSSFDataValidation.operatorTypeMappings.get(operatorType).toString());
Cell cell_11 = row1.createCell(1); Cell cell_11 = row1.createCell(1);
Cell cell_21 = row1.createCell(2); Cell cell_21 = row1.createCell(2);
Cell cell_22 = i==0 && j < 2 ? row2.createCell(2) : null; Cell cell_22 = i==0 && j < 2 ? (row2 == null ? null : row2.createCell(2)) : null;
Cell cell_13 = row1.createCell(3); Cell cell_13 = row1.createCell(3);
@ -170,7 +169,9 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size());
cellRangeAddressList = new CellRangeAddressList(); cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_22.getRowIndex(), cell_22.getRowIndex(), cell_22.getColumnIndex(), cell_22.getColumnIndex())); if (cell_22 != null) {
cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_22.getRowIndex(), cell_22.getRowIndex(), cell_22.getColumnIndex(), cell_22.getColumnIndex()));
}
validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList);
setOtherValidationParameters( validation); setOtherValidationParameters( validation);
sheet.addValidationData(validation); sheet.addValidationData(validation);
@ -178,7 +179,9 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
} else if(i==0 && j==1 ){ } else if(i==0 && j==1 ){
cellRangeAddressList = new CellRangeAddressList(); cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex()));
cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_22.getRowIndex(), cell_22.getRowIndex(), cell_22.getColumnIndex(), cell_22.getColumnIndex())); if (cell_22 != null) {
cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_22.getRowIndex(), cell_22.getRowIndex(), cell_22.getColumnIndex(), cell_22.getColumnIndex()));
}
validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList);
setOtherValidationParameters( validation); setOtherValidationParameters( validation);
sheet.addValidationData(validation); sheet.addValidationData(validation);
@ -262,16 +265,16 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
List<XSSFDataValidation> lst = sheet.getDataValidations(); //<-- works List<XSSFDataValidation> lst = sheet.getDataValidations(); //<-- works
assertEquals(0, lst.size()); assertEquals(0, lst.size());
//create the cell that will have the validation applied //create the cell that will have the validation applied
sheet.createRow(0).createCell(0); sheet.createRow(0).createCell(0);
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500"); DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); DataValidation validation = dataValidationHelper.createValidation(constraint, addressList);
sheet.addValidationData(validation); sheet.addValidationData(validation);
// this line caused XmlValueOutOfRangeException , see Bugzilla 3965 // this line caused XmlValueOutOfRangeException , see Bugzilla 3965
lst = sheet.getDataValidations(); lst = sheet.getDataValidations();
assertEquals(1, lst.size()); assertEquals(1, lst.size());
@ -282,10 +285,10 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
public void testDefaultErrorStyle() throws IOException { public void testDefaultErrorStyle() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) { try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
final XSSFDataValidation validation = createValidation(sheet); final XSSFDataValidation validation = createValidation(sheet);
sheet.addValidationData(validation); sheet.addValidationData(validation);
final List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); final List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
assertEquals(DataValidation.ErrorStyle.STOP, dataValidations.get(0).getErrorStyle()); assertEquals(DataValidation.ErrorStyle.STOP, dataValidations.get(0).getErrorStyle());
} }
@ -295,22 +298,22 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
public void testSetErrorStyles() throws IOException { public void testSetErrorStyles() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) { try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
XSSFDataValidation validation = createValidation(sheet); XSSFDataValidation validation = createValidation(sheet);
sheet.addValidationData(validation); sheet.addValidationData(validation);
// extract generated validation from sheet // extract generated validation from sheet
List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
validation = dataValidations.get(0); validation = dataValidations.get(0);
// test INFO // test INFO
validation.setErrorStyle(DataValidation.ErrorStyle.INFO); validation.setErrorStyle(DataValidation.ErrorStyle.INFO);
assertEquals(DataValidation.ErrorStyle.INFO, dataValidations.get(0).getErrorStyle()); assertEquals(DataValidation.ErrorStyle.INFO, dataValidations.get(0).getErrorStyle());
// test WARNING // test WARNING
validation.setErrorStyle(DataValidation.ErrorStyle.WARNING); validation.setErrorStyle(DataValidation.ErrorStyle.WARNING);
assertEquals(DataValidation.ErrorStyle.WARNING, dataValidations.get(0).getErrorStyle()); assertEquals(DataValidation.ErrorStyle.WARNING, dataValidations.get(0).getErrorStyle());
// test STOP // test STOP
validation.setErrorStyle(DataValidation.ErrorStyle.STOP); validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
assertEquals(DataValidation.ErrorStyle.STOP, dataValidations.get(0).getErrorStyle()); assertEquals(DataValidation.ErrorStyle.STOP, dataValidations.get(0).getErrorStyle());
@ -321,10 +324,10 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
public void testDefaultAllowBlank() throws IOException { public void testDefaultAllowBlank() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) { try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
final XSSFDataValidation validation = createValidation(sheet); final XSSFDataValidation validation = createValidation(sheet);
sheet.addValidationData(validation); sheet.addValidationData(validation);
final List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); final List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
assertEquals(true, dataValidations.get(0).getCtDdataValidation().getAllowBlank()); assertEquals(true, dataValidations.get(0).getCtDdataValidation().getAllowBlank());
} }
@ -334,12 +337,12 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
public void testSetAllowBlankToFalse() throws IOException { public void testSetAllowBlankToFalse() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) { try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
final XSSFDataValidation validation = createValidation(sheet); final XSSFDataValidation validation = createValidation(sheet);
validation.getCtDdataValidation().setAllowBlank(false); validation.getCtDdataValidation().setAllowBlank(false);
sheet.addValidationData(validation); sheet.addValidationData(validation);
final List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); final List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
assertEquals(false, dataValidations.get(0).getCtDdataValidation().getAllowBlank()); assertEquals(false, dataValidations.get(0).getCtDdataValidation().getAllowBlank());
} }
@ -349,12 +352,12 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
public void testSetAllowBlankToTrue() throws IOException { public void testSetAllowBlankToTrue() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) { try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
final XSSFDataValidation validation = createValidation(sheet); final XSSFDataValidation validation = createValidation(sheet);
validation.getCtDdataValidation().setAllowBlank(true); validation.getCtDdataValidation().setAllowBlank(true);
sheet.addValidationData(validation); sheet.addValidationData(validation);
final List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); final List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
assertEquals(true, dataValidations.get(0).getCtDdataValidation().getAllowBlank()); assertEquals(true, dataValidations.get(0).getCtDdataValidation().getAllowBlank());
} }
@ -370,7 +373,7 @@ public class TestXSSFDataValidation extends BaseTestDataValidation {
DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("true"); DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("true");
return (XSSFDataValidation) dataValidationHelper.createValidation(constraint, new CellRangeAddressList(0, 0, 0, 0)); return (XSSFDataValidation) dataValidationHelper.createValidation(constraint, new CellRangeAddressList(0, 0, 0, 0));
} }
@Test @Test
public void testTableBasedValidationList() throws IOException { public void testTableBasedValidationList() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("dataValidationTableRange.xlsx")) { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("dataValidationTableRange.xlsx")) {

View File

@ -36,8 +36,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.poifs.crypt.CryptoFunctions; import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.ss.usermodel.AutoFilter; import org.apache.poi.ss.usermodel.AutoFilter;
@ -158,7 +158,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals("", ftr.getLeft()); assertEquals("", ftr.getLeft());
assertEquals("", ftr.getCenter()); assertEquals("", ftr.getCenter());
assertEquals("", ftr.getRight()); assertEquals("", ftr.getRight());
wb2.close(); wb2.close();
} }
@ -200,7 +200,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// Defaults are odd // Defaults are odd
assertEquals("odd footer left", sheet.getFooter().getLeft()); assertEquals("odd footer left", sheet.getFooter().getLeft());
assertEquals("odd header center", sheet.getHeader().getCenter()); assertEquals("odd header center", sheet.getHeader().getCenter());
workbook.close(); workbook.close();
} }
@ -265,7 +265,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
sheet.createSplitPane(4, 8, 12, 12, 1); sheet.createSplitPane(4, 8, 12, 12, 1);
assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0); assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0);
assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane());
workbook.close(); workbook.close();
} }
@ -374,7 +374,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
colArray = cols.getColArray(); colArray = cols.getColArray();
assertEquals(4, colArray.length); assertEquals(4, colArray.length);
assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol()); assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol());
workbook.close(); workbook.close();
} }
@ -411,7 +411,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals(3, sheet.getPhysicalNumberOfRows()); assertEquals(3, sheet.getPhysicalNumberOfRows());
assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow());
workbook.close(); workbook.close();
} }
@ -553,10 +553,10 @@ public final class TestXSSFSheet extends BaseTestXSheet {
checkColumnGroup(cols.getColArray(3), 10, 11); // false, true checkColumnGroup(cols.getColArray(3), 10, 11); // false, true
checkColumnGroup(cols.getColArray(4), 12, 12, false, false); checkColumnGroup(cols.getColArray(4), 12, 12, false, false);
checkColumnGroup(cols.getColArray(5), 13, 13, false, false); checkColumnGroup(cols.getColArray(5), 13, 13, false, false);
wb2.close(); wb2.close();
} }
/** /**
* Verify that column groups were created correctly after Sheet.groupColumn * Verify that column groups were created correctly after Sheet.groupColumn
* *
@ -575,7 +575,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals("isSetHidden", isSetHidden, col.isSetHidden()); assertEquals("isSetHidden", isSetHidden, col.isSetHidden());
assertEquals("isSetCollapsed", isSetCollapsed, col.isSetCollapsed()); //not necessarily set assertEquals("isSetCollapsed", isSetCollapsed, col.isSetCollapsed()); //not necessarily set
} }
/** /**
* Verify that column groups were created correctly after Sheet.groupColumn * Verify that column groups were created correctly after Sheet.groupColumn
* *
@ -708,7 +708,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(16).getCTRow().isSetHidden());
assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed());
assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(18).getCTRow().isSetHidden());
wb2.close(); wb2.close();
} }
@ -755,7 +755,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals(4, col.getMax()); assertEquals(4, col.getMax());
assertEquals(33.0, col.getWidth(), 0.0); assertEquals(33.0, col.getWidth(), 0.0);
assertTrue(col.getCustomWidth()); assertTrue(col.getCustomWidth());
workbook.close(); workbook.close();
} }
@ -801,7 +801,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
//now the span is splitted into 5 individual columns //now the span is splitted into 5 individual columns
assertEquals(5, cols.sizeOfColArray()); assertEquals(5, cols.sizeOfColArray());
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
assertEquals(cw[i]*256, sheet.getColumnWidth(i)); assertEquals(cw[i]*256L, sheet.getColumnWidth(i));
assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0);
} }
@ -812,10 +812,10 @@ public final class TestXSSFSheet extends BaseTestXSheet {
cols = sheet.getCTWorksheet().getColsArray(0); cols = sheet.getCTWorksheet().getColsArray(0);
assertEquals(5, cols.sizeOfColArray()); assertEquals(5, cols.sizeOfColArray());
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
assertEquals(cw[i]*256, sheet.getColumnWidth(i)); assertEquals(cw[i]*256L, sheet.getColumnWidth(i));
assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0);
} }
wb2.close(); wb2.close();
} }
@ -889,7 +889,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertFalse(sheet.isColumnHidden(3)); assertFalse(sheet.isColumnHidden(3));
assertFalse(sheet.isColumnHidden(4)); assertFalse(sheet.isColumnHidden(4));
assertFalse(sheet.isColumnHidden(5)); assertFalse(sheet.isColumnHidden(5));
wb2.close(); wb2.close();
} }
@ -920,7 +920,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
//comment1 and comment2 are different objects //comment1 and comment2 are different objects
assertNotSame(comment1, comment2); assertNotSame(comment1, comment2);
wb1.close(); wb1.close();
//now test against a workbook containing cell comments //now test against a workbook containing cell comments
XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx"); XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx");
sheet1 = wb2.getSheetAt(0); sheet1 = wb2.getSheetAt(0);
@ -928,7 +928,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertNotNull(comment1); assertNotNull(comment1);
assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName()); assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName());
assertSame(comment1, sheet1.getCommentsTable(true)); assertSame(comment1, sheet1.getCommentsTable(true));
wb2.close(); wb2.close();
} }
@ -1034,7 +1034,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertTrue(nm.getCTName().getHidden()); assertTrue(nm.getCTName().getHidden());
assertEquals("_xlnm._FilterDatabase", nm.getCTName().getName()); assertEquals("_xlnm._FilterDatabase", nm.getCTName().getName());
assertEquals("'new sheet'!$A$1:$D$100", nm.getCTName().getStringValue()); assertEquals("'new sheet'!$A$1:$D$100", nm.getCTName().getStringValue());
wb.close(); wb.close();
} }
@ -1057,7 +1057,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
sheet.protectSheet(null); sheet.protectSheet(null);
assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection()); assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection());
wb.close(); wb.close();
} }
@ -1095,12 +1095,12 @@ public final class TestXSSFSheet extends BaseTestXSheet {
wb1.close(); wb1.close();
assertTrue(wb2.getSheetAt(0).validateSheetPassword(password)); assertTrue(wb2.getSheetAt(0).validateSheetPassword(password));
wb2.close(); wb2.close();
XSSFWorkbook wb3 = openSampleWorkbook("workbookProtection-sheet_password-2013.xlsx"); XSSFWorkbook wb3 = openSampleWorkbook("workbookProtection-sheet_password-2013.xlsx");
assertTrue(wb3.getSheetAt(0).validateSheetPassword("pwd")); assertTrue(wb3.getSheetAt(0).validateSheetPassword("pwd"));
wb3.close(); wb3.close();
} }
@Test @Test
public void bug49966() throws IOException { public void bug49966() throws IOException {
@ -1161,7 +1161,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
XSSFSheet sheet = wb1.createSheet("Sheet 1"); XSSFSheet sheet = wb1.createSheet("Sheet 1");
assertFalse(sheet.getForceFormulaRecalculation()); assertFalse(sheet.getForceFormulaRecalculation());
// Set // Set
sheet.setForceFormulaRecalculation(true); sheet.setForceFormulaRecalculation(true);
assertTrue(sheet.getForceFormulaRecalculation()); assertTrue(sheet.getForceFormulaRecalculation());
@ -1221,7 +1221,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
} }
swb.close(); swb.close();
} }
wb.close(); wb.close();
} }
@ -1246,7 +1246,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
} }
swb.close(); swb.close();
} }
wb.close(); wb.close();
} }
@ -1295,7 +1295,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0);
assertNotNull(name); assertNotNull(name);
assertEquals("Sheet0!$B:$C", name.getRefersToFormula()); assertEquals("Sheet0!$B:$C", name.getRefersToFormula());
wb.close(); wb.close();
} }
@ -1389,7 +1389,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
XSSFPivotTable pivotTable = sheet2.createPivotTable XSSFPivotTable pivotTable = sheet2.createPivotTable
(wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5"), sheet1); (wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5"), sheet1);
assertEquals(0, pivotTable.getRowLabelColumns().size()); assertEquals(0, pivotTable.getRowLabelColumns().size());
assertEquals(1, wb.getPivotTables().size()); assertEquals(1, wb.getPivotTables().size());
assertEquals(0, sheet1.getPivotTables().size()); assertEquals(0, sheet1.getPivotTables().size());
assertEquals(1, sheet2.getPivotTables().size()); assertEquals(1, sheet2.getPivotTables().size());
@ -1421,12 +1421,12 @@ public final class TestXSSFSheet extends BaseTestXSheet {
sheet2); sheet2);
wb.close(); wb.close();
} }
@Test(expected=POIXMLException.class) @Test(expected=POIXMLException.class)
public void testReadFails() throws IOException { public void testReadFails() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
// Throws exception because we cannot read here // Throws exception because we cannot read here
try { try {
sheet.onDocumentRead(); sheet.onDocumentRead();
@ -1434,8 +1434,8 @@ public final class TestXSSFSheet extends BaseTestXSheet {
wb.close(); wb.close();
} }
} }
/** /**
* This would be better off as a testable example rather than a simple unit test * This would be better off as a testable example rather than a simple unit test
* since Sheet.createComment() was deprecated and removed. * since Sheet.createComment() was deprecated and removed.
* https://poi.apache.org/spreadsheet/quick-guide.html#CellComments * https://poi.apache.org/spreadsheet/quick-guide.html#CellComments
@ -1450,7 +1450,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertNotNull(comment); assertNotNull(comment);
wb.close(); wb.close();
} }
protected void testCopyOneRow(String copyRowsTestWorkbook) throws IOException { protected void testCopyOneRow(String copyRowsTestWorkbook) throws IOException {
final double FLOAT_PRECISION = 1e-9; final double FLOAT_PRECISION = 1e-9;
final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook); final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook);
@ -1496,24 +1496,24 @@ public final class TestXSSFSheet extends BaseTestXSheet {
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
assertEquals("[String] G7 cell type", CellType.STRING, cell.getCellType()); assertEquals("[String] G7 cell type", CellType.STRING, cell.getCellType());
assertEquals("[String] G7 cell value", "Hello", cell.getStringCellValue()); assertEquals("[String] G7 cell value", "Hello", cell.getStringCellValue());
// Int // Int
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
assertEquals("[Int] H7 cell type", CellType.NUMERIC, cell.getCellType()); assertEquals("[Int] H7 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Int] H7 cell value", 15, (int) cell.getNumericCellValue()); assertEquals("[Int] H7 cell value", 15, (int) cell.getNumericCellValue());
// Float // Float
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
assertEquals("[Float] I7 cell type", CellType.NUMERIC, cell.getCellType()); assertEquals("[Float] I7 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Float] I7 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION); assertEquals("[Float] I7 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION);
// Cell Formula // Cell Formula
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
assertEquals("J7", new CellReference(cell).formatAsString()); assertEquals("J7", new CellReference(cell).formatAsString());
assertEquals("[Cell Formula] J7 cell type", CellType.FORMULA, cell.getCellType()); assertEquals("[Cell Formula] J7 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula] J7 cell formula", "5+2", cell.getCellFormula()); assertEquals("[Cell Formula] J7 cell formula", "5+2", cell.getCellFormula());
//System.out.println("Cell formula evaluation currently unsupported"); //System.out.println("Cell formula evaluation currently unsupported");
// Cell Formula with Reference // Cell Formula with Reference
// Formula row references should be adjusted by destRowNum-srcRowNum // Formula row references should be adjusted by destRowNum-srcRowNum
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
@ -1522,21 +1522,21 @@ public final class TestXSSFSheet extends BaseTestXSheet {
CellType.FORMULA, cell.getCellType()); CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference] K7 cell formula", assertEquals("[Cell Formula with Reference] K7 cell formula",
"J7+H$2", cell.getCellFormula()); "J7+H$2", cell.getCellFormula());
// Cell Formula with Reference spanning multiple rows // Cell Formula with Reference spanning multiple rows
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell type", assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell type",
CellType.FORMULA, cell.getCellType()); CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell formula", assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell formula",
"G7&\" \"&G8", cell.getCellFormula()); "G7&\" \"&G8", cell.getCellFormula());
// Cell Formula with Reference spanning multiple rows // Cell Formula with Reference spanning multiple rows
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
assertEquals("[Cell Formula with Area Reference] M7 cell type", assertEquals("[Cell Formula with Area Reference] M7 cell type",
CellType.FORMULA, cell.getCellType()); CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Area Reference] M7 cell formula", assertEquals("[Cell Formula with Area Reference] M7 cell formula",
"SUM(H7:I8)", cell.getCellFormula()); "SUM(H7:I8)", cell.getCellFormula());
// Array Formula // Array Formula
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
//System.out.println("Array formulas currently unsupported"); //System.out.println("Array formulas currently unsupported");
@ -1545,7 +1545,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals("[Array Formula] N7 cell type", CellType.FORMULA, cell.getCellType()); assertEquals("[Array Formula] N7 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Array Formula] N7 cell formula", "{SUM(H7:J7*{1,2,3})}", cell.getCellFormula()); assertEquals("[Array Formula] N7 cell formula", "{SUM(H7:J7*{1,2,3})}", cell.getCellFormula());
*/ */
// Data Format // Data Format
cell = CellUtil.getCell(destRow, col++); cell = CellUtil.getCell(destRow, col++);
assertEquals("[Data Format] O7 cell type;", CellType.NUMERIC, cell.getCellType()); assertEquals("[Data Format] O7 cell type;", CellType.NUMERIC, cell.getCellType());
@ -1553,14 +1553,14 @@ public final class TestXSSFSheet extends BaseTestXSheet {
//FIXME: currently fails //FIXME: currently fails
final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"; final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)";
assertEquals("[Data Format] O7 data format", moneyFormat, cell.getCellStyle().getDataFormatString()); assertEquals("[Data Format] O7 data format", moneyFormat, cell.getCellStyle().getDataFormatString());
// Merged // Merged
cell = CellUtil.getCell(destRow, col); cell = CellUtil.getCell(destRow, col);
assertEquals("[Merged] P7:Q7 cell value", assertEquals("[Merged] P7:Q7 cell value",
"Merged cells", cell.getStringCellValue()); "Merged cells", cell.getStringCellValue());
assertTrue("[Merged] P7:Q7 merged region", assertTrue("[Merged] P7:Q7 merged region",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P7:Q7"))); sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P7:Q7")));
// Merged across multiple rows // Merged across multiple rows
// Microsoft Excel 2013 does not copy a merged region unless all rows of // Microsoft Excel 2013 does not copy a merged region unless all rows of
// the source merged region are selected // the source merged region are selected
@ -1571,23 +1571,23 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// which will not overwrite a cell in destination row if merged region extends beyond the copied row. // which will not overwrite a cell in destination row if merged region extends beyond the copied row.
// The Excel way would require: // The Excel way would require:
//assertEquals("[Merged across multiple rows] R7:S8 merged region", "Should NOT be overwritten", cell.getStringCellValue()); //assertEquals("[Merged across multiple rows] R7:S8 merged region", "Should NOT be overwritten", cell.getStringCellValue());
//assertFalse("[Merged across multiple rows] R7:S8 merged region", //assertFalse("[Merged across multiple rows] R7:S8 merged region",
// sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8"))); // sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8")));
// As currently implemented, cell value is copied but merged region is not copied // As currently implemented, cell value is copied but merged region is not copied
assertEquals("[Merged across multiple rows] R7:S8 cell value", assertEquals("[Merged across multiple rows] R7:S8 cell value",
"Merged cells across multiple rows", cell.getStringCellValue()); "Merged cells across multiple rows", cell.getStringCellValue());
assertFalse("[Merged across multiple rows] R7:S7 merged region (one row)", assertFalse("[Merged across multiple rows] R7:S7 merged region (one row)",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S7"))); //shouldn't do 1-row merge sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S7"))); //shouldn't do 1-row merge
assertFalse("[Merged across multiple rows] R7:S8 merged region", assertFalse("[Merged across multiple rows] R7:S8 merged region",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8"))); //shouldn't do 2-row merge sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8"))); //shouldn't do 2-row merge
// Make sure other rows are blank (off-by-one errors) // Make sure other rows are blank (off-by-one errors)
assertNull(sheet.getRow(5)); assertNull(sheet.getRow(5));
assertNull(sheet.getRow(7)); assertNull(sheet.getRow(7));
wb.close(); wb.close();
} }
protected void testCopyMultipleRows(String copyRowsTestWorkbook) throws IOException { protected void testCopyMultipleRows(String copyRowsTestWorkbook) throws IOException {
final double FLOAT_PRECISION = 1e-9; final double FLOAT_PRECISION = 1e-9;
final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook); final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook);
@ -1595,8 +1595,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy(); final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy();
sheet.copyRows(0, 3, 8, defaultCopyPolicy); sheet.copyRows(0, 3, 8, defaultCopyPolicy);
@SuppressWarnings("unused") sheet.getRow(0);
final Row srcHeaderRow = sheet.getRow(0);
final Row srcRow1 = sheet.getRow(1); final Row srcRow1 = sheet.getRow(1);
final Row srcRow2 = sheet.getRow(2); final Row srcRow2 = sheet.getRow(2);
final Row srcRow3 = sheet.getRow(3); final Row srcRow3 = sheet.getRow(3);
@ -1606,102 +1605,102 @@ public final class TestXSSFSheet extends BaseTestXSheet {
final Row destRow3 = sheet.getRow(11); final Row destRow3 = sheet.getRow(11);
int col = 0; int col = 0;
Cell cell; Cell cell;
// Header row should be copied // Header row should be copied
assertNotNull(destHeaderRow); assertNotNull(destHeaderRow);
// Data rows // Data rows
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("Source row ->", cell.getStringCellValue()); assertEquals("Source row ->", cell.getStringCellValue());
// Style // Style
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Style] B10 cell value", "Red", cell.getStringCellValue()); assertEquals("[Style] B10 cell value", "Red", cell.getStringCellValue());
assertEquals("[Style] B10 cell style", CellUtil.getCell(srcRow1, 1).getCellStyle(), cell.getCellStyle()); assertEquals("[Style] B10 cell style", CellUtil.getCell(srcRow1, 1).getCellStyle(), cell.getCellStyle());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Style] B11 cell value", "Blue", cell.getStringCellValue()); assertEquals("[Style] B11 cell value", "Blue", cell.getStringCellValue());
assertEquals("[Style] B11 cell style", CellUtil.getCell(srcRow2, 1).getCellStyle(), cell.getCellStyle()); assertEquals("[Style] B11 cell style", CellUtil.getCell(srcRow2, 1).getCellStyle(), cell.getCellStyle());
// Blank // Blank
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Blank] C10 cell type", CellType.BLANK, cell.getCellType()); assertEquals("[Blank] C10 cell type", CellType.BLANK, cell.getCellType());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Blank] C11 cell type", CellType.BLANK, cell.getCellType()); assertEquals("[Blank] C11 cell type", CellType.BLANK, cell.getCellType());
// Error // Error
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Error] D10 cell type", CellType.ERROR, cell.getCellType()); assertEquals("[Error] D10 cell type", CellType.ERROR, cell.getCellType());
FormulaError error = FormulaError.forInt(cell.getErrorCellValue()); FormulaError error = FormulaError.forInt(cell.getErrorCellValue());
assertEquals("[Error] D10 cell value", FormulaError.NA, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here assertEquals("[Error] D10 cell value", FormulaError.NA, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Error] D11 cell type", CellType.ERROR, cell.getCellType()); assertEquals("[Error] D11 cell type", CellType.ERROR, cell.getCellType());
error = FormulaError.forInt(cell.getErrorCellValue()); error = FormulaError.forInt(cell.getErrorCellValue());
assertEquals("[Error] D11 cell value", FormulaError.NAME, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here assertEquals("[Error] D11 cell value", FormulaError.NAME, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here
// Date // Date
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Date] E10 cell type", CellType.NUMERIC, cell.getCellType()); assertEquals("[Date] E10 cell type", CellType.NUMERIC, cell.getCellType());
Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime(); Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime();
assertEquals("[Date] E10 cell value", date, cell.getDateCellValue()); assertEquals("[Date] E10 cell value", date, cell.getDateCellValue());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Date] E11 cell type", CellType.NUMERIC, cell.getCellType()); assertEquals("[Date] E11 cell type", CellType.NUMERIC, cell.getCellType());
date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 2).getTime(); date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 2).getTime();
assertEquals("[Date] E11 cell value", date, cell.getDateCellValue()); assertEquals("[Date] E11 cell value", date, cell.getDateCellValue());
// Boolean // Boolean
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Boolean] F10 cell type", CellType.BOOLEAN, cell.getCellType()); assertEquals("[Boolean] F10 cell type", CellType.BOOLEAN, cell.getCellType());
assertEquals("[Boolean] F10 cell value", true, cell.getBooleanCellValue()); assertEquals("[Boolean] F10 cell value", true, cell.getBooleanCellValue());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Boolean] F11 cell type", CellType.BOOLEAN, cell.getCellType()); assertEquals("[Boolean] F11 cell type", CellType.BOOLEAN, cell.getCellType());
assertEquals("[Boolean] F11 cell value", false, cell.getBooleanCellValue()); assertEquals("[Boolean] F11 cell value", false, cell.getBooleanCellValue());
// String // String
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[String] G10 cell type", CellType.STRING, cell.getCellType()); assertEquals("[String] G10 cell type", CellType.STRING, cell.getCellType());
assertEquals("[String] G10 cell value", "Hello", cell.getStringCellValue()); assertEquals("[String] G10 cell value", "Hello", cell.getStringCellValue());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[String] G11 cell type", CellType.STRING, cell.getCellType()); assertEquals("[String] G11 cell type", CellType.STRING, cell.getCellType());
assertEquals("[String] G11 cell value", "World", cell.getStringCellValue()); assertEquals("[String] G11 cell value", "World", cell.getStringCellValue());
// Int // Int
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Int] H10 cell type", CellType.NUMERIC, cell.getCellType()); assertEquals("[Int] H10 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Int] H10 cell value", 15, (int) cell.getNumericCellValue()); assertEquals("[Int] H10 cell value", 15, (int) cell.getNumericCellValue());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Int] H11 cell type", CellType.NUMERIC, cell.getCellType()); assertEquals("[Int] H11 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Int] H11 cell value", 42, (int) cell.getNumericCellValue()); assertEquals("[Int] H11 cell value", 42, (int) cell.getNumericCellValue());
// Float // Float
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Float] I10 cell type", CellType.NUMERIC, cell.getCellType()); assertEquals("[Float] I10 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Float] I10 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION); assertEquals("[Float] I10 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION);
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Float] I11 cell type", CellType.NUMERIC, cell.getCellType()); assertEquals("[Float] I11 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Float] I11 cell value", 5.5, cell.getNumericCellValue(), FLOAT_PRECISION); assertEquals("[Float] I11 cell value", 5.5, cell.getNumericCellValue(), FLOAT_PRECISION);
// Cell Formula // Cell Formula
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Cell Formula] J10 cell type", CellType.FORMULA, cell.getCellType()); assertEquals("[Cell Formula] J10 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula] J10 cell formula", "5+2", cell.getCellFormula()); assertEquals("[Cell Formula] J10 cell formula", "5+2", cell.getCellFormula());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Cell Formula] J11 cell type", CellType.FORMULA, cell.getCellType()); assertEquals("[Cell Formula] J11 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula] J11 cell formula", "6+18", cell.getCellFormula()); assertEquals("[Cell Formula] J11 cell formula", "6+18", cell.getCellFormula());
@ -1714,11 +1713,11 @@ public final class TestXSSFSheet extends BaseTestXSheet {
CellType.FORMULA, cell.getCellType()); CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference] K10 cell formula", assertEquals("[Cell Formula with Reference] K10 cell formula",
"J10+H$2", cell.getCellFormula()); "J10+H$2", cell.getCellFormula());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Cell Formula with Reference] K11 cell type", CellType.FORMULA, cell.getCellType()); assertEquals("[Cell Formula with Reference] K11 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference] K11 cell formula", "J11+H$2", cell.getCellFormula()); assertEquals("[Cell Formula with Reference] K11 cell formula", "J11+H$2", cell.getCellFormula());
// Cell Formula with Reference spanning multiple rows // Cell Formula with Reference spanning multiple rows
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
@ -1726,13 +1725,13 @@ public final class TestXSSFSheet extends BaseTestXSheet {
CellType.FORMULA, cell.getCellType()); CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference spanning multiple rows] L10 cell formula", assertEquals("[Cell Formula with Reference spanning multiple rows] L10 cell formula",
"G10&\" \"&G11", cell.getCellFormula()); "G10&\" \"&G11", cell.getCellFormula());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell type", assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell type",
CellType.FORMULA, cell.getCellType()); CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell formula", assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell formula",
"G11&\" \"&G12", cell.getCellFormula()); "G11&\" \"&G12", cell.getCellFormula());
// Cell Formula with Area Reference // Cell Formula with Area Reference
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
@ -1740,13 +1739,13 @@ public final class TestXSSFSheet extends BaseTestXSheet {
CellType.FORMULA, cell.getCellType()); CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Area Reference] M10 cell formula", assertEquals("[Cell Formula with Area Reference] M10 cell formula",
"SUM(H10:I11)", cell.getCellFormula()); "SUM(H10:I11)", cell.getCellFormula());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Cell Formula with Area Reference] M11 cell type", assertEquals("[Cell Formula with Area Reference] M11 cell type",
CellType.FORMULA, cell.getCellType()); CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Area Reference] M11 cell formula", assertEquals("[Cell Formula with Area Reference] M11 cell formula",
"SUM($H$3:I10)", cell.getCellFormula()); //Also acceptable: SUM($H10:I$3), but this AreaReference isn't in ascending order "SUM($H$3:I10)", cell.getCellFormula()); //Also acceptable: SUM($H10:I$3), but this AreaReference isn't in ascending order
// Array Formula // Array Formula
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
@ -1755,13 +1754,13 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula()
assertEquals("[Array Formula] N10 cell type", CellType.FORMULA, cell.getCellType()); assertEquals("[Array Formula] N10 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Array Formula] N10 cell formula", "{SUM(H10:J10*{1,2,3})}", cell.getCellFormula()); assertEquals("[Array Formula] N10 cell formula", "{SUM(H10:J10*{1,2,3})}", cell.getCellFormula());
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
// FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula()
assertEquals("[Array Formula] N11 cell type", CellType.FORMULA, cell.getCellType()); assertEquals("[Array Formula] N11 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Array Formula] N11 cell formula", "{SUM(H11:J11*{1,2,3})}", cell.getCellFormula()); assertEquals("[Array Formula] N11 cell formula", "{SUM(H11:J11*{1,2,3})}", cell.getCellFormula());
*/ */
// Data Format // Data Format
col++; col++;
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
@ -1769,7 +1768,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals("[Data Format] O10 cell value", 100.20, cell.getNumericCellValue(), FLOAT_PRECISION); assertEquals("[Data Format] O10 cell value", 100.20, cell.getNumericCellValue(), FLOAT_PRECISION);
final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"; final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)";
assertEquals("[Data Format] O10 cell data format", moneyFormat, cell.getCellStyle().getDataFormatString()); assertEquals("[Data Format] O10 cell data format", moneyFormat, cell.getCellStyle().getDataFormatString());
// Merged // Merged
col++; col++;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
@ -1777,42 +1776,42 @@ public final class TestXSSFSheet extends BaseTestXSheet {
"Merged cells", cell.getStringCellValue()); "Merged cells", cell.getStringCellValue());
assertTrue("[Merged] P10:Q10 merged region", assertTrue("[Merged] P10:Q10 merged region",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P10:Q10"))); sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P10:Q10")));
cell = CellUtil.getCell(destRow2, col); cell = CellUtil.getCell(destRow2, col);
assertEquals("[Merged] P11:Q11 cell value", "Merged cells", cell.getStringCellValue()); assertEquals("[Merged] P11:Q11 cell value", "Merged cells", cell.getStringCellValue());
assertTrue("[Merged] P11:Q11 merged region", assertTrue("[Merged] P11:Q11 merged region",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P11:Q11"))); sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P11:Q11")));
// Should Q10/Q11 be checked? // Should Q10/Q11 be checked?
// Merged across multiple rows // Merged across multiple rows
// Microsoft Excel 2013 does not copy a merged region unless all rows of // Microsoft Excel 2013 does not copy a merged region unless all rows of
// the source merged region are selected // the source merged region are selected
// POI's behavior should match this behavior // POI's behavior should match this behavior
col += 2; col += 2;
cell = CellUtil.getCell(destRow1, col); cell = CellUtil.getCell(destRow1, col);
assertEquals("[Merged across multiple rows] R10:S11 cell value", assertEquals("[Merged across multiple rows] R10:S11 cell value",
"Merged cells across multiple rows", cell.getStringCellValue()); "Merged cells across multiple rows", cell.getStringCellValue());
assertTrue("[Merged across multiple rows] R10:S11 merged region", assertTrue("[Merged across multiple rows] R10:S11 merged region",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R10:S11"))); sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R10:S11")));
// Row 3 (zero-based) was empty, so Row 11 (zero-based) should be empty too. // Row 3 (zero-based) was empty, so Row 11 (zero-based) should be empty too.
if (srcRow3 == null) { if (srcRow3 == null) {
assertNull("Row 3 was empty, so Row 11 should be empty", destRow3); assertNull("Row 3 was empty, so Row 11 should be empty", destRow3);
} }
// Make sure other rows are blank (off-by-one errors) // Make sure other rows are blank (off-by-one errors)
assertNull("Off-by-one lower edge case", sheet.getRow(7)); //one row above destHeaderRow assertNull("Off-by-one lower edge case", sheet.getRow(7)); //one row above destHeaderRow
assertNull("Off-by-one upper edge case", sheet.getRow(12)); //one row below destRow3 assertNull("Off-by-one upper edge case", sheet.getRow(12)); //one row below destRow3
wb.close(); wb.close();
} }
@Test @Test
public void testCopyOneRow() throws IOException { public void testCopyOneRow() throws IOException {
testCopyOneRow("XSSFSheet.copyRows.xlsx"); testCopyOneRow("XSSFSheet.copyRows.xlsx");
} }
@Test @Test
public void testCopyMultipleRows() throws IOException { public void testCopyMultipleRows() throws IOException {
testCopyMultipleRows("XSSFSheet.copyRows.xlsx"); testCopyMultipleRows("XSSFSheet.copyRows.xlsx");
@ -1828,12 +1827,12 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals(1, ignoredError.getSqref().size()); assertEquals(1, ignoredError.getSqref().size());
assertEquals("B2:D4", ignoredError.getSqref().get(0)); assertEquals("B2:D4", ignoredError.getSqref().get(0));
assertTrue(ignoredError.getNumberStoredAsText()); assertTrue(ignoredError.getNumberStoredAsText());
Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors();
assertEquals(1, ignoredErrors.size()); assertEquals(1, ignoredErrors.size());
assertEquals(1, ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).size()); assertEquals(1, ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).size());
assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).iterator().next().formatAsString()); assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).iterator().next().formatAsString());
workbook.close(); workbook.close();
} }
@ -1849,7 +1848,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertFalse(ignoredError.getNumberStoredAsText()); assertFalse(ignoredError.getNumberStoredAsText());
assertTrue(ignoredError.getFormula()); assertTrue(ignoredError.getFormula());
assertTrue(ignoredError.getEvalError()); assertTrue(ignoredError.getEvalError());
Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors();
assertEquals(2, ignoredErrors.size()); assertEquals(2, ignoredErrors.size());
assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size()); assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size());
@ -1867,19 +1866,19 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// Two calls means two elements, no clever collapsing just yet. // Two calls means two elements, no clever collapsing just yet.
sheet.addIgnoredErrors(region, IgnoredErrorType.EVALUATION_ERROR); sheet.addIgnoredErrors(region, IgnoredErrorType.EVALUATION_ERROR);
sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA); sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA);
CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0);
assertEquals(1, ignoredError.getSqref().size()); assertEquals(1, ignoredError.getSqref().size());
assertEquals("B2:D4", ignoredError.getSqref().get(0)); assertEquals("B2:D4", ignoredError.getSqref().get(0));
assertFalse(ignoredError.getFormula()); assertFalse(ignoredError.getFormula());
assertTrue(ignoredError.getEvalError()); assertTrue(ignoredError.getEvalError());
ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(1); ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(1);
assertEquals(1, ignoredError.getSqref().size()); assertEquals(1, ignoredError.getSqref().size());
assertEquals("B2:D4", ignoredError.getSqref().get(0)); assertEquals("B2:D4", ignoredError.getSqref().get(0));
assertTrue(ignoredError.getFormula()); assertTrue(ignoredError.getFormula());
assertFalse(ignoredError.getEvalError()); assertFalse(ignoredError.getEvalError());
Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors();
assertEquals(2, ignoredErrors.size()); assertEquals(2, ignoredErrors.size());
assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size()); assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size());
@ -1888,7 +1887,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString()); assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString());
workbook.close(); workbook.close();
} }
@Test @Test
public void setTabColor() throws IOException { public void setTabColor() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) { try (XSSFWorkbook wb = new XSSFWorkbook()) {
@ -1900,7 +1899,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
sh.getCTWorksheet().getSheetPr().getTabColor().getIndexed()); sh.getCTWorksheet().getSheetPr().getTabColor().getIndexed());
} }
} }
@Test @Test
public void getTabColor() throws IOException { public void getTabColor() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) { try (XSSFWorkbook wb = new XSSFWorkbook()) {
@ -1912,7 +1911,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals(expected, sh.getTabColor()); assertEquals(expected, sh.getTabColor());
} }
} }
// Test using an existing workbook saved by Excel // Test using an existing workbook saved by Excel
@Test @Test
public void tabColor() throws IOException { public void tabColor() throws IOException {
@ -1930,7 +1929,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals(expected, wb.getSheet("customOrange").getTabColor()); assertEquals(expected, wb.getSheet("customOrange").getTabColor());
} }
} }
/** /**
* See bug #52425 * See bug #52425
*/ */
@ -1947,7 +1946,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// Adding Comment to cloned Sheet 3 // Adding Comment to cloned Sheet 3
addComments(helper, sheet3); addComments(helper, sheet3);
} }
private void addComments(CreationHelper helper, Sheet sheet) { private void addComments(CreationHelper helper, Sheet sheet) {
Drawing<?> drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
@ -1974,7 +1973,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
} }
} }
// bug 59687: XSSFSheet.RemoveRow doesn't handle row gaps properly when removing row comments // bug 59687: XSSFSheet.RemoveRow doesn't handle row gaps properly when removing row comments
@Test @Test
public void testRemoveRowWithCommentAndGapAbove() throws IOException { public void testRemoveRowWithCommentAndGapAbove() throws IOException {
@ -1984,22 +1983,22 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// comment exists // comment exists
CellAddress commentCellAddress = new CellAddress("A4"); CellAddress commentCellAddress = new CellAddress("A4");
assertNotNull(sheet.getCellComment(commentCellAddress)); assertNotNull(sheet.getCellComment(commentCellAddress));
assertEquals("Wrong starting # of comments", 1, sheet.getCellComments().size()); assertEquals("Wrong starting # of comments", 1, sheet.getCellComments().size());
sheet.removeRow(sheet.getRow(commentCellAddress.getRow())); sheet.removeRow(sheet.getRow(commentCellAddress.getRow()));
assertEquals("There should not be any comments left!", 0, sheet.getCellComments().size()); assertEquals("There should not be any comments left!", 0, sheet.getCellComments().size());
} }
@Test @Test
public void testGetHeaderFooterProperties() throws IOException { public void testGetHeaderFooterProperties() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = wb.createSheet(); XSSFSheet sh = wb.createSheet();
XSSFHeaderFooterProperties hfProp = sh.getHeaderFooterProperties(); XSSFHeaderFooterProperties hfProp = sh.getHeaderFooterProperties();
assertNotNull(hfProp); assertNotNull(hfProp);
wb.close(); wb.close();
} }
} }

View File

@ -1044,8 +1044,10 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
//assertCloseDoesNotModifyFile(filename, wb); //assertCloseDoesNotModifyFile(filename, wb);
// InputStream // InputStream
wb = new XSSFWorkbook(new FileInputStream(file)); try (FileInputStream is = new FileInputStream(file)) {
assertCloseDoesNotModifyFile(filename, wb); wb = new XSSFWorkbook(is);
assertCloseDoesNotModifyFile(filename, wb);
}
// OPCPackage // OPCPackage
//wb = new XSSFWorkbook(OPCPackage.open(file)); //wb = new XSSFWorkbook(OPCPackage.open(file));

View File

@ -65,7 +65,7 @@ public class TestXSSFChartTitle {
row = sheet.createRow((short) rowIndex); row = sheet.createRow((short) rowIndex);
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
cell = row.createCell((short) colIndex); cell = row.createCell((short) colIndex);
cell.setCellValue(colIndex * (rowIndex + 1)); cell.setCellValue(colIndex * (rowIndex + 1L));
} }
} }

View File

@ -17,18 +17,23 @@
package org.apache.poi.xssf.util; package org.apache.poi.xssf.util;
import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellReference;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
import junit.framework.TestCase;
/** /**
* Mixed utilities for testing memory usage in XSSF * Mixed utilities for testing memory usage in XSSF
@ -37,7 +42,7 @@ import java.util.ArrayList;
*/ */
public class MemoryUsage extends TestCase { public class MemoryUsage extends TestCase {
private static final int NUM_COLUMNS = 255; private static final int NUM_COLUMNS = 255;
private static void printMemoryUsage(String msg) { private static void printMemoryUsage(String msg) {
System.out.println(" Memory (" + msg + "): " + Runtime.getRuntime().totalMemory()/(1024*1024) + "MB"); System.out.println(" Memory (" + msg + "): " + Runtime.getRuntime().totalMemory()/(1024*1024) + "MB");
} }
@ -62,8 +67,11 @@ public class MemoryUsage extends TestCase {
Row row = sh.createRow(i); Row row = sh.createRow(i);
for(int j=0; j < numCols; j++){ for(int j=0; j < numCols; j++){
Cell cell = row.createCell(j); Cell cell = row.createCell(j);
if(j % 2 == 0) cell.setCellValue(j); if(j % 2 == 0) {
else cell.setCellValue(new CellReference(j, i).formatAsString()); cell.setCellValue(j);
} else {
cell.setCellValue(new CellReference(j, i).formatAsString());
}
cnt++; cnt++;
} }
} }
@ -78,7 +86,7 @@ public class MemoryUsage extends TestCase {
/** /**
* Generate a spreadsheet who's all cell values are numbers. * Generate a spreadsheet who's all cell values are numbers.
* The data is generated until OutOfMemoryError. * The data is generated until OutOfMemoryError.
* <p> * <p>
* as compared to {@link #mixedSpreadsheet(org.apache.poi.ss.usermodel.Workbook, int)}, * as compared to {@link #mixedSpreadsheet(org.apache.poi.ss.usermodel.Workbook, int)},
* this method does not set string values and, hence, does not involve the Shared Strings Table. * this method does not set string values and, hence, does not involve the Shared Strings Table.
@ -161,7 +169,7 @@ public class MemoryUsage extends TestCase {
rows.add(r); rows.add(r);
} }
} catch (OutOfMemoryError er) { } catch (OutOfMemoryError er) {
System.out.println("Failed at row=" + i); System.out.println("Failed at row=" + i + " from " + rows.size() + " kept.");
} catch (final Exception e) { } catch (final Exception e) {
System.out.println("Unable to reach an OutOfMemoryError"); System.out.println("Unable to reach an OutOfMemoryError");
System.out.println(e.getClass().getName() + ": " + e.getMessage()); System.out.println(e.getClass().getName() + ": " + e.getMessage());
@ -190,7 +198,7 @@ public class MemoryUsage extends TestCase {
rows.add(r); rows.add(r);
} }
} catch (OutOfMemoryError er) { } catch (OutOfMemoryError er) {
System.out.println("Failed at row=" + i); System.out.println("Failed at row=" + i + " from " + rows.size() + " kept.");
} catch (final Exception e) { } catch (final Exception e) {
System.out.println("Unable to reach an OutOfMemoryError"); System.out.println("Unable to reach an OutOfMemoryError");
System.out.println(e.getClass().getName() + ": " + e.getMessage()); System.out.println(e.getClass().getName() + ": " + e.getMessage());