More IntelliJ warnings fixes

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1809370 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Dominik Stadler 2017-09-23 07:38:01 +00:00
parent 9b27d51247
commit c05129144f
17 changed files with 232 additions and 356 deletions

View File

@ -169,7 +169,6 @@ public class CopyCompare
* @exception NoPropertySetStreamException if the application tries to * @exception NoPropertySetStreamException if the application tries to
* create a property set from a POI document stream that is not a property * create a property set from a POI document stream that is not a property
* set stream. * set stream.
* @throws UnsupportedEncodingException
* @exception IOException if any I/O exception occurs. * @exception IOException if any I/O exception occurs.
*/ */
private static boolean equal(final DirectoryEntry d1, private static boolean equal(final DirectoryEntry d1,
@ -233,7 +232,6 @@ public class CopyCompare
* @exception NoPropertySetStreamException if the application tries to * @exception NoPropertySetStreamException if the application tries to
* create a property set from a POI document stream that is not a property * create a property set from a POI document stream that is not a property
* set stream. * set stream.
* @throws UnsupportedEncodingException
* @exception IOException if any I/O exception occurs. * @exception IOException if any I/O exception occurs.
*/ */
private static boolean equal(final DocumentEntry d1, final DocumentEntry d2, private static boolean equal(final DocumentEntry d1, final DocumentEntry d2,
@ -355,8 +353,6 @@ public class CopyCompare
* @param path The file's path in the POI filesystem. * @param path The file's path in the POI filesystem.
* @param name The file's name in the POI filesystem. * @param name The file's name in the POI filesystem.
* @param ps The property set to write. * @param ps The property set to write.
* @throws WritingNotSupportedException
* @throws IOException
*/ */
public void copy(final POIFSFileSystem poiFs, public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path, final POIFSDocumentPath path,
@ -378,7 +374,6 @@ public class CopyCompare
* @param path The source document's path. * @param path The source document's path.
* @param name The source document's name. * @param name The source document's name.
* @param stream The stream containing the source document. * @param stream The stream containing the source document.
* @throws IOException
*/ */
public void copy(final POIFSFileSystem poiFs, public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path, final POIFSDocumentPath path,
@ -407,9 +402,6 @@ public class CopyCompare
/** /**
* <p>Writes the POI file system to a disk file.</p> * <p>Writes the POI file system to a disk file.</p>
*
* @throws FileNotFoundException
* @throws IOException
*/ */
public void close() throws FileNotFoundException, IOException { public void close() throws FileNotFoundException, IOException {
out = new FileOutputStream(dstName); out = new FileOutputStream(dstName);

View File

@ -19,17 +19,12 @@ package org.apache.poi.hpsf.examples;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import org.apache.poi.hpsf.CustomProperties; import org.apache.poi.hpsf.CustomProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySetFactory; import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.hpsf.WritingNotSupportedException;
import org.apache.poi.poifs.filesystem.DirectoryEntry; import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
@ -76,16 +71,8 @@ public class ModifyDocumentSummaryInformation {
* <p>Main method - see class description.</p> * <p>Main method - see class description.</p>
* *
* @param args The command-line parameters. * @param args The command-line parameters.
* @throws IOException
* @throws MarkUnsupportedException
* @throws NoPropertySetStreamException
* @throws UnexpectedPropertySetTypeException
* @throws WritingNotSupportedException
*/ */
public static void main(final String[] args) throws IOException, public static void main(final String[] args) throws Exception {
NoPropertySetStreamException, MarkUnsupportedException,
UnexpectedPropertySetTypeException, WritingNotSupportedException
{
/* Read the name of the POI filesystem to modify from the command line. /* Read the name of the POI filesystem to modify from the command line.
* For brevity to boundary check is performed on the command-line * For brevity to boundary check is performed on the command-line
* arguments. */ * arguments. */

View File

@ -19,7 +19,6 @@ package org.apache.poi.hpsf.examples;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.NoPropertySetStreamException;
@ -64,7 +63,7 @@ public class ReadCustomPropertySets
@Override @Override
public void processPOIFSReaderEvent(final POIFSReaderEvent event) public void processPOIFSReaderEvent(final POIFSReaderEvent event)
{ {
PropertySet ps = null; PropertySet ps;
try try
{ {
ps = PropertySetFactory.create(event.getStream()); ps = PropertySetFactory.create(event.getStream());
@ -93,10 +92,8 @@ public class ReadCustomPropertySets
/* Print the list of sections: */ /* Print the list of sections: */
List<Section> sections = ps.getSections(); List<Section> sections = ps.getSections();
int nr = 0; int nr = 0;
for (Iterator<Section> i = sections.iterator(); i.hasNext();) for (Section sec : sections) {
{
/* Print a single section: */ /* Print a single section: */
Section sec = i.next();
out(" Section " + nr++ + ":"); out(" Section " + nr++ + ":");
String s = hex(sec.getFormatID().getBytes()); String s = hex(sec.getFormatID().getBytes());
s = s.substring(0, s.length() - 1); s = s.substring(0, s.length() - 1);
@ -108,15 +105,13 @@ public class ReadCustomPropertySets
/* Print the properties: */ /* Print the properties: */
Property[] properties = sec.getProperties(); Property[] properties = sec.getProperties();
for (int i2 = 0; i2 < properties.length; i2++) for (Property p : properties) {
{
/* Print a single property: */ /* Print a single property: */
Property p = properties[i2];
long id = p.getID(); long id = p.getID();
long type = p.getType(); long type = p.getType();
Object value = p.getValue(); Object value = p.getValue();
out(" Property ID: " + id + ", type: " + type + out(" Property ID: " + id + ", type: " + type +
", value: " + value); ", value: " + value);
} }
} }
} }

View File

@ -193,7 +193,7 @@ public class WriteAuthorAndTitle
/* According to the definition of the processPOIFSReaderEvent method /* According to the definition of the processPOIFSReaderEvent method
* we cannot pass checked exceptions to the caller. The following * we cannot pass checked exceptions to the caller. The following
* lines check whether a checked exception occured and throws an * lines check whether a checked exception occurred and throws an
* unchecked exception. The message of that exception is that of * unchecked exception. The message of that exception is that of
* the underlying checked exception. */ * the underlying checked exception. */
if (t != null) { if (t != null) {
@ -212,8 +212,6 @@ public class WriteAuthorAndTitle
* @param name The original (and destination) stream's name. * @param name The original (and destination) stream's name.
* @param si The property set. It should be a summary information * @param si The property set. It should be a summary information
* property set. * property set.
* @throws IOException
* @throws WritingNotSupportedException
*/ */
public void editSI(final POIFSFileSystem poiFs, public void editSI(final POIFSFileSystem poiFs,
final POIFSDocumentPath path, final POIFSDocumentPath path,
@ -257,8 +255,6 @@ public class WriteAuthorAndTitle
* @param path The file's path in the POI filesystem. * @param path The file's path in the POI filesystem.
* @param name The file's name in the POI filesystem. * @param name The file's name in the POI filesystem.
* @param ps The property set to write. * @param ps The property set to write.
* @throws WritingNotSupportedException
* @throws IOException
*/ */
public void copy(final POIFSFileSystem poiFs, public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path, final POIFSDocumentPath path,
@ -281,7 +277,6 @@ public class WriteAuthorAndTitle
* @param path The source document's path. * @param path The source document's path.
* @param name The source document's name. * @param name The source document's name.
* @param stream The stream containing the source document. * @param stream The stream containing the source document.
* @throws IOException
*/ */
public void copy(final POIFSFileSystem poiFs, public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path, final POIFSDocumentPath path,
@ -303,9 +298,6 @@ public class WriteAuthorAndTitle
/** /**
* <p>Writes the POI file system to a disk file.</p> * <p>Writes the POI file system to a disk file.</p>
*
* @throws FileNotFoundException
* @throws IOException
*/ */
public void close() throws FileNotFoundException, IOException public void close() throws FileNotFoundException, IOException
{ {

View File

@ -99,8 +99,6 @@ public class XLS2CSVmra implements HSSFListener {
* Creates a new XLS -> CSV converter * Creates a new XLS -> CSV converter
* @param filename The file to process * @param filename The file to process
* @param minColumns The minimum number of columns to output, or -1 for no minimum * @param minColumns The minimum number of columns to output, or -1 for no minimum
* @throws IOException
* @throws FileNotFoundException
*/ */
public XLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException { public XLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException {
this( this(

View File

@ -43,9 +43,9 @@ public class BigExample {
// create a new sheet // create a new sheet
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
// declare a row object reference // declare a row object reference
HSSFRow r = null; HSSFRow r;
// declare a cell object reference // declare a cell object reference
HSSFCell c = null; HSSFCell c;
// create 3 cell styles // create 3 cell styles
HSSFCellStyle cs = wb.createCellStyle(); HSSFCellStyle cs = wb.createCellStyle();
HSSFCellStyle cs2 = wb.createCellStyle(); HSSFCellStyle cs2 = wb.createCellStyle();
@ -69,9 +69,9 @@ public class BigExample {
//make it bold //make it bold
f2.setBold(true); f2.setBold(true);
//set cell stlye //set cell style
cs.setFont(f); cs.setFont(f);
//set the cell format see HSSFDataFromat for a full list //set the cell format see HSSFDataFormat for a full list
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
//set a thin border //set a thin border

View File

@ -20,7 +20,6 @@ package org.apache.poi.hssf.usermodel.examples;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;

View File

@ -498,13 +498,13 @@ public void paintBorder(Component c, Graphics g, int x, int y, int width,
* @param y the y origin of the line * @param y the y origin of the line
* @param thickness the thickness of the line * @param thickness the thickness of the line
* @param horizontal or vertical (true for horizontal) * @param horizontal or vertical (true for horizontal)
* @param right/bottom or left/top thickness (true for right or top), * @param rightBottom or left/top thickness (true for right or top),
* if true then the x or y origin will be incremented to provide * if true then the x or y origin will be incremented to provide
* thickness, if false, they'll be decremented. For vertical * thickness, if false, they'll be decremented. For vertical
* borders, x is incremented or decremented, for horizontal its y. * borders, x is incremented or decremented, for horizontal its y.
* Just set to true for north and west, and false for east and * Just set to true for north and west, and false for east and
* south. * south.
* @returns length - returns the length of the line. * @return length - returns the length of the line.
*/ */
private int drawDashDotDot(Graphics g,int x, int y, int thickness, private int drawDashDotDot(Graphics g,int x, int y, int thickness,
boolean horizontal, boolean horizontal,
@ -529,7 +529,7 @@ public void paintBorder(Component c, Graphics g, int x, int y, int width,
} }
/** /**
* @returns the line thickness for a border based on border type * @return the line thickness for a border based on border type
*/ */
private int getThickness(BorderStyle thickness) { private int getThickness(BorderStyle thickness) {
switch (thickness) { switch (thickness) {

View File

@ -57,23 +57,16 @@ public class DocumentDescriptorRenderer extends DefaultTreeCellRenderer
/** /**
* <p>Renders {@link DocumentDescriptor} as a string.</p> * <p>Renders {@link DocumentDescriptor} as a string.</p>
*/ */
protected String renderAsString(final DocumentDescriptor d) protected String renderAsString(final DocumentDescriptor d) {
{ return "Name: " +
final StringBuilder b = new StringBuilder(); d.name +
b.append("Name: "); " " +
b.append(d.name); HexDump.toHex(d.name) +
b.append(" "); "\n" +
b.append(HexDump.toHex(d.name)); "Size: " +
b.append("\n"); d.size +
" bytes\n" +
b.append("Size: "); "First bytes: " +
b.append(d.size); HexDump.toHex(d.bytes);
b.append(" bytes\n");
b.append("First bytes: ");
b.append(HexDump.toHex(d.bytes));
return b.toString();
} }
} }

View File

@ -84,9 +84,7 @@ public class POIBrowser extends JFrame
/* Add the POI filesystems to the tree. */ /* Add the POI filesystems to the tree. */
int displayedFiles = 0; int displayedFiles = 0;
for (int i = 0; i < args.length; i++) for (final String filename : args) {
{
final String filename = args[i];
try { try {
FileInputStream fis = new FileInputStream(filename); FileInputStream fis = new FileInputStream(filename);
POIFSReader r = new POIFSReader(); POIFSReader r = new POIFSReader();
@ -98,7 +96,7 @@ public class POIBrowser extends JFrame
System.err.println(filename + ": " + ex); System.err.println(filename + ": " + ex);
} catch (Exception t) { } catch (Exception t) {
System.err.println("Unexpected exception while reading \"" + System.err.println("Unexpected exception while reading \"" +
filename + "\":"); filename + "\":");
t.printStackTrace(System.err); t.printStackTrace(System.err);
} }
} }

View File

@ -333,10 +333,10 @@ public class AddDimensionedImage {
URL imageFile, double reqImageWidthMM, double reqImageHeightMM, URL imageFile, double reqImageWidthMM, double reqImageHeightMM,
int resizeBehaviour) throws IOException, int resizeBehaviour) throws IOException,
IllegalArgumentException { IllegalArgumentException {
ClientAnchor anchor = null; ClientAnchor anchor;
ClientAnchorDetail rowClientAnchorDetail = null; ClientAnchorDetail rowClientAnchorDetail;
ClientAnchorDetail colClientAnchorDetail = null; ClientAnchorDetail colClientAnchorDetail;
int imageType = 0; int imageType;
// Validate the resizeBehaviour parameter. // Validate the resizeBehaviour parameter.
if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) && if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&
@ -427,9 +427,9 @@ public class AddDimensionedImage {
private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber, private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber,
double reqImageWidthMM, int resizeBehaviour) { double reqImageWidthMM, int resizeBehaviour) {
double colWidthMM = 0.0D; double colWidthMM;
double colCoordinatesPerMM = 0.0D; double colCoordinatesPerMM;
int pictureWidthCoordinates = 0; int pictureWidthCoordinates;
ClientAnchorDetail colClientAnchorDetail = null; ClientAnchorDetail colClientAnchorDetail = null;
// Get the colum's width in millimetres // Get the colum's width in millimetres
@ -522,10 +522,10 @@ public class AddDimensionedImage {
*/ */
private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber, private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber,
double reqImageHeightMM, int resizeBehaviour) { double reqImageHeightMM, int resizeBehaviour) {
Row row = null; Row row;
double rowHeightMM = 0.0D; double rowHeightMM;
double rowCoordinatesPerMM = 0.0D; double rowCoordinatesPerMM;
int pictureHeightCoordinates = 0; int pictureHeightCoordinates;
ClientAnchorDetail rowClientAnchorDetail = null; ClientAnchorDetail rowClientAnchorDetail = null;
// Get the row and it's height // Get the row and it's height
@ -612,13 +612,13 @@ public class AddDimensionedImage {
private ClientAnchorDetail calculateColumnLocation(Sheet sheet, private ClientAnchorDetail calculateColumnLocation(Sheet sheet,
int startingColumn, int startingColumn,
double reqImageWidthMM) { double reqImageWidthMM) {
ClientAnchorDetail anchorDetail = null; ClientAnchorDetail anchorDetail;
double totalWidthMM = 0.0D; double totalWidthMM = 0.0D;
double colWidthMM = 0.0D; double colWidthMM = 0.0D;
double overlapMM = 0.0D; double overlapMM;
double coordinatePositionsPerMM = 0.0D; double coordinatePositionsPerMM;
int toColumn = startingColumn; int toColumn = startingColumn;
int inset = 0; int inset;
// Calculate how many columns the image will have to // Calculate how many columns the image will have to
// span in order to be presented at the required size. // span in order to be presented at the required size.
@ -722,14 +722,14 @@ public class AddDimensionedImage {
*/ */
private ClientAnchorDetail calculateRowLocation(Sheet sheet, private ClientAnchorDetail calculateRowLocation(Sheet sheet,
int startingRow, double reqImageHeightMM) { int startingRow, double reqImageHeightMM) {
ClientAnchorDetail clientAnchorDetail = null; ClientAnchorDetail clientAnchorDetail;
Row row = null; Row row;
double rowHeightMM = 0.0D; double rowHeightMM = 0.0D;
double totalRowHeightMM = 0.0D; double totalRowHeightMM = 0.0D;
double overlapMM = 0.0D; double overlapMM;
double rowCoordinatesPerMM = 0.0D; double rowCoordinatesPerMM;
int toRow = startingRow; int toRow = startingRow;
int inset = 0; int inset;
// Step through the rows in the sheet and accumulate a total of their // Step through the rows in the sheet and accumulate a total of their
// heights. // heights.
@ -813,11 +813,11 @@ public class AddDimensionedImage {
* @param args the command line arguments * @param args the command line arguments
*/ */
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
String imageFile = null; String imageFile;
String outputFile = null; String outputFile;
FileOutputStream fos = null; FileOutputStream fos;
Workbook workbook = null; Workbook workbook;
Sheet sheet = null; Sheet sheet;
if(args.length < 2){ if(args.length < 2){
System.err.println("Usage: AddDimensionedImage imageFile outputFile"); System.err.println("Usage: AddDimensionedImage imageFile outputFile");
@ -962,8 +962,6 @@ public class AddDimensionedImage {
/** /**
* pixel units to excel width units(units of 1/256th of a character width) * pixel units to excel width units(units of 1/256th of a character width)
* @param pxs
* @return
*/ */
public static short pixel2WidthUnits(int pxs) { public static short pixel2WidthUnits(int pxs) {
short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR *
@ -975,9 +973,6 @@ public class AddDimensionedImage {
/** /**
* excel width units(units of 1/256th of a character width) to pixel * excel width units(units of 1/256th of a character width) to pixel
* units. * units.
*
* @param widthUnits
* @return
*/ */
public static int widthUnits2Pixel(short widthUnits) { public static int widthUnits2Pixel(short widthUnits) {
int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR)

View File

@ -63,7 +63,6 @@ public class ConditionalFormats {
* generates a sample workbook with conditional formatting, * generates a sample workbook with conditional formatting,
* and prints out a summary of applied formats for one sheet * and prints out a summary of applied formats for one sheet
* @param args pass "-xls" to generate an HSSF workbook, default is XSSF * @param args pass "-xls" to generate an HSSF workbook, default is XSSF
* @throws IOException
*/ */
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
Workbook wb; Workbook wb;
@ -656,8 +655,6 @@ public class ConditionalFormats {
/** /**
* Print out a summary of the conditional formatting rules applied to cells on the given sheet. * Print out a summary of the conditional formatting rules applied to cells on the given sheet.
* Only cells with a matching rule are printed, and for those, all matching rules are sumarized. * Only cells with a matching rule are printed, and for those, all matching rules are sumarized.
* @param wb
* @param sheetName
*/ */
static void evaluateRules(Workbook wb, String sheetName) { static void evaluateRules(Workbook wb, String sheetName) {
final WorkbookEvaluatorProvider wbEvalProv = (WorkbookEvaluatorProvider) wb.getCreationHelper().createFormulaEvaluator(); final WorkbookEvaluatorProvider wbEvalProv = (WorkbookEvaluatorProvider) wb.getCreationHelper().createFormulaEvaluator();

View File

@ -285,8 +285,8 @@ public class ToCSV {
IllegalArgumentException, InvalidFormatException { IllegalArgumentException, InvalidFormatException {
File source = new File(strSource); File source = new File(strSource);
File destination = new File(strDestination); File destination = new File(strDestination);
File[] filesList = null; File[] filesList;
String destinationFilename = null; String destinationFilename;
// Check that the source file/folder exists. // Check that the source file/folder exists.
if(!source.exists()) { if(!source.exists()) {
@ -406,9 +406,9 @@ public class ToCSV {
* a CSV file. * a CSV file.
*/ */
private void convertToCSV() { private void convertToCSV() {
Sheet sheet = null; Sheet sheet;
Row row = null; Row row;
int lastRowNum = 0; int lastRowNum;
this.csvData = new ArrayList<>(); this.csvData = new ArrayList<>();
System.out.println("Converting files contents to CSV format."); System.out.println("Converting files contents to CSV format.");
@ -451,11 +451,11 @@ public class ToCSV {
*/ */
private void saveCSVFile(File file) private void saveCSVFile(File file)
throws FileNotFoundException, IOException { throws FileNotFoundException, IOException {
FileWriter fw = null; FileWriter fw;
BufferedWriter bw = null; BufferedWriter bw = null;
ArrayList<String> line = null; ArrayList<String> line;
StringBuffer buffer = null; StringBuffer buffer;
String csvLineElement = null; String csvLineElement;
try { try {
System.out.println("Saving the CSV file [" + file.getName() + "]"); System.out.println("Saving the CSV file [" + file.getName() + "]");
@ -524,8 +524,8 @@ public class ToCSV {
* an Excel workbook. * an Excel workbook.
*/ */
private void rowToCSV(Row row) { private void rowToCSV(Row row) {
Cell cell = null; Cell cell;
int lastCellNum = 0; int lastCellNum;
ArrayList<String> csvLine = new ArrayList<>(); ArrayList<String> csvLine = new ArrayList<>();
// Check to ensure that a row was recovered from the sheet as it is // Check to ensure that a row was recovered from the sheet as it is
@ -603,7 +603,7 @@ public class ToCSV {
* speech mark characters correctly escaped. * speech mark characters correctly escaped.
*/ */
private String escapeEmbeddedCharacters(String field) { private String escapeEmbeddedCharacters(String field) {
StringBuffer buffer = null; StringBuffer buffer;
// If the fields contents should be formatted to confrom with Excel's // If the fields contents should be formatted to confrom with Excel's
// convention.... // convention....
@ -671,7 +671,7 @@ public class ToCSV {
// with matching names but different extensions - Test.xls and Test.xlsx // with matching names but different extensions - Test.xls and Test.xlsx
// for example - then the CSV file generated from one will overwrite // for example - then the CSV file generated from one will overwrite
// that generated from the other. // that generated from the other.
ToCSV converter = null; ToCSV converter;
boolean converted = true; boolean converted = true;
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
try { try {

View File

@ -328,12 +328,9 @@ public class ToHtml {
style = wb.getCellStyleAt((short) 0); style = wb.getCellStyleAt((short) 0);
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb); try (Formatter fmt = new Formatter(sb)) {
try {
fmt.format("style_%02x", style.getIndex()); fmt.format("style_%02x", style.getIndex());
return fmt.toString(); return fmt.toString();
} finally {
fmt.close();
} }
} }
@ -371,14 +368,14 @@ public class ToHtml {
/** /**
* computes the column widths, defined by the sheet. * computes the column widths, defined by the sheet.
* *
* @param sheet * @param sheet The sheet for which to compute widths
* @return Map with key: column index; value: column width in pixels * @return Map with key: column index; value: column width in pixels
* <br>special keys: * <br>special keys:
* <br>{@link #IDX_HEADER_COL_WIDTH} - width of the header column * <br>{@link #IDX_HEADER_COL_WIDTH} - width of the header column
* <br>{@link #IDX_TABLE_WIDTH} - width of the entire table * <br>{@link #IDX_TABLE_WIDTH} - width of the entire table
*/ */
private Map<Integer, Integer> computeWidths(Sheet sheet) { private Map<Integer, Integer> computeWidths(Sheet sheet) {
Map<Integer, Integer> ret = new TreeMap<Integer, Integer>(); Map<Integer, Integer> ret = new TreeMap<>();
int tableWidth = 0; int tableWidth = 0;
ensureColumnBounds(sheet); ensureColumnBounds(sheet);

View File

@ -20,7 +20,6 @@
package org.apache.poi.xssf.eventusermodel.examples; package org.apache.poi.xssf.eventusermodel.examples;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.crypt.examples.EncryptionUtils; import org.apache.poi.crypt.examples.EncryptionUtils;

View File

@ -44,170 +44,148 @@ public class TestXSSFImportFromXML {
@Test @Test
public void testImportFromXML() throws IOException, XPathExpressionException, SAXException{ public void testImportFromXML() throws IOException, XPathExpressionException, SAXException{
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx")) {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx"); String name = "name";
try { String teacher = "teacher";
String name = "name"; String tutor = "tutor";
String teacher = "teacher"; String cdl = "cdl";
String tutor = "tutor"; String duration = "duration";
String cdl = "cdl"; String topic = "topic";
String duration = "duration"; String project = "project";
String topic = "topic"; String credits = "credits";
String project = "project";
String credits = "credits"; String testXML = "<CORSO>" +
"<NOME>" + name + "</NOME>" +
String testXML = "<CORSO>"+ "<DOCENTE>" + teacher + "</DOCENTE>" +
"<NOME>"+name+"</NOME>"+ "<TUTOR>" + tutor + "</TUTOR>" +
"<DOCENTE>"+teacher+"</DOCENTE>"+ "<CDL>" + cdl + "</CDL>" +
"<TUTOR>"+tutor+"</TUTOR>"+ "<DURATA>" + duration + "</DURATA>" +
"<CDL>"+cdl+"</CDL>"+ "<ARGOMENTO>" + topic + "</ARGOMENTO>" +
"<DURATA>"+duration+"</DURATA>"+ "<PROGETTO>" + project + "</PROGETTO>" +
"<ARGOMENTO>"+topic+"</ARGOMENTO>"+ "<CREDITI>" + credits + "</CREDITI>" +
"<PROGETTO>"+project+"</PROGETTO>"+ "</CORSO>\u0000";
"<CREDITI>"+credits+"</CREDITI>"+
"</CORSO>\u0000"; XSSFMap map = wb.getMapInfo().getXSSFMapByName("CORSO_mapping");
assertNotNull(map);
XSSFMap map = wb.getMapInfo().getXSSFMapByName("CORSO_mapping"); XSSFImportFromXML importer = new XSSFImportFromXML(map);
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map); importer.importFromXML(testXML);
importer.importFromXML(testXML); XSSFSheet sheet = wb.getSheetAt(0);
XSSFSheet sheet=wb.getSheetAt(0); XSSFRow row = sheet.getRow(0);
assertTrue(row.getCell(0).getStringCellValue().equals(name));
XSSFRow row = sheet.getRow(0); assertTrue(row.getCell(1).getStringCellValue().equals(teacher));
assertTrue(row.getCell(0).getStringCellValue().equals(name)); assertTrue(row.getCell(2).getStringCellValue().equals(tutor));
assertTrue(row.getCell(1).getStringCellValue().equals(teacher)); assertTrue(row.getCell(3).getStringCellValue().equals(cdl));
assertTrue(row.getCell(2).getStringCellValue().equals(tutor)); assertTrue(row.getCell(4).getStringCellValue().equals(duration));
assertTrue(row.getCell(3).getStringCellValue().equals(cdl)); assertTrue(row.getCell(5).getStringCellValue().equals(topic));
assertTrue(row.getCell(4).getStringCellValue().equals(duration)); assertTrue(row.getCell(6).getStringCellValue().equals(project));
assertTrue(row.getCell(5).getStringCellValue().equals(topic)); assertTrue(row.getCell(7).getStringCellValue().equals(credits));
assertTrue(row.getCell(6).getStringCellValue().equals(project)); }
assertTrue(row.getCell(7).getStringCellValue().equals(credits));
} finally {
wb.close();
}
} }
@Test(timeout=60000) @Test(timeout=60000)
public void testMultiTable() throws IOException, XPathExpressionException, SAXException{ public void testMultiTable() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx"); try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) {
try { String cellC6 = "c6";
String cellC6 = "c6"; String cellC7 = "c7";
String cellC7 = "c7"; String cellC8 = "c8";
String cellC8 = "c8"; String cellC9 = "c9";
String cellC9 = "c9";
StringBuilder testXML = new StringBuilder("<ns1:MapInfo xmlns:ns1=\"" + NS_SPREADSHEETML + "\" SelectionNamespaces=\"\">" +
String testXML = "<ns1:MapInfo xmlns:ns1=\""+NS_SPREADSHEETML+"\" SelectionNamespaces=\"\">" + "<ns1:Schema ID=\"" + cellC6 + "\" SchemaRef=\"a\" />" +
"<ns1:Schema ID=\""+cellC6+"\" SchemaRef=\"a\" />"+ "<ns1:Schema ID=\"" + cellC7 + "\" SchemaRef=\"b\" />" +
"<ns1:Schema ID=\""+cellC7+"\" SchemaRef=\"b\" />"+ "<ns1:Schema ID=\"" + cellC8 + "\" SchemaRef=\"c\" />" +
"<ns1:Schema ID=\""+cellC8+"\" SchemaRef=\"c\" />"+ "<ns1:Schema ID=\"" + cellC9 + "\" SchemaRef=\"d\" />");
"<ns1:Schema ID=\""+cellC9+"\" SchemaRef=\"d\" />";
for (int i = 10; i < 10010; i++) {
for(int i = 10; i< 10010; i++){ testXML.append("<ns1:Schema ID=\"c").append(i).append("\" SchemaRef=\"d\" />");
testXML += "<ns1:Schema ID=\"c"+i+"\" SchemaRef=\"d\" />"; }
}
testXML.append("<ns1:Map ID=\"1\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "<ns1:Map ID=\"2\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "<ns1:Map ID=\"3\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "</ns1:MapInfo>\u0000");
testXML += "<ns1:Map ID=\"1\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">"+
"<ns1:DataBinding DataBindingLoadMode=\"\" />"+ XSSFMap map = wb.getMapInfo().getXSSFMapByName("MapInfo_mapping");
"</ns1:Map>"+ assertNotNull(map);
"<ns1:Map ID=\"2\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">"+ XSSFImportFromXML importer = new XSSFImportFromXML(map);
"<ns1:DataBinding DataBindingLoadMode=\"\" />"+
"</ns1:Map>"+ importer.importFromXML(testXML.toString());
"<ns1:Map ID=\"3\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">"+
"<ns1:DataBinding DataBindingLoadMode=\"\" />"+ //Check for Schema element
"</ns1:Map>"+ XSSFSheet sheet = wb.getSheetAt(1);
"</ns1:MapInfo>\u0000";
assertEquals(cellC6, sheet.getRow(5).getCell(2).getStringCellValue());
XSSFMap map = wb.getMapInfo().getXSSFMapByName("MapInfo_mapping"); assertEquals(cellC7, sheet.getRow(6).getCell(2).getStringCellValue());
assertNotNull(map); assertEquals(cellC8, sheet.getRow(7).getCell(2).getStringCellValue());
XSSFImportFromXML importer = new XSSFImportFromXML(map); assertEquals(cellC9, sheet.getRow(8).getCell(2).getStringCellValue());
assertEquals("c5001", sheet.getRow(5000).getCell(2).getStringCellValue());
importer.importFromXML(testXML); }
//Check for Schema element
XSSFSheet sheet=wb.getSheetAt(1);
assertEquals(cellC6,sheet.getRow(5).getCell(2).getStringCellValue());
assertEquals(cellC7,sheet.getRow(6).getCell(2).getStringCellValue());
assertEquals(cellC8,sheet.getRow(7).getCell(2).getStringCellValue());
assertEquals(cellC9,sheet.getRow(8).getCell(2).getStringCellValue());
assertEquals("c5001",sheet.getRow(5000).getCell(2).getStringCellValue());
} finally {
wb.close();
}
} }
@Test @Test
public void testSingleAttributeCellWithNamespace() throws IOException, XPathExpressionException, SAXException{ public void testSingleAttributeCellWithNamespace() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx"); try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx")) {
try { int id = 1;
int id = 1; String displayName = "dispName";
String displayName = "dispName"; String ref = "19";
String ref="19"; int count = 21;
int count = 21;
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" +
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>"+ "<ns1:table xmlns:ns1=\"" + NS_SPREADSHEETML + "\" id=\"" + id + "\" displayName=\"" + displayName + "\" ref=\"" + ref + "\">" +
"<ns1:table xmlns:ns1=\""+NS_SPREADSHEETML+"\" id=\""+id+"\" displayName=\""+displayName+"\" ref=\""+ref+"\">"+ "<ns1:tableColumns count=\"" + count + "\" />" +
"<ns1:tableColumns count=\""+count+"\" />"+ "</ns1:table>\u0000";
"</ns1:table>\u0000"; XSSFMap map = wb.getMapInfo().getXSSFMapByName("table_mapping");
XSSFMap map = wb.getMapInfo().getXSSFMapByName("table_mapping"); assertNotNull(map);
assertNotNull(map); XSSFImportFromXML importer = new XSSFImportFromXML(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map); importer.importFromXML(testXML);
importer.importFromXML(testXML);
//Check for Schema element
//Check for Schema element XSSFSheet sheet = wb.getSheetAt(0);
XSSFSheet sheet=wb.getSheetAt(0);
assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0);
assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0); assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue());
assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue()); assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue());
assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue()); assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0);
assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0); }
} finally {
wb.close();
}
} }
@Test @Test
public void testOptionalFields_Bugzilla_55864() throws IOException, XPathExpressionException, SAXException { public void testOptionalFields_Bugzilla_55864() throws IOException, XPathExpressionException, SAXException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx"); try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx")) {
try { String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<PersonInfoRoot>" +
"<PersonInfoRoot>" + "<PersonData>" +
"<PersonData>" + "<FirstName>Albert</FirstName>" +
"<FirstName>Albert</FirstName>" + "<LastName>Einstein</LastName>" +
"<LastName>Einstein</LastName>" + "<BirthDate>1879-03-14</BirthDate>" +
"<BirthDate>1879-03-14</BirthDate>" + "</PersonData>" +
"</PersonData>" + "</PersonInfoRoot>";
"</PersonInfoRoot>";
XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map");
XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map"); assertNotNull(map);
assertNotNull(map); XSSFImportFromXML importer = new XSSFImportFromXML(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML);
importer.importFromXML(testXML);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFSheet sheet=wb.getSheetAt(0);
XSSFRow rowHeadings = sheet.getRow(0);
XSSFRow rowHeadings = sheet.getRow(0); XSSFRow rowData = sheet.getRow(1);
XSSFRow rowData = sheet.getRow(1);
assertEquals("FirstName", rowHeadings.getCell(0).getStringCellValue());
assertEquals("FirstName", rowHeadings.getCell(0).getStringCellValue()); assertEquals("Albert", rowData.getCell(0).getStringCellValue());
assertEquals("Albert", rowData.getCell(0).getStringCellValue());
assertEquals("LastName", rowHeadings.getCell(1).getStringCellValue());
assertEquals("LastName", rowHeadings.getCell(1).getStringCellValue()); assertEquals("Einstein", rowData.getCell(1).getStringCellValue());
assertEquals("Einstein", rowData.getCell(1).getStringCellValue());
assertEquals("BirthDate", rowHeadings.getCell(2).getStringCellValue());
assertEquals("BirthDate", rowHeadings.getCell(2).getStringCellValue()); assertEquals("1879-03-14", rowData.getCell(2).getStringCellValue());
assertEquals("1879-03-14", rowData.getCell(2).getStringCellValue());
// Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx
// Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue());
assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue()); assertNull("", rowData.getCell(3));
assertNull("", rowData.getCell(3)); }
} finally {
wb.close();
}
} }
@Test @Test

View File

@ -180,8 +180,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test @Test
public void getCellStyleAt() throws IOException{ public void getCellStyleAt() throws IOException{
XSSFWorkbook workbook = new XSSFWorkbook(); try (XSSFWorkbook workbook = new XSSFWorkbook()) {
try {
short i = 0; short i = 0;
//get default style //get default style
CellStyle cellStyleAt = workbook.getCellStyleAt(i); CellStyle cellStyleAt = workbook.getCellStyleAt(i);
@ -194,17 +193,14 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
font.setFontName("Verdana"); font.setFontName("Verdana");
customStyle.setFont(font); customStyle.setFont(font);
int x = styleSource.putStyle(customStyle); int x = styleSource.putStyle(customStyle);
cellStyleAt = workbook.getCellStyleAt((short)x); cellStyleAt = workbook.getCellStyleAt((short) x);
assertNotNull(cellStyleAt); assertNotNull(cellStyleAt);
} finally { }
workbook.close();
}
} }
@Test @Test
public void getFontAt() throws IOException{ public void getFontAt() throws IOException{
XSSFWorkbook workbook = new XSSFWorkbook(); try (XSSFWorkbook workbook = new XSSFWorkbook()) {
try {
StylesTable styleSource = workbook.getStylesSource(); StylesTable styleSource = workbook.getStylesSource();
short i = 0; short i = 0;
//get default font //get default font
@ -215,22 +211,17 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
XSSFFont customFont = new XSSFFont(); XSSFFont customFont = new XSSFFont();
customFont.setItalic(true); customFont.setItalic(true);
int x = styleSource.putFont(customFont); int x = styleSource.putFont(customFont);
fontAt = workbook.getFontAt((short)x); fontAt = workbook.getFontAt((short) x);
assertNotNull(fontAt); assertNotNull(fontAt);
} finally { }
workbook.close();
}
} }
@Test @Test
public void getNumCellStyles() throws IOException{ public void getNumCellStyles() throws IOException{
XSSFWorkbook workbook = new XSSFWorkbook(); try (XSSFWorkbook workbook = new XSSFWorkbook()) {
try {
//get default cellStyles //get default cellStyles
assertEquals(1, workbook.getNumCellStyles()); assertEquals(1, workbook.getNumCellStyles());
} finally { }
workbook.close();
}
} }
@Test @Test
@ -303,35 +294,27 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test @Test
public void incrementSheetId() throws IOException { public void incrementSheetId() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); try (XSSFWorkbook wb = new XSSFWorkbook()) {
try { int sheetId = (int) wb.createSheet().sheet.getSheetId();
int sheetId = (int)wb.createSheet().sheet.getSheetId();
assertEquals(1, sheetId); assertEquals(1, sheetId);
sheetId = (int)wb.createSheet().sheet.getSheetId(); sheetId = (int) wb.createSheet().sheet.getSheetId();
assertEquals(2, sheetId); assertEquals(2, sheetId);
//test file with gaps in the sheetId sequence //test file with gaps in the sheetId sequence
XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm"); try (XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm")) {
try { int lastSheetId = (int) wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId();
int lastSheetId = (int)wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId(); sheetId = (int) wbBack.createSheet().sheet.getSheetId();
sheetId = (int)wbBack.createSheet().sheet.getSheetId(); assertEquals(lastSheetId + 1, sheetId);
assertEquals(lastSheetId+1, sheetId);
} finally {
wbBack.close();
} }
} finally {
wb.close();
} }
} }
/** /**
* Test setting of core properties such as Title and Author * Test setting of core properties such as Title and Author
* @throws IOException
*/ */
@Test @Test
public void workbookProperties() throws IOException { public void workbookProperties() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); try (XSSFWorkbook workbook = new XSSFWorkbook()) {
try {
POIXMLProperties props = workbook.getProperties(); POIXMLProperties props = workbook.getProperties();
assertNotNull(props); assertNotNull(props);
//the Application property must be set for new workbooks, see Bugzilla #47559 //the Application property must be set for new workbooks, see Bugzilla #47559
@ -350,8 +333,6 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().getValue()); assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().getValue());
assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().getValue()); assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().getValue());
wbBack.close(); wbBack.close();
} finally {
workbook.close();
} }
} }
@ -396,6 +377,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
/** /**
* When deleting a sheet make sure that we adjust sheet indices of named ranges * When deleting a sheet make sure that we adjust sheet indices of named ranges
*/ */
@SuppressWarnings("deprecation")
@Test @Test
public void bug47737() throws IOException { public void bug47737() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx");
@ -500,8 +482,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test @Test
public void recalcId() throws IOException { public void recalcId() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); try (XSSFWorkbook wb = new XSSFWorkbook()) {
try {
assertFalse(wb.getForceFormulaRecalculation()); assertFalse(wb.getForceFormulaRecalculation());
CTWorkbook ctWorkbook = wb.getCTWorkbook(); CTWorkbook ctWorkbook = wb.getCTWorkbook();
assertFalse(ctWorkbook.isSetCalcPr()); assertFalse(ctWorkbook.isSetCalcPr());
@ -523,8 +504,6 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
calcPr.setCalcMode(STCalcMode.MANUAL); calcPr.setCalcMode(STCalcMode.MANUAL);
wb.setForceFormulaRecalculation(true); wb.setForceFormulaRecalculation(true);
assertEquals(STCalcMode.AUTO, calcPr.getCalcMode()); assertEquals(STCalcMode.AUTO, calcPr.getCalcMode());
} finally {
wb.close();
} }
} }
@ -549,11 +528,8 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
accessWorkbook(workbook); accessWorkbook(workbook);
ByteArrayOutputStream stream = new ByteArrayOutputStream(); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
try {
workbook.write(stream); workbook.write(stream);
} finally {
stream.close();
} }
accessWorkbook(workbook); accessWorkbook(workbook);
@ -703,8 +679,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test @Test
public void bug51158a() throws IOException { public void bug51158a() throws IOException {
// create a workbook // create a workbook
final XSSFWorkbook workbook = new XSSFWorkbook(); try (XSSFWorkbook workbook = new XSSFWorkbook()) {
try {
workbook.createSheet("Test Sheet"); workbook.createSheet("Test Sheet");
XSSFSheet sheetBack = workbook.getSheetAt(0); XSSFSheet sheetBack = workbook.getSheetAt(0);
@ -713,7 +688,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
sheetBack.commit(); sheetBack.commit();
// ensure that a memory based package part does not have lingering data from previous commit() calls // ensure that a memory based package part does not have lingering data from previous commit() calls
if(sheetBack.getPackagePart() instanceof MemoryPackagePart) { if (sheetBack.getPackagePart() instanceof MemoryPackagePart) {
sheetBack.getPackagePart().clear(); sheetBack.getPackagePart().clear();
} }
@ -722,8 +697,6 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()), "UTF-8"); String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()), "UTF-8");
assertEquals(1, countMatches(str, "<worksheet")); assertEquals(1, countMatches(str, "<worksheet"));
} finally {
workbook.close();
} }
} }
@ -752,16 +725,13 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test @Test
public void testAddPivotCache() throws IOException { public void testAddPivotCache() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); try (XSSFWorkbook wb = new XSSFWorkbook()) {
try {
CTWorkbook ctWb = wb.getCTWorkbook(); CTWorkbook ctWb = wb.getCTWorkbook();
CTPivotCache pivotCache = wb.addPivotCache("0"); CTPivotCache pivotCache = wb.addPivotCache("0");
//Ensures that pivotCaches is initiated //Ensures that pivotCaches is initiated
assertTrue(ctWb.isSetPivotCaches()); assertTrue(ctWb.isSetPivotCaches());
assertSame(pivotCache, ctWb.getPivotCaches().getPivotCacheArray(0)); assertSame(pivotCache, ctWb.getPivotCaches().getPivotCacheArray(0));
assertEquals("0", pivotCache.getId()); assertEquals("0", pivotCache.getId());
} finally {
wb.close();
} }
} }
@ -801,22 +771,16 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
public void testLoadWorkbookWithPivotTable() throws Exception { public void testLoadWorkbookWithPivotTable() throws Exception {
File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx"); File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx");
XSSFWorkbook wb = new XSSFWorkbook(); try (XSSFWorkbook wb = new XSSFWorkbook()) {
try {
setPivotData(wb); setPivotData(wb);
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
} finally {
wb.close();
} }
XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file); try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) {
try {
assertTrue(wb2.getPivotTables().size() == 1); assertTrue(wb2.getPivotTables().size() == 1);
} finally {
wb2.close();
} }
assertTrue(file.delete()); assertTrue(file.delete());
@ -826,26 +790,17 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
public void testAddPivotTableToWorkbookWithLoadedPivotTable() throws Exception { public void testAddPivotTableToWorkbookWithLoadedPivotTable() throws Exception {
File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx"); File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx");
XSSFWorkbook wb = new XSSFWorkbook(); try (XSSFWorkbook wb = new XSSFWorkbook()) {
try {
setPivotData(wb); setPivotData(wb);
FileOutputStream fileOut = new FileOutputStream(file); try (FileOutputStream fileOut = new FileOutputStream(file)) {
try {
wb.write(fileOut); wb.write(fileOut);
} finally {
fileOut.close();
} }
} finally {
wb.close();
} }
XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file); try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) {
try {
setPivotData(wb2); setPivotData(wb2);
assertTrue(wb2.getPivotTables().size() == 2); assertTrue(wb2.getPivotTables().size() == 2);
} finally {
wb2.close();
} }
assertTrue(file.delete()); assertTrue(file.delete());
@ -853,17 +808,17 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test @Test
public void testSetFirstVisibleTab_57373() throws IOException { public void testSetFirstVisibleTab_57373() throws IOException {
Workbook wb = new XSSFWorkbook();
try { try (Workbook wb = new XSSFWorkbook()) {
/*Sheet sheet1 =*/ wb.createSheet(); /*Sheet sheet1 =*/
wb.createSheet();
Sheet sheet2 = wb.createSheet(); Sheet sheet2 = wb.createSheet();
int idx2 = wb.getSheetIndex(sheet2); int idx2 = wb.getSheetIndex(sheet2);
Sheet sheet3 = wb.createSheet(); Sheet sheet3 = wb.createSheet();
int idx3 = wb.getSheetIndex(sheet3); int idx3 = wb.getSheetIndex(sheet3);
// add many sheets so "first visible" is relevant // add many sheets so "first visible" is relevant
for(int i = 0; i < 30;i++) { for (int i = 0; i < 30; i++) {
wb.createSheet(); wb.createSheet();
} }
@ -878,12 +833,12 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
sheet2 = wbBack.getSheetAt(idx2); sheet2 = wbBack.getSheetAt(idx2);
assertNotNull(sheet2);
sheet3 = wbBack.getSheetAt(idx3); sheet3 = wbBack.getSheetAt(idx3);
assertNotNull(sheet3);
assertEquals(idx2, wb.getFirstVisibleTab()); assertEquals(idx2, wb.getFirstVisibleTab());
assertEquals(idx3, wb.getActiveSheetIndex()); assertEquals(idx3, wb.getActiveSheetIndex());
wbBack.close(); wbBack.close();
} finally {
wb.close();
} }
} }
@ -947,8 +902,8 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
* In order to make code for looping over sheets in workbooks standard, regardless * In order to make code for looping over sheets in workbooks standard, regardless
* of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously * of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously
* available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator * available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator
* have been replaced with Iterator<Sheet> {@link #iterator} and * have been replaced with Iterator<Sheet> {@link Sheet#iterator} and
* Iterator<Sheet> {@link #sheetIterator}. This makes iterating over sheets in a workbook * Iterator<Sheet> {@link Workbook#sheetIterator}. This makes iterating over sheets in a workbook
* similar to iterating over rows in a sheet and cells in a row. * similar to iterating over rows in a sheet and cells in a row.
* *
* Note: this breaks backwards compatibility! Existing codebases will need to * Note: this breaks backwards compatibility! Existing codebases will need to
@ -1124,6 +1079,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
wb.close(); wb.close();
} }
@SuppressWarnings("deprecation")
@Test @Test
public void testRemoveSheet() throws IOException { public void testRemoveSheet() throws IOException {
// Test removing a sheet maintains the named ranges correctly // Test removing a sheet maintains the named ranges correctly