package org.apache.poi.ooxml.util;
-import junit.framework.TestCase;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.StringUtil;
-import org.apache.poi.util.SuppressForbidden;
-import org.apache.xmlbeans.StringEnumAbstractBase;
-import org.junit.Test;
-import org.junit.internal.TextListener;
-import org.junit.runner.Description;
-import org.junit.runner.JUnitCore;
-import org.junit.runner.Result;
-import org.reflections.Reflections;
-
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
-import java.util.*;
+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.StringUtil;
+import org.apache.poi.util.SuppressForbidden;
+import org.apache.xmlbeans.StringEnumAbstractBase;
+import org.junit.Test;
+import org.junit.internal.TextListener;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.reflections.Reflections;
+
+import junit.framework.TestCase;
+
/**
* Build a 'lite' version of the ooxml-schemas.jar
*
}
public static void main(String[] args) throws IOException {
- System.out.println("Free memory (bytes): " +
+ System.out.println("Free memory (bytes): " +
Runtime.getRuntime().freeMemory());
long maxMemory = Runtime.getRuntime().maxMemory();
- System.out.println("Maximum memory (bytes): " +
+ System.out.println("Maximum memory (bytes): " +
(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
- System.out.println("Total memory (bytes): " +
+ System.out.println("Total memory (bytes): " +
Runtime.getRuntime().totalMemory());
String dest = null, test = null, ooxml = null;
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "-dest":
- dest = args[++i];
+ dest = args[++i]; // lgtm[java/index-out-of-bounds]
break;
case "-test":
- test = args[++i];
+ test = args[++i]; // lgtm[java/index-out-of-bounds]
break;
case "-ooxml":
- ooxml = args[++i];
+ ooxml = args[++i]; // lgtm[java/index-out-of-bounds]
break;
}
}
return true;
}
}
-
+
// also check super classes
if(testclass.getSuperclass() != null) {
for (Method m : testclass.getSuperclass().getDeclaredMethods()) {
}
}
}
-
+
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
String path = arg.getAbsolutePath();
String prefix = root.getAbsolutePath();
String cls = path.substring(prefix.length() + 1).replace(File.separator, ".");
- if(!cls.matches(ptrn)) return;
- if (cls.matches(exclude)) return;
+ if(!cls.matches(ptrn)) {
+ return;
+ }
+ if (cls.matches(exclude)) {
+ return;
+ }
//ignore inner classes defined in tests
if (cls.indexOf('$') != -1) {
System.out.println("Inner class " + cls + " not included");
*/
@SuppressWarnings("unchecked")
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
// without failing, see https://issues.apache.org/bugzilla/show_bug.cgi?id=56550
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)")
public Field run() {
try {
for (Class<?> cls : classes) {
// e.g. proxy-classes, ...
ProtectionDomain pd = cls.getProtectionDomain();
- if (pd == null) continue;
+ if (pd == null) {
+ continue;
+ }
CodeSource cs = pd.getCodeSource();
- if (cs == null) continue;
+ if (cs == null) {
+ continue;
+ }
URL loc = cs.getLocation();
- if (loc == null) continue;
+ if (loc == null) {
+ continue;
+ }
String jar = loc.toString();
if (jar.contains(ptrn)) {
import java.util.Set;
import java.util.TreeMap;
-import junit.framework.AssertionFailedError;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.poi.util.IOUtils;
import org.xmlunit.diff.DifferenceEvaluator;
import org.xmlunit.diff.ElementSelectors;
+import junit.framework.AssertionFailedError;
+
/**
* Compare the contents of 2 zip files.
*/
public final class ZipFileAssert {
- private ZipFileAssert() {
- }
-
- private static void equals(
- TreeMap<String, ByteArrayOutputStream> file1,
- TreeMap<String, ByteArrayOutputStream> file2) {
- Set<String> listFile1 = file1.keySet();
- 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);
- // no need to check for contain1. The key come from it
-
- if (fileName.matches(".*\\.(xml|rels)$")) {
- // we have a xml file
- final Diff diff = DiffBuilder.
- compare(Input.fromByteArray(contain1.toByteArray())).
- withTest(Input.fromByteArray(contain2.toByteArray())).
- ignoreWhitespace().
- checkForSimilar().
- withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()).
- withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)).
- build();
- assertFalse(fileName+": "+diff.toString(), diff.hasDifferences());
+ private ZipFileAssert() {
+ }
+
+ private static void equals(
+ TreeMap<String, ByteArrayOutputStream> file1,
+ TreeMap<String, ByteArrayOutputStream> file2) {
+ Set<String> listFile1 = file1.keySet();
+ 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);
+ // no need to check for contain1. The key come from it
+
+ if (fileName.matches(".*\\.(xml|rels)$")) {
+ // we have a xml file
+ final Diff diff = DiffBuilder.
+ compare(Input.fromByteArray(contain1.toByteArray())).
+ withTest(Input.fromByteArray(contain2.toByteArray())).
+ ignoreWhitespace().
+ checkForSimilar().
+ withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()).
+ withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)).
+ build();
+ assertFalse(fileName+": "+diff.toString(), diff.hasDifferences());
} 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());
- assertArrayEquals("contents differ", contain1.toByteArray(), contain2.toByteArray());
- }
- }
- }
-
- private static TreeMap<String, ByteArrayOutputStream> decompress(
- File filename) throws IOException {
- // store the zip content in memory
- // let s assume it is not Go ;-)
- TreeMap<String, ByteArrayOutputStream> zipContent = new TreeMap<>();
-
- /* Open file to decompress */
- FileInputStream file_decompress = new FileInputStream(filename);
-
- /* Create a buffer for the decompressed files */
- BufferedInputStream buffi = new BufferedInputStream(file_decompress);
-
- /* Open the file with the buffer */
- ZipArchiveInputStream zis = new ZipArchiveInputStream(buffi);
-
- /* Processing entries of the zip file */
- ArchiveEntry entree;
- while ((entree = zis.getNextEntry()) != null) {
-
- /* Create a array for the current entry */
- ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
- IOUtils.copy(zis, byteArray);
- zipContent.put(entree.getName(), byteArray);
- }
-
- zis.close();
-
- return zipContent;
- }
-
- /**
- * Asserts that two files are equal. Throws an <tt>AssertionFailedError</tt>
- * if they are not.
- * <p>
- *
- */
- public static void assertEquals(File expected, File actual) {
- assertNotNull(expected);
- assertNotNull(actual);
-
- assertTrue("File does not exist [" + expected.getAbsolutePath()
- + "]", expected.exists());
- assertTrue("File does not exist [" + actual.getAbsolutePath()
- + "]", actual.exists());
-
- assertTrue("Expected file not readable", expected.canRead());
- assertTrue("Actual file not readable", actual.canRead());
-
- try {
- TreeMap<String, ByteArrayOutputStream> file1 = decompress(expected);
- TreeMap<String, ByteArrayOutputStream> file2 = decompress(actual);
- equals(file1, file2);
- } catch (IOException e) {
- throw new AssertionFailedError(e.toString());
- }
- }
-
- private static class IgnoreXMLDeclEvaluator implements DifferenceEvaluator {
- public ComparisonResult evaluate(final Comparison comparison, final ComparisonResult outcome) {
- if (outcome != ComparisonResult.EQUAL) {
- // only evaluate differences
- switch (comparison.getType()) {
- case CHILD_NODELIST_SEQUENCE:
- case XML_STANDALONE:
- case NAMESPACE_PREFIX:
- return ComparisonResult.SIMILAR;
- case TEXT_VALUE:
- switch (comparison.getControlDetails().getTarget().getParentNode().getNodeName()) {
- case "dcterms:created":
- case "dc:creator":
- return ComparisonResult.SIMILAR;
- }
- break;
- default:
- break;
- }
- }
-
- return outcome;
- }
- }
+ assertArrayEquals("contents differ", contain1.toByteArray(), contain2.toByteArray());
+ }
+ }
+ }
+
+ private static TreeMap<String, ByteArrayOutputStream> decompress(
+ File filename) throws IOException {
+ // store the zip content in memory
+ // let s assume it is not Go ;-)
+ TreeMap<String, ByteArrayOutputStream> zipContent = new TreeMap<>();
+
+ try (
+ /* Open file to decompress */
+ FileInputStream file_decompress = new FileInputStream(filename);
+
+ /* Create a buffer for the decompressed files */
+ BufferedInputStream buffi = new BufferedInputStream(file_decompress);
+
+ /* Open the file with the buffer */
+ ZipArchiveInputStream zis = new ZipArchiveInputStream(buffi);
+ ) {
+
+ /* Processing entries of the zip file */
+ ArchiveEntry entree;
+ while ((entree = zis.getNextEntry()) != null) {
+
+ /* Create a array for the current entry */
+ ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
+ IOUtils.copy(zis, byteArray);
+ zipContent.put(entree.getName(), byteArray);
+ }
+
+ }
+
+ return zipContent;
+ }
+
+ /**
+ * Asserts that two files are equal. Throws an <tt>AssertionFailedError</tt>
+ * if they are not.
+ * <p>
+ *
+ */
+ public static void assertEquals(File expected, File actual) {
+ assertNotNull(expected);
+ assertNotNull(actual);
+
+ assertTrue("File does not exist [" + expected.getAbsolutePath()
+ + "]", expected.exists());
+ assertTrue("File does not exist [" + actual.getAbsolutePath()
+ + "]", actual.exists());
+
+ assertTrue("Expected file not readable", expected.canRead());
+ assertTrue("Actual file not readable", actual.canRead());
+
+ try {
+ TreeMap<String, ByteArrayOutputStream> file1 = decompress(expected);
+ TreeMap<String, ByteArrayOutputStream> file2 = decompress(actual);
+ equals(file1, file2);
+ } catch (IOException e) {
+ throw new AssertionFailedError(e.toString());
+ }
+ }
+
+ private static class IgnoreXMLDeclEvaluator implements DifferenceEvaluator {
+ @Override
+ public ComparisonResult evaluate(final Comparison comparison, final ComparisonResult outcome) {
+ if (outcome != ComparisonResult.EQUAL) {
+ // only evaluate differences
+ switch (comparison.getType()) {
+ case CHILD_NODELIST_SEQUENCE:
+ case XML_STANDALONE:
+ case NAMESPACE_PREFIX:
+ return ComparisonResult.SIMILAR;
+ case TEXT_VALUE:
+ switch (comparison.getControlDetails().getTarget().getParentNode().getNodeName()) {
+ case "dcterms:created":
+ case "dc:creator":
+ return ComparisonResult.SIMILAR;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ return outcome;
+ }
+ }
}
DrawTextParagraphProxy(XSLFTextParagraph p) {
super(p);
}
-
+
@Override
public void breakText(Graphics2D graphics) {
super.breakText(graphics);
}
-
+
@Override
public double getWrappingWidth(boolean firstLine, Graphics2D graphics) {
return super.getWrappingWidth(firstLine, graphics);
}
-
+
public List<DrawTextFragment> getLines() {
return lines;
}
}
-
+
@Test
public void testWrappingWidth() throws IOException {
XMLSlideShow ppt = new XMLSlideShow();
Rectangle2D anchor = new Rectangle2D.Double(50, 50, 300, 200);
sh.setAnchor(anchor);
-
+
DrawTextParagraphProxy dtp = new DrawTextParagraphProxy(p);
- Double leftInset = sh.getLeftInset();
- Double rightInset = sh.getRightInset();
+ double leftInset = sh.getLeftInset();
+ double rightInset = sh.getRightInset();
assertEquals(7.2, leftInset, 0);
assertEquals(7.2, rightInset, 0);
indent = p.getIndent();
assertEquals(-72.0, indent, 0);
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
// other lines are indented by leftMargin (the value of indent is not used)
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);
-
+
ppt.close();
}
assertEquals(-20.0, p.getBulletFontSize(), 0);
assertEquals(72.0, p.getDefaultTabSize(), 0);
-
+
assertNull(p.getIndent());
p.setIndent(72.0);
assertEquals(72.0, p.getIndent(), 0);
p.setIndent(-1d); // the value of -1.0 resets to the defaults (not any more ...)
assertEquals(-1d, p.getIndent(), 0);
- p.setIndent(null);
+ p.setIndent(null);
assertNull(p.getIndent());
assertEquals(0.0, p.getLeftMargin(), 0);
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
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
*/
public class XSSFTestDataSamples {
throw new RuntimeException(e);
}
}
-
+
/**
* 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).
writeOut(wb, file);
return file;
}
-
+
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
// 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.
}
return file;
}
-
+
/**
* Write out workbook <code>wb</code> to a memory buffer
*
wb.write(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
* both workbooks open.
- *
+ *
* Make sure there are no references to any objects in the workbook
* so that garbage collection may free the workbook.
- *
+ *
* 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.
- *
+ *
* Alternatively, use {@link #writeOutAndClose(Workbook)} to use a ByteArrayOutputStream/ByteArrayInputStream
* 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.
throw new RuntimeException(e);
}
}
-
-
+
+
/**
* Write out workbook <code>wb</code> to a memory buffer,
* then close the workbook
throw new RuntimeException(e);
}
}
-
+
/**
* Read back a workbook that was written out to a file with
* {@link #writeOut(Workbook, String))} or {@link #writeOutAndClose(Workbook, String)}.
*/
public static XSSFWorkbook readBackAndDelete(File file) throws IOException {
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();
return wb;
}
-
+
/**
* Read back a workbook that was written out to a file with
* {@link #writeOut(Workbook, String)} or {@link #writeOutAndClose(Workbook, String)}.
in.close();
}
}
-
+
/**
* Read back a workbook that was written out to a memory buffer with
* {@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
* @throws IOException
*/
is.close();
}
}
-
+
/**
* 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,
* consider using:
- *
+ *
* Workbook wb = new XSSFWorkbook();
* String testName = "example";
- *
+ *
* <code>
* File file = writeOutAndClose(wb, testName);
* // clear all references that would prevent the workbook from getting garbage collected
R r = (R) result;
return r;
}
-
+
/**
* Write out, close, and read back the workbook using a memory buffer to avoid disk I/O.
*
@SuppressWarnings("unchecked")
R r = (R) result;
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.
* If TEST_OUTPUT_DIR is set, the file will NOT be deleted at the end of this function.
* @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.
* @return new instance read from the stream written by the wb parameter.
*/
-
+
public static <R extends Workbook> R writeOutAndReadBack(R wb, String testName) {
if (System.getProperty(TEST_OUTPUT_DIR) == null) {
return writeOutAndReadBack(wb);
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
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.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
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.SAXHelper;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.functions.Function;
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.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress;
* problems when deleting columns, conditionally to stop recursion
*/
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";
/**
* problems when deleting rows, conditionally to stop recursion
*/
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";
/**
@Test
public void test57236() throws IOException {
// 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()));
double d = 3.0E-104;
wb.close();
}
-
+
/**
* Auto column sizing failed when there were loads of fonts with
* errors like ArrayIndexOutOfBoundsException: -32765
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
-
+
// Create lots of fonts
XSSFDataFormat formats = wb.createDataFormat();
XSSFFont[] fonts = new XSSFFont[50000];
font.setFontHeight(i);
fonts[i] = font;
}
-
+
// Create a moderate number of columns, which use
// fonts from the start and end of the font list
final int numCols = 125;
for (int i=0; i<numCols; i++) {
XSSFCellStyle cs = wb.createCellStyle();
cs.setDataFormat(formats.getFormat("'Test "+i+"' #,###"));
-
+
XSSFFont font = fonts[i];
if (i%2==1) { font = fonts[fonts.length-i]; }
cs.setFont(font);
-
+
XSSFCell c = row.createCell(i);
c.setCellValue(i);
c.setCellStyle(cs);
}
-
+
// Do the auto-size
for (int i=0; i<numCols; i++) {
sheet.autoSizeColumn(i);
* Test asserts the POI produces <cols> 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".
* 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>
* 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
* </em>
- *
+ *
*/
public class TestXSSFColGrouping {
-
+
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
*/
@Test
sheet.setColumnWidth(4, 5000);
sheet.setColumnWidth(5, 5000);
-
+
sheet.groupColumn((short) 4, (short) 7);
sheet.groupColumn((short) 9, (short) 12);
-
+
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGrouping");
sheet = wb2.getSheet("test");
-
+
CTCols cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "test52186/cols:" + cols);
for (CTCol col : cols.getColArray()) {
assertTrue("Col width attribute is unset: " + col, col.isSetWidth());
}
-
+
wb2.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
*/
@Test
sheet.setColumnWidth(4, 5000);
sheet.setColumnWidth(5, 5000);
-
+
sheet.groupColumn((short) 4, (short) 5);
-
+
sheet.setColumnGroupCollapsed(4, true);
-
+
CTCols cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "test52186_2/cols:" + cols);
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGroupingAndCollapsing");
sheet = wb2.getSheet("test");
-
+
for (int i = 4; i <= 5; i++) {
assertEquals("Unexpected width of column "+ i, 5000, sheet.getColumnWidth(i));
}
wb2.close();
wb1.close();
}
-
+
/**
* Test the cols element is correct in case of NumericRanges.OVERLAPS_2_WRAPS
*/
col.setCustomWidth(true);
sheet.groupColumn((short) 2, (short) 3);
-
+
sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_WRAPS/cols:" + cols);
-
+
assertEquals(0, cols.getColArray(0).getOutlineLevel());
assertEquals(2, cols.getColArray(0).getMin()); // 1 based
assertEquals(2, cols.getColArray(0).getMax()); // 1 based
assertEquals(1, cols.getColArray(1).getOutlineLevel());
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(0, cols.getColArray(2).getOutlineLevel());
assertEquals(5, cols.getColArray(2).getMin()); // 1 based
assertEquals(5, cols.getColArray(2).getMax()); // 1 based
assertEquals(true, cols.getColArray(2).getCustomWidth());
-
+
assertEquals(3, cols.sizeOfColArray());
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_WRAPS");
sheet = wb2.getSheet("test");
-
+
for (int i = 1; i <= 4; i++) {
assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i));
}
-
+
wb2.close();
wb1.close();
}
col.setCustomWidth(true);
sheet.groupColumn((short) 1, (short) 5);
-
+
cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_WRAPS/cols:" + cols);
-
+
assertEquals(1, cols.getColArray(0).getOutlineLevel());
assertEquals(2, cols.getColArray(0).getMin()); // 1 based
assertEquals(2, cols.getColArray(0).getMax()); // 1 based
assertEquals(1, cols.getColArray(1).getOutlineLevel());
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(1, cols.getColArray(2).getOutlineLevel());
assertEquals(6, cols.getColArray(2).getMin()); // 1 based
assertEquals(6, cols.getColArray(2).getMax()); // 1 based
assertEquals(false, cols.getColArray(2).getCustomWidth());
-
+
assertEquals(3, cols.sizeOfColArray());
-
+
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_WRAPS");
sheet = wb2.getSheet("test");
-
+
for (int i = 2; i <= 4; i++) {
assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i));
}
-
+
wb2.close();
wb1.close();
}
col.setCustomWidth(true);
sheet.groupColumn((short) 3, (short) 5);
-
+
cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_MINOR/cols:" + cols);
assertEquals(1, cols.getColArray(1).getOutlineLevel());
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(1, cols.getColArray(2).getOutlineLevel());
assertEquals(6, cols.getColArray(2).getMin()); // 1 based
assertEquals(6, cols.getColArray(2).getMax()); // 1 based
assertEquals(false, cols.getColArray(2).getCustomWidth());
-
+
assertEquals(3, cols.sizeOfColArray());
-
+
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_MINOR");
sheet = wb2.getSheet("test");
-
+
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();
wb1.close();
}
col.setCustomWidth(true);
sheet.groupColumn((short) 1, (short) 3);
-
+
cols = sheet.getCTWorksheet().getColsArray(0);
logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_MINOR/cols:" + cols);
assertEquals(1, cols.getColArray(1).getOutlineLevel());
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(0, cols.getColArray(2).getOutlineLevel());
assertEquals(5, cols.getColArray(2).getMin()); // 1 based
assertEquals(5, cols.getColArray(2).getMax()); // 1 based
assertEquals(true, cols.getColArray(2).getCustomWidth());
-
+
assertEquals(3, cols.sizeOfColArray());
-
+
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_MINOR");
sheet = wb2.getSheet("test");
-
+
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();
wb1.close();
}
import java.util.List;
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.usermodel.BaseTestDataValidation;
import org.apache.poi.ss.usermodel.Cell;
/**
* For each validation type, there are two cells with the same validation. This tests
* application of a single validation definition to multiple cells.
- *
+ *
* 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 show the drop down arrow.
* = 2
- *
+ *
* For number validations ( integer/decimal and text length ) with 8 different types of operators.
- * = 50
- *
+ * = 50
+ *
* = 52 ( Total )
*/
assertEquals(52,dataValidations.size());
cell_10.setCellValue(XSSFDataValidation.operatorTypeMappings.get(operatorType).toString());
Cell cell_11 = row1.createCell(1);
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);
assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size());
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);
setOtherValidationParameters( validation);
sheet.addValidationData(validation);
} else if(i==0 && j==1 ){
cellRangeAddressList = new CellRangeAddressList();
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);
setOtherValidationParameters( validation);
sheet.addValidationData(validation);
XSSFSheet sheet = wb.createSheet();
List<XSSFDataValidation> lst = sheet.getDataValidations(); //<-- works
assertEquals(0, lst.size());
-
+
//create the cell that will have the validation applied
sheet.createRow(0).createCell(0);
-
+
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DataValidation validation = dataValidationHelper.createValidation(constraint, addressList);
sheet.addValidationData(validation);
-
+
// this line caused XmlValueOutOfRangeException , see Bugzilla 3965
lst = sheet.getDataValidations();
assertEquals(1, lst.size());
public void testDefaultErrorStyle() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
-
+
final XSSFDataValidation validation = createValidation(sheet);
sheet.addValidationData(validation);
-
+
final List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
assertEquals(DataValidation.ErrorStyle.STOP, dataValidations.get(0).getErrorStyle());
}
public void testSetErrorStyles() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
-
+
XSSFDataValidation validation = createValidation(sheet);
sheet.addValidationData(validation);
-
+
// extract generated validation from sheet
List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
validation = dataValidations.get(0);
-
+
// test INFO
validation.setErrorStyle(DataValidation.ErrorStyle.INFO);
assertEquals(DataValidation.ErrorStyle.INFO, dataValidations.get(0).getErrorStyle());
-
+
// test WARNING
validation.setErrorStyle(DataValidation.ErrorStyle.WARNING);
assertEquals(DataValidation.ErrorStyle.WARNING, dataValidations.get(0).getErrorStyle());
-
+
// test STOP
validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
assertEquals(DataValidation.ErrorStyle.STOP, dataValidations.get(0).getErrorStyle());
public void testDefaultAllowBlank() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
-
+
final XSSFDataValidation validation = createValidation(sheet);
sheet.addValidationData(validation);
-
+
final List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
assertEquals(true, dataValidations.get(0).getCtDdataValidation().getAllowBlank());
}
public void testSetAllowBlankToFalse() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
-
+
final XSSFDataValidation validation = createValidation(sheet);
validation.getCtDdataValidation().setAllowBlank(false);
-
+
sheet.addValidationData(validation);
-
+
final List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
assertEquals(false, dataValidations.get(0).getCtDdataValidation().getAllowBlank());
}
public void testSetAllowBlankToTrue() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
-
+
final XSSFDataValidation validation = createValidation(sheet);
validation.getCtDdataValidation().setAllowBlank(true);
-
+
sheet.addValidationData(validation);
-
+
final List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
assertEquals(true, dataValidations.get(0).getCtDdataValidation().getAllowBlank());
}
DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("true");
return (XSSFDataValidation) dataValidationHelper.createValidation(constraint, new CellRangeAddressList(0, 0, 0, 0));
}
-
+
@Test
public void testTableBasedValidationList() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("dataValidationTableRange.xlsx")) {
import java.util.Map;
import java.util.Set;
-import org.apache.poi.ooxml.POIXMLException;
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.HashAlgorithm;
import org.apache.poi.ss.usermodel.AutoFilter;
assertEquals("", ftr.getLeft());
assertEquals("", ftr.getCenter());
assertEquals("", ftr.getRight());
-
+
wb2.close();
}
// Defaults are odd
assertEquals("odd footer left", sheet.getFooter().getLeft());
assertEquals("odd header center", sheet.getHeader().getCenter());
-
+
workbook.close();
}
sheet.createSplitPane(4, 8, 12, 12, 1);
assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0);
assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane());
-
+
workbook.close();
}
colArray = cols.getColArray();
assertEquals(4, colArray.length);
assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol());
-
+
workbook.close();
}
assertEquals(3, sheet.getPhysicalNumberOfRows());
assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow());
-
+
workbook.close();
}
checkColumnGroup(cols.getColArray(3), 10, 11); // false, true
checkColumnGroup(cols.getColArray(4), 12, 12, false, false);
checkColumnGroup(cols.getColArray(5), 13, 13, false, false);
-
+
wb2.close();
}
-
+
/**
* Verify that column groups were created correctly after Sheet.groupColumn
*
assertEquals("isSetHidden", isSetHidden, col.isSetHidden());
assertEquals("isSetCollapsed", isSetCollapsed, col.isSetCollapsed()); //not necessarily set
}
-
+
/**
* Verify that column groups were created correctly after Sheet.groupColumn
*
assertFalse(sheet1.getRow(16).getCTRow().isSetHidden());
assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed());
assertFalse(sheet1.getRow(18).getCTRow().isSetHidden());
-
+
wb2.close();
}
assertEquals(4, col.getMax());
assertEquals(33.0, col.getWidth(), 0.0);
assertTrue(col.getCustomWidth());
-
+
workbook.close();
}
//now the span is splitted into 5 individual columns
assertEquals(5, cols.sizeOfColArray());
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);
}
cols = sheet.getCTWorksheet().getColsArray(0);
assertEquals(5, cols.sizeOfColArray());
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);
}
-
+
wb2.close();
}
assertFalse(sheet.isColumnHidden(3));
assertFalse(sheet.isColumnHidden(4));
assertFalse(sheet.isColumnHidden(5));
-
+
wb2.close();
}
//comment1 and comment2 are different objects
assertNotSame(comment1, comment2);
wb1.close();
-
+
//now test against a workbook containing cell comments
XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx");
sheet1 = wb2.getSheetAt(0);
assertNotNull(comment1);
assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName());
assertSame(comment1, sheet1.getCommentsTable(true));
-
+
wb2.close();
}
assertTrue(nm.getCTName().getHidden());
assertEquals("_xlnm._FilterDatabase", nm.getCTName().getName());
assertEquals("'new sheet'!$A$1:$D$100", nm.getCTName().getStringValue());
-
+
wb.close();
}
sheet.protectSheet(null);
assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection());
-
+
wb.close();
}
wb1.close();
assertTrue(wb2.getSheetAt(0).validateSheetPassword(password));
wb2.close();
-
+
XSSFWorkbook wb3 = openSampleWorkbook("workbookProtection-sheet_password-2013.xlsx");
assertTrue(wb3.getSheetAt(0).validateSheetPassword("pwd"));
wb3.close();
}
-
+
@Test
public void bug49966() throws IOException {
XSSFSheet sheet = wb1.createSheet("Sheet 1");
assertFalse(sheet.getForceFormulaRecalculation());
-
+
// Set
sheet.setForceFormulaRecalculation(true);
assertTrue(sheet.getForceFormulaRecalculation());
}
swb.close();
}
-
+
wb.close();
}
}
swb.close();
}
-
+
wb.close();
}
name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0);
assertNotNull(name);
assertEquals("Sheet0!$B:$C", name.getRefersToFormula());
-
+
wb.close();
}
XSSFPivotTable pivotTable = sheet2.createPivotTable
(wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5"), sheet1);
assertEquals(0, pivotTable.getRowLabelColumns().size());
-
+
assertEquals(1, wb.getPivotTables().size());
assertEquals(0, sheet1.getPivotTables().size());
assertEquals(1, sheet2.getPivotTables().size());
sheet2);
wb.close();
}
-
+
@Test(expected=POIXMLException.class)
public void testReadFails() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
-
+
// Throws exception because we cannot read here
try {
sheet.onDocumentRead();
wb.close();
}
}
-
- /**
+
+ /**
* This would be better off as a testable example rather than a simple unit test
* since Sheet.createComment() was deprecated and removed.
* https://poi.apache.org/spreadsheet/quick-guide.html#CellComments
assertNotNull(comment);
wb.close();
}
-
+
protected void testCopyOneRow(String copyRowsTestWorkbook) throws IOException {
final double FLOAT_PRECISION = 1e-9;
final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook);
cell = CellUtil.getCell(destRow, col++);
assertEquals("[String] G7 cell type", CellType.STRING, cell.getCellType());
assertEquals("[String] G7 cell value", "Hello", cell.getStringCellValue());
-
+
// Int
cell = CellUtil.getCell(destRow, col++);
assertEquals("[Int] H7 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Int] H7 cell value", 15, (int) cell.getNumericCellValue());
-
+
// Float
cell = CellUtil.getCell(destRow, col++);
assertEquals("[Float] I7 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Float] I7 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION);
-
+
// Cell Formula
cell = CellUtil.getCell(destRow, col++);
assertEquals("J7", new CellReference(cell).formatAsString());
assertEquals("[Cell Formula] J7 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula] J7 cell formula", "5+2", cell.getCellFormula());
//System.out.println("Cell formula evaluation currently unsupported");
-
+
// Cell Formula with Reference
// Formula row references should be adjusted by destRowNum-srcRowNum
cell = CellUtil.getCell(destRow, col++);
CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference] K7 cell formula",
"J7+H$2", cell.getCellFormula());
-
+
// Cell Formula with Reference spanning multiple rows
cell = CellUtil.getCell(destRow, col++);
assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell type",
CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell formula",
"G7&\" \"&G8", cell.getCellFormula());
-
+
// Cell Formula with Reference spanning multiple rows
cell = CellUtil.getCell(destRow, col++);
assertEquals("[Cell Formula with Area Reference] M7 cell type",
CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Area Reference] M7 cell formula",
"SUM(H7:I8)", cell.getCellFormula());
-
+
// Array Formula
cell = CellUtil.getCell(destRow, col++);
//System.out.println("Array formulas currently unsupported");
assertEquals("[Array Formula] N7 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Array Formula] N7 cell formula", "{SUM(H7:J7*{1,2,3})}", cell.getCellFormula());
*/
-
+
// Data Format
cell = CellUtil.getCell(destRow, col++);
assertEquals("[Data Format] O7 cell type;", CellType.NUMERIC, cell.getCellType());
//FIXME: currently fails
final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)";
assertEquals("[Data Format] O7 data format", moneyFormat, cell.getCellStyle().getDataFormatString());
-
+
// Merged
cell = CellUtil.getCell(destRow, col);
assertEquals("[Merged] P7:Q7 cell value",
"Merged cells", cell.getStringCellValue());
assertTrue("[Merged] P7:Q7 merged region",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P7:Q7")));
-
+
// Merged across multiple rows
// Microsoft Excel 2013 does not copy a merged region unless all rows of
// the source merged region are selected
// which will not overwrite a cell in destination row if merged region extends beyond the copied row.
// The Excel way would require:
//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")));
// As currently implemented, cell value is copied but merged region is not copied
assertEquals("[Merged across multiple rows] R7:S8 cell value",
"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
- 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
-
+
// Make sure other rows are blank (off-by-one errors)
assertNull(sheet.getRow(5));
assertNull(sheet.getRow(7));
-
+
wb.close();
}
-
+
protected void testCopyMultipleRows(String copyRowsTestWorkbook) throws IOException {
final double FLOAT_PRECISION = 1e-9;
final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook);
final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy();
sheet.copyRows(0, 3, 8, defaultCopyPolicy);
- @SuppressWarnings("unused")
- final Row srcHeaderRow = sheet.getRow(0);
+ sheet.getRow(0);
final Row srcRow1 = sheet.getRow(1);
final Row srcRow2 = sheet.getRow(2);
final Row srcRow3 = sheet.getRow(3);
final Row destRow3 = sheet.getRow(11);
int col = 0;
Cell cell;
-
+
// Header row should be copied
assertNotNull(destHeaderRow);
-
+
// Data rows
cell = CellUtil.getCell(destRow1, col);
assertEquals("Source row ->", cell.getStringCellValue());
-
+
// Style
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Style] B10 cell value", "Red", cell.getStringCellValue());
assertEquals("[Style] B10 cell style", CellUtil.getCell(srcRow1, 1).getCellStyle(), cell.getCellStyle());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Style] B11 cell value", "Blue", cell.getStringCellValue());
assertEquals("[Style] B11 cell style", CellUtil.getCell(srcRow2, 1).getCellStyle(), cell.getCellStyle());
-
+
// Blank
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Blank] C10 cell type", CellType.BLANK, cell.getCellType());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Blank] C11 cell type", CellType.BLANK, cell.getCellType());
-
+
// Error
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Error] D10 cell type", CellType.ERROR, cell.getCellType());
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
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Error] D11 cell type", CellType.ERROR, cell.getCellType());
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
-
+
// Date
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Date] E10 cell type", CellType.NUMERIC, cell.getCellType());
Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime();
assertEquals("[Date] E10 cell value", date, cell.getDateCellValue());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Date] E11 cell type", CellType.NUMERIC, cell.getCellType());
date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 2).getTime();
assertEquals("[Date] E11 cell value", date, cell.getDateCellValue());
-
+
// Boolean
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Boolean] F10 cell type", CellType.BOOLEAN, cell.getCellType());
assertEquals("[Boolean] F10 cell value", true, cell.getBooleanCellValue());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Boolean] F11 cell type", CellType.BOOLEAN, cell.getCellType());
assertEquals("[Boolean] F11 cell value", false, cell.getBooleanCellValue());
-
+
// String
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[String] G10 cell type", CellType.STRING, cell.getCellType());
assertEquals("[String] G10 cell value", "Hello", cell.getStringCellValue());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[String] G11 cell type", CellType.STRING, cell.getCellType());
assertEquals("[String] G11 cell value", "World", cell.getStringCellValue());
-
+
// Int
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Int] H10 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Int] H10 cell value", 15, (int) cell.getNumericCellValue());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Int] H11 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Int] H11 cell value", 42, (int) cell.getNumericCellValue());
-
+
// Float
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Float] I10 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Float] I10 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION);
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Float] I11 cell type", CellType.NUMERIC, cell.getCellType());
assertEquals("[Float] I11 cell value", 5.5, cell.getNumericCellValue(), FLOAT_PRECISION);
-
+
// Cell Formula
col++;
cell = CellUtil.getCell(destRow1, col);
assertEquals("[Cell Formula] J10 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula] J10 cell formula", "5+2", cell.getCellFormula());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Cell Formula] J11 cell type", CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula] J11 cell formula", "6+18", cell.getCellFormula());
CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference] K10 cell formula",
"J10+H$2", cell.getCellFormula());
-
+
cell = CellUtil.getCell(destRow2, col);
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());
-
+
// Cell Formula with Reference spanning multiple rows
col++;
cell = CellUtil.getCell(destRow1, col);
CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference spanning multiple rows] L10 cell formula",
"G10&\" \"&G11", cell.getCellFormula());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell type",
CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell formula",
"G11&\" \"&G12", cell.getCellFormula());
-
+
// Cell Formula with Area Reference
col++;
cell = CellUtil.getCell(destRow1, col);
CellType.FORMULA, cell.getCellType());
assertEquals("[Cell Formula with Area Reference] M10 cell formula",
"SUM(H10:I11)", cell.getCellFormula());
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Cell Formula with Area Reference] M11 cell type",
CellType.FORMULA, cell.getCellType());
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
-
+
// Array Formula
col++;
cell = CellUtil.getCell(destRow1, col);
// 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 formula", "{SUM(H10:J10*{1,2,3})}", cell.getCellFormula());
-
+
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 formula", "{SUM(H11:J11*{1,2,3})}", cell.getCellFormula());
*/
-
+
// Data Format
col++;
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Data Format] O10 cell value", 100.20, cell.getNumericCellValue(), FLOAT_PRECISION);
final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)";
assertEquals("[Data Format] O10 cell data format", moneyFormat, cell.getCellStyle().getDataFormatString());
-
+
// Merged
col++;
cell = CellUtil.getCell(destRow1, col);
"Merged cells", cell.getStringCellValue());
assertTrue("[Merged] P10:Q10 merged region",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P10:Q10")));
-
+
cell = CellUtil.getCell(destRow2, col);
assertEquals("[Merged] P11:Q11 cell value", "Merged cells", cell.getStringCellValue());
assertTrue("[Merged] P11:Q11 merged region",
sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P11:Q11")));
-
+
// Should Q10/Q11 be checked?
-
+
// Merged across multiple rows
// Microsoft Excel 2013 does not copy a merged region unless all rows of
// the source merged region are selected
// POI's behavior should match this behavior
col += 2;
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());
- 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")));
-
+
// Row 3 (zero-based) was empty, so Row 11 (zero-based) should be empty too.
if (srcRow3 == null) {
assertNull("Row 3 was empty, so Row 11 should be empty", destRow3);
}
-
+
// 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 upper edge case", sheet.getRow(12)); //one row below destRow3
-
+
wb.close();
}
-
+
@Test
public void testCopyOneRow() throws IOException {
testCopyOneRow("XSSFSheet.copyRows.xlsx");
}
-
+
@Test
public void testCopyMultipleRows() throws IOException {
testCopyMultipleRows("XSSFSheet.copyRows.xlsx");
assertEquals(1, ignoredError.getSqref().size());
assertEquals("B2:D4", ignoredError.getSqref().get(0));
assertTrue(ignoredError.getNumberStoredAsText());
-
+
Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors();
assertEquals(1, ignoredErrors.size());
assertEquals(1, ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).size());
assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).iterator().next().formatAsString());
-
+
workbook.close();
}
assertFalse(ignoredError.getNumberStoredAsText());
assertTrue(ignoredError.getFormula());
assertTrue(ignoredError.getEvalError());
-
+
Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors();
assertEquals(2, ignoredErrors.size());
assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size());
// Two calls means two elements, no clever collapsing just yet.
sheet.addIgnoredErrors(region, IgnoredErrorType.EVALUATION_ERROR);
sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA);
-
+
CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0);
assertEquals(1, ignoredError.getSqref().size());
assertEquals("B2:D4", ignoredError.getSqref().get(0));
assertFalse(ignoredError.getFormula());
assertTrue(ignoredError.getEvalError());
-
+
ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(1);
assertEquals(1, ignoredError.getSqref().size());
assertEquals("B2:D4", ignoredError.getSqref().get(0));
assertTrue(ignoredError.getFormula());
assertFalse(ignoredError.getEvalError());
-
+
Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors();
assertEquals(2, ignoredErrors.size());
assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size());
assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString());
workbook.close();
}
-
+
@Test
public void setTabColor() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
sh.getCTWorksheet().getSheetPr().getTabColor().getIndexed());
}
}
-
+
@Test
public void getTabColor() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
assertEquals(expected, sh.getTabColor());
}
}
-
+
// Test using an existing workbook saved by Excel
@Test
public void tabColor() throws IOException {
assertEquals(expected, wb.getSheet("customOrange").getTabColor());
}
}
-
+
/**
* See bug #52425
*/
// Adding Comment to cloned Sheet 3
addComments(helper, sheet3);
}
-
+
private void addComments(CreationHelper helper, Sheet sheet) {
Drawing<?> drawing = sheet.createDrawingPatriarch();
}
}
-
+
// bug 59687: XSSFSheet.RemoveRow doesn't handle row gaps properly when removing row comments
@Test
public void testRemoveRowWithCommentAndGapAbove() throws IOException {
// comment exists
CellAddress commentCellAddress = new CellAddress("A4");
assertNotNull(sheet.getCellComment(commentCellAddress));
-
+
assertEquals("Wrong starting # of comments", 1, sheet.getCellComments().size());
-
+
sheet.removeRow(sheet.getRow(commentCellAddress.getRow()));
-
+
assertEquals("There should not be any comments left!", 0, sheet.getCellComments().size());
}
-
+
@Test
public void testGetHeaderFooterProperties() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = wb.createSheet();
-
+
XSSFHeaderFooterProperties hfProp = sh.getHeaderFooterProperties();
assertNotNull(hfProp);
-
+
wb.close();
}
}
//assertCloseDoesNotModifyFile(filename, wb);
// InputStream
- wb = new XSSFWorkbook(new FileInputStream(file));
- assertCloseDoesNotModifyFile(filename, wb);
+ try (FileInputStream is = new FileInputStream(file)) {
+ wb = new XSSFWorkbook(is);
+ assertCloseDoesNotModifyFile(filename, wb);
+ }
// OPCPackage
//wb = new XSSFWorkbook(OPCPackage.open(file));
row = sheet.createRow((short) rowIndex);
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
cell = row.createCell((short) colIndex);
- cell.setCellValue(colIndex * (rowIndex + 1));
+ cell.setCellValue(colIndex * (rowIndex + 1L));
}
}
package org.apache.poi.xssf.util;
-import junit.framework.TestCase;
+import java.util.ArrayList;
+import java.util.List;
+
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.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.openxmlformats.schemas.spreadsheetml.x2006.main.*;
+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 java.util.List;
-import java.util.ArrayList;
+import junit.framework.TestCase;
/**
* Mixed utilities for testing memory usage in XSSF
*/
public class MemoryUsage extends TestCase {
private static final int NUM_COLUMNS = 255;
-
+
private static void printMemoryUsage(String msg) {
System.out.println(" Memory (" + msg + "): " + Runtime.getRuntime().totalMemory()/(1024*1024) + "MB");
}
Row row = sh.createRow(i);
for(int j=0; j < numCols; j++){
Cell cell = row.createCell(j);
- if(j % 2 == 0) cell.setCellValue(j);
- else cell.setCellValue(new CellReference(j, i).formatAsString());
+ if(j % 2 == 0) {
+ cell.setCellValue(j);
+ } else {
+ cell.setCellValue(new CellReference(j, i).formatAsString());
+ }
cnt++;
}
}
/**
* Generate a spreadsheet who's all cell values are numbers.
- * The data is generated until OutOfMemoryError.
+ * The data is generated until OutOfMemoryError.
* <p>
* 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.
rows.add(r);
}
} 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) {
System.out.println("Unable to reach an OutOfMemoryError");
System.out.println(e.getClass().getName() + ": " + e.getMessage());
rows.add(r);
}
} 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) {
System.out.println("Unable to reach an OutOfMemoryError");
System.out.println(e.getClass().getName() + ": " + e.getMessage());