* @exception NoPropertySetStreamException if the application tries to
* create a property set from a POI document stream that is not a property
* set stream.
- * @throws UnsupportedEncodingException
* @exception IOException if any I/O exception occurs.
*/
private static boolean equal(final DirectoryEntry d1,
* @exception NoPropertySetStreamException if the application tries to
* create a property set from a POI document stream that is not a property
* set stream.
- * @throws UnsupportedEncodingException
* @exception IOException if any I/O exception occurs.
*/
private static boolean equal(final DocumentEntry d1, final DocumentEntry d2,
* @param path The file's path in the POI filesystem.
* @param name The file's name in the POI filesystem.
* @param ps The property set to write.
- * @throws WritingNotSupportedException
- * @throws IOException
*/
public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
* @param path The source document's path.
* @param name The source document's name.
* @param stream The stream containing the source document.
- * @throws IOException
*/
public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
/**
* <p>Writes the POI file system to a disk file.</p>
- *
- * @throws FileNotFoundException
- * @throws IOException
*/
public void close() throws FileNotFoundException, IOException {
out = new FileOutputStream(dstName);
import java.io.File;
import java.io.FileNotFoundException;
-import java.io.IOException;
import java.util.Date;
import org.apache.poi.hpsf.CustomProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation;
-import org.apache.poi.hpsf.MarkUnsupportedException;
-import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
-import org.apache.poi.hpsf.WritingNotSupportedException;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
* <p>Main method - see class description.</p>
*
* @param args The command-line parameters.
- * @throws IOException
- * @throws MarkUnsupportedException
- * @throws NoPropertySetStreamException
- * @throws UnexpectedPropertySetTypeException
- * @throws WritingNotSupportedException
*/
- public static void main(final String[] args) throws IOException,
- NoPropertySetStreamException, MarkUnsupportedException,
- UnexpectedPropertySetTypeException, WritingNotSupportedException
- {
+ public static void main(final String[] args) throws Exception {
/* Read the name of the POI filesystem to modify from the command line.
* For brevity to boundary check is performed on the command-line
* arguments. */
import java.io.FileInputStream;
import java.io.IOException;
-import java.util.Iterator;
import java.util.List;
import org.apache.poi.hpsf.NoPropertySetStreamException;
@Override
public void processPOIFSReaderEvent(final POIFSReaderEvent event)
{
- PropertySet ps = null;
+ PropertySet ps;
try
{
ps = PropertySetFactory.create(event.getStream());
/* Print the list of sections: */
List<Section> sections = ps.getSections();
int nr = 0;
- for (Iterator<Section> i = sections.iterator(); i.hasNext();)
- {
+ for (Section sec : sections) {
/* Print a single section: */
- Section sec = i.next();
out(" Section " + nr++ + ":");
String s = hex(sec.getFormatID().getBytes());
s = s.substring(0, s.length() - 1);
/* Print the properties: */
Property[] properties = sec.getProperties();
- for (int i2 = 0; i2 < properties.length; i2++)
- {
+ for (Property p : properties) {
/* Print a single property: */
- Property p = properties[i2];
long id = p.getID();
long type = p.getType();
Object value = p.getValue();
out(" Property ID: " + id + ", type: " + type +
- ", value: " + value);
+ ", value: " + value);
}
}
}
/* According to the definition of the processPOIFSReaderEvent method
* we cannot pass checked exceptions to the caller. The following
- * lines check whether a checked exception occured and throws an
+ * lines check whether a checked exception occurred and throws an
* unchecked exception. The message of that exception is that of
* the underlying checked exception. */
if (t != null) {
* @param name The original (and destination) stream's name.
* @param si The property set. It should be a summary information
* property set.
- * @throws IOException
- * @throws WritingNotSupportedException
*/
public void editSI(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
* @param path The file's path in the POI filesystem.
* @param name The file's name in the POI filesystem.
* @param ps The property set to write.
- * @throws WritingNotSupportedException
- * @throws IOException
*/
public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
* @param path The source document's path.
* @param name The source document's name.
* @param stream The stream containing the source document.
- * @throws IOException
*/
public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
/**
* <p>Writes the POI file system to a disk file.</p>
- *
- * @throws FileNotFoundException
- * @throws IOException
*/
public void close() throws FileNotFoundException, IOException
{
* Creates a new XLS -> CSV converter
* @param filename The file to process
* @param minColumns The minimum number of columns to output, or -1 for no minimum
- * @throws IOException
- * @throws FileNotFoundException
*/
public XLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException {
this(
// create a new sheet
HSSFSheet s = wb.createSheet();
// declare a row object reference
- HSSFRow r = null;
+ HSSFRow r;
// declare a cell object reference
- HSSFCell c = null;
+ HSSFCell c;
// create 3 cell styles
HSSFCellStyle cs = wb.createCellStyle();
HSSFCellStyle cs2 = wb.createCellStyle();
//make it bold
f2.setBold(true);
- //set cell stlye
+ //set cell style
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)"));
//set a thin border
import java.io.File;
import java.io.FileOutputStream;
-import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
* @param y the y origin of the line
* @param thickness the thickness of the line
* @param horizontal or vertical (true for horizontal)
- * @param right/bottom or left/top thickness (true for right or top),
+ * @param rightBottom or left/top thickness (true for right or top),
* if true then the x or y origin will be incremented to provide
* thickness, if false, they'll be decremented. For vertical
* borders, x is incremented or decremented, for horizontal its y.
* Just set to true for north and west, and false for east and
* south.
- * @returns length - returns the length of the line.
+ * @return length - returns the length of the line.
*/
private int drawDashDotDot(Graphics g,int x, int y, int thickness,
boolean horizontal,
}
/**
- * @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) {
switch (thickness) {
/**
* <p>Renders {@link DocumentDescriptor} as a string.</p>
*/
- protected String renderAsString(final DocumentDescriptor d)
- {
- final StringBuilder b = new StringBuilder();
- b.append("Name: ");
- b.append(d.name);
- b.append(" ");
- b.append(HexDump.toHex(d.name));
- b.append("\n");
-
- b.append("Size: ");
- b.append(d.size);
- b.append(" bytes\n");
-
- b.append("First bytes: ");
- b.append(HexDump.toHex(d.bytes));
-
- return b.toString();
+ protected String renderAsString(final DocumentDescriptor d) {
+ return "Name: " +
+ d.name +
+ " " +
+ HexDump.toHex(d.name) +
+ "\n" +
+ "Size: " +
+ d.size +
+ " bytes\n" +
+ "First bytes: " +
+ HexDump.toHex(d.bytes);
}
-
}
/* Add the POI filesystems to the tree. */
int displayedFiles = 0;
- for (int i = 0; i < args.length; i++)
- {
- final String filename = args[i];
+ for (final String filename : args) {
try {
FileInputStream fis = new FileInputStream(filename);
POIFSReader r = new POIFSReader();
System.err.println(filename + ": " + ex);
} catch (Exception t) {
System.err.println("Unexpected exception while reading \"" +
- filename + "\":");
+ filename + "\":");
t.printStackTrace(System.err);
}
}
URL imageFile, double reqImageWidthMM, double reqImageHeightMM,
int resizeBehaviour) throws IOException,
IllegalArgumentException {
- ClientAnchor anchor = null;
- ClientAnchorDetail rowClientAnchorDetail = null;
- ClientAnchorDetail colClientAnchorDetail = null;
- int imageType = 0;
+ ClientAnchor anchor;
+ ClientAnchorDetail rowClientAnchorDetail;
+ ClientAnchorDetail colClientAnchorDetail;
+ int imageType;
// Validate the resizeBehaviour parameter.
if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&
private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber,
double reqImageWidthMM, int resizeBehaviour) {
- double colWidthMM = 0.0D;
- double colCoordinatesPerMM = 0.0D;
- int pictureWidthCoordinates = 0;
+ double colWidthMM;
+ double colCoordinatesPerMM;
+ int pictureWidthCoordinates;
ClientAnchorDetail colClientAnchorDetail = null;
// Get the colum's width in millimetres
*/
private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber,
double reqImageHeightMM, int resizeBehaviour) {
- Row row = null;
- double rowHeightMM = 0.0D;
- double rowCoordinatesPerMM = 0.0D;
- int pictureHeightCoordinates = 0;
+ Row row;
+ double rowHeightMM;
+ double rowCoordinatesPerMM;
+ int pictureHeightCoordinates;
ClientAnchorDetail rowClientAnchorDetail = null;
// Get the row and it's height
private ClientAnchorDetail calculateColumnLocation(Sheet sheet,
int startingColumn,
double reqImageWidthMM) {
- ClientAnchorDetail anchorDetail = null;
+ ClientAnchorDetail anchorDetail;
double totalWidthMM = 0.0D;
double colWidthMM = 0.0D;
- double overlapMM = 0.0D;
- double coordinatePositionsPerMM = 0.0D;
+ double overlapMM;
+ double coordinatePositionsPerMM;
int toColumn = startingColumn;
- int inset = 0;
+ int inset;
// Calculate how many columns the image will have to
// span in order to be presented at the required size.
*/
private ClientAnchorDetail calculateRowLocation(Sheet sheet,
int startingRow, double reqImageHeightMM) {
- ClientAnchorDetail clientAnchorDetail = null;
- Row row = null;
+ ClientAnchorDetail clientAnchorDetail;
+ Row row;
double rowHeightMM = 0.0D;
double totalRowHeightMM = 0.0D;
- double overlapMM = 0.0D;
- double rowCoordinatesPerMM = 0.0D;
+ double overlapMM;
+ double rowCoordinatesPerMM;
int toRow = startingRow;
- int inset = 0;
+ int inset;
// Step through the rows in the sheet and accumulate a total of their
// heights.
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
- String imageFile = null;
- String outputFile = null;
- FileOutputStream fos = null;
- Workbook workbook = null;
- Sheet sheet = null;
+ String imageFile;
+ String outputFile;
+ FileOutputStream fos;
+ Workbook workbook;
+ Sheet sheet;
if(args.length < 2){
System.err.println("Usage: AddDimensionedImage imageFile outputFile");
/**
* pixel units to excel width units(units of 1/256th of a character width)
- * @param pxs
- * @return
*/
public static short pixel2WidthUnits(int pxs) {
short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR *
/**
* excel width units(units of 1/256th of a character width) to pixel
* units.
- *
- * @param widthUnits
- * @return
*/
public static int widthUnits2Pixel(short widthUnits) {
int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR)
* generates a sample workbook with conditional formatting,
* and prints out a summary of applied formats for one sheet
* @param args pass "-xls" to generate an HSSF workbook, default is XSSF
- * @throws IOException
*/
public static void main(String[] args) throws IOException {
Workbook wb;
/**
* 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.
- * @param wb
- * @param sheetName
*/
static void evaluateRules(Workbook wb, String sheetName) {
final WorkbookEvaluatorProvider wbEvalProv = (WorkbookEvaluatorProvider) wb.getCreationHelper().createFormulaEvaluator();
IllegalArgumentException, InvalidFormatException {
File source = new File(strSource);
File destination = new File(strDestination);
- File[] filesList = null;
- String destinationFilename = null;
+ File[] filesList;
+ String destinationFilename;
// Check that the source file/folder exists.
if(!source.exists()) {
* a CSV file.
*/
private void convertToCSV() {
- Sheet sheet = null;
- Row row = null;
- int lastRowNum = 0;
+ Sheet sheet;
+ Row row;
+ int lastRowNum;
this.csvData = new ArrayList<>();
System.out.println("Converting files contents to CSV format.");
*/
private void saveCSVFile(File file)
throws FileNotFoundException, IOException {
- FileWriter fw = null;
+ FileWriter fw;
BufferedWriter bw = null;
- ArrayList<String> line = null;
- StringBuffer buffer = null;
- String csvLineElement = null;
+ ArrayList<String> line;
+ StringBuffer buffer;
+ String csvLineElement;
try {
System.out.println("Saving the CSV file [" + file.getName() + "]");
* an Excel workbook.
*/
private void rowToCSV(Row row) {
- Cell cell = null;
- int lastCellNum = 0;
+ Cell cell;
+ int lastCellNum;
ArrayList<String> csvLine = new ArrayList<>();
// Check to ensure that a row was recovered from the sheet as it is
* speech mark characters correctly escaped.
*/
private String escapeEmbeddedCharacters(String field) {
- StringBuffer buffer = null;
+ StringBuffer buffer;
// If the fields contents should be formatted to confrom with Excel's
// convention....
// with matching names but different extensions - Test.xls and Test.xlsx
// for example - then the CSV file generated from one will overwrite
// that generated from the other.
- ToCSV converter = null;
+ ToCSV converter;
boolean converted = true;
long startTime = System.currentTimeMillis();
try {
style = wb.getCellStyleAt((short) 0);
}
StringBuilder sb = new StringBuilder();
- Formatter fmt = new Formatter(sb);
- try {
+ try (Formatter fmt = new Formatter(sb)) {
fmt.format("style_%02x", style.getIndex());
return fmt.toString();
- } finally {
- fmt.close();
}
}
/**
* 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
* <br>special keys:
* <br>{@link #IDX_HEADER_COL_WIDTH} - width of the header column
* <br>{@link #IDX_TABLE_WIDTH} - width of the entire table
*/
private Map<Integer, Integer> computeWidths(Sheet sheet) {
- Map<Integer, Integer> ret = new TreeMap<Integer, Integer>();
+ Map<Integer, Integer> ret = new TreeMap<>();
int tableWidth = 0;
ensureColumnBounds(sheet);
package org.apache.poi.xssf.eventusermodel.examples;
import java.io.FileInputStream;
-import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.crypt.examples.EncryptionUtils;
@Test
public void testImportFromXML() throws IOException, XPathExpressionException, SAXException{
-
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx");
- try {
- String name = "name";
- String teacher = "teacher";
- String tutor = "tutor";
- String cdl = "cdl";
- String duration = "duration";
- String topic = "topic";
- String project = "project";
- String credits = "credits";
-
- String testXML = "<CORSO>"+
- "<NOME>"+name+"</NOME>"+
- "<DOCENTE>"+teacher+"</DOCENTE>"+
- "<TUTOR>"+tutor+"</TUTOR>"+
- "<CDL>"+cdl+"</CDL>"+
- "<DURATA>"+duration+"</DURATA>"+
- "<ARGOMENTO>"+topic+"</ARGOMENTO>"+
- "<PROGETTO>"+project+"</PROGETTO>"+
- "<CREDITI>"+credits+"</CREDITI>"+
- "</CORSO>\u0000";
-
- XSSFMap map = wb.getMapInfo().getXSSFMapByName("CORSO_mapping");
- assertNotNull(map);
- XSSFImportFromXML importer = new XSSFImportFromXML(map);
-
- importer.importFromXML(testXML);
-
- XSSFSheet sheet=wb.getSheetAt(0);
-
- XSSFRow row = sheet.getRow(0);
- assertTrue(row.getCell(0).getStringCellValue().equals(name));
- assertTrue(row.getCell(1).getStringCellValue().equals(teacher));
- assertTrue(row.getCell(2).getStringCellValue().equals(tutor));
- assertTrue(row.getCell(3).getStringCellValue().equals(cdl));
- assertTrue(row.getCell(4).getStringCellValue().equals(duration));
- assertTrue(row.getCell(5).getStringCellValue().equals(topic));
- assertTrue(row.getCell(6).getStringCellValue().equals(project));
- assertTrue(row.getCell(7).getStringCellValue().equals(credits));
- } finally {
- wb.close();
- }
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx")) {
+ String name = "name";
+ String teacher = "teacher";
+ String tutor = "tutor";
+ String cdl = "cdl";
+ String duration = "duration";
+ String topic = "topic";
+ String project = "project";
+ String credits = "credits";
+
+ String testXML = "<CORSO>" +
+ "<NOME>" + name + "</NOME>" +
+ "<DOCENTE>" + teacher + "</DOCENTE>" +
+ "<TUTOR>" + tutor + "</TUTOR>" +
+ "<CDL>" + cdl + "</CDL>" +
+ "<DURATA>" + duration + "</DURATA>" +
+ "<ARGOMENTO>" + topic + "</ARGOMENTO>" +
+ "<PROGETTO>" + project + "</PROGETTO>" +
+ "<CREDITI>" + credits + "</CREDITI>" +
+ "</CORSO>\u0000";
+
+ XSSFMap map = wb.getMapInfo().getXSSFMapByName("CORSO_mapping");
+ assertNotNull(map);
+ XSSFImportFromXML importer = new XSSFImportFromXML(map);
+
+ importer.importFromXML(testXML);
+
+ XSSFSheet sheet = wb.getSheetAt(0);
+
+ XSSFRow row = sheet.getRow(0);
+ assertTrue(row.getCell(0).getStringCellValue().equals(name));
+ assertTrue(row.getCell(1).getStringCellValue().equals(teacher));
+ assertTrue(row.getCell(2).getStringCellValue().equals(tutor));
+ assertTrue(row.getCell(3).getStringCellValue().equals(cdl));
+ assertTrue(row.getCell(4).getStringCellValue().equals(duration));
+ assertTrue(row.getCell(5).getStringCellValue().equals(topic));
+ assertTrue(row.getCell(6).getStringCellValue().equals(project));
+ assertTrue(row.getCell(7).getStringCellValue().equals(credits));
+ }
}
@Test(timeout=60000)
public void testMultiTable() throws IOException, XPathExpressionException, SAXException{
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx");
- try {
- String cellC6 = "c6";
- String cellC7 = "c7";
- String cellC8 = "c8";
- String cellC9 = "c9";
-
- String testXML = "<ns1:MapInfo xmlns:ns1=\""+NS_SPREADSHEETML+"\" SelectionNamespaces=\"\">" +
- "<ns1:Schema ID=\""+cellC6+"\" SchemaRef=\"a\" />"+
- "<ns1:Schema ID=\""+cellC7+"\" SchemaRef=\"b\" />"+
- "<ns1:Schema ID=\""+cellC8+"\" SchemaRef=\"c\" />"+
- "<ns1:Schema ID=\""+cellC9+"\" SchemaRef=\"d\" />";
-
- for(int i = 10; i< 10010; i++){
- testXML += "<ns1:Schema ID=\"c"+i+"\" SchemaRef=\"d\" />";
- }
-
- testXML += "<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";
-
- XSSFMap map = wb.getMapInfo().getXSSFMapByName("MapInfo_mapping");
- assertNotNull(map);
- XSSFImportFromXML importer = new XSSFImportFromXML(map);
-
- 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();
- }
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) {
+ String cellC6 = "c6";
+ String cellC7 = "c7";
+ String cellC8 = "c8";
+ String cellC9 = "c9";
+
+ StringBuilder testXML = new StringBuilder("<ns1:MapInfo xmlns:ns1=\"" + NS_SPREADSHEETML + "\" SelectionNamespaces=\"\">" +
+ "<ns1:Schema ID=\"" + cellC6 + "\" SchemaRef=\"a\" />" +
+ "<ns1:Schema ID=\"" + cellC7 + "\" SchemaRef=\"b\" />" +
+ "<ns1:Schema ID=\"" + cellC8 + "\" SchemaRef=\"c\" />" +
+ "<ns1:Schema ID=\"" + cellC9 + "\" SchemaRef=\"d\" />");
+
+ for (int i = 10; i < 10010; i++) {
+ testXML.append("<ns1:Schema ID=\"c").append(i).append("\" 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");
+
+ XSSFMap map = wb.getMapInfo().getXSSFMapByName("MapInfo_mapping");
+ assertNotNull(map);
+ XSSFImportFromXML importer = new XSSFImportFromXML(map);
+
+ importer.importFromXML(testXML.toString());
+
+ //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());
+ }
}
@Test
public void testSingleAttributeCellWithNamespace() throws IOException, XPathExpressionException, SAXException{
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx");
- try {
- int id = 1;
- String displayName = "dispName";
- String ref="19";
- int count = 21;
-
- String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>"+
- "<ns1:table xmlns:ns1=\""+NS_SPREADSHEETML+"\" id=\""+id+"\" displayName=\""+displayName+"\" ref=\""+ref+"\">"+
- "<ns1:tableColumns count=\""+count+"\" />"+
- "</ns1:table>\u0000";
- XSSFMap map = wb.getMapInfo().getXSSFMapByName("table_mapping");
- assertNotNull(map);
- XSSFImportFromXML importer = new XSSFImportFromXML(map);
- importer.importFromXML(testXML);
-
- //Check for Schema element
- XSSFSheet sheet=wb.getSheetAt(0);
-
- assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0);
- assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue());
- assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue());
- assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0);
- } finally {
- wb.close();
- }
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx")) {
+ int id = 1;
+ String displayName = "dispName";
+ String ref = "19";
+ int count = 21;
+
+ String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" +
+ "<ns1:table xmlns:ns1=\"" + NS_SPREADSHEETML + "\" id=\"" + id + "\" displayName=\"" + displayName + "\" ref=\"" + ref + "\">" +
+ "<ns1:tableColumns count=\"" + count + "\" />" +
+ "</ns1:table>\u0000";
+ XSSFMap map = wb.getMapInfo().getXSSFMapByName("table_mapping");
+ assertNotNull(map);
+ XSSFImportFromXML importer = new XSSFImportFromXML(map);
+ importer.importFromXML(testXML);
+
+ //Check for Schema element
+ XSSFSheet sheet = wb.getSheetAt(0);
+
+ assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0);
+ assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue());
+ assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue());
+ assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0);
+ }
}
@Test
public void testOptionalFields_Bugzilla_55864() throws IOException, XPathExpressionException, SAXException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx");
- try {
- String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
- "<PersonInfoRoot>" +
- "<PersonData>" +
- "<FirstName>Albert</FirstName>" +
- "<LastName>Einstein</LastName>" +
- "<BirthDate>1879-03-14</BirthDate>" +
- "</PersonData>" +
- "</PersonInfoRoot>";
-
- XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map");
- assertNotNull(map);
- XSSFImportFromXML importer = new XSSFImportFromXML(map);
-
- importer.importFromXML(testXML);
-
- XSSFSheet sheet=wb.getSheetAt(0);
-
- XSSFRow rowHeadings = sheet.getRow(0);
- XSSFRow rowData = sheet.getRow(1);
-
- assertEquals("FirstName", rowHeadings.getCell(0).getStringCellValue());
- assertEquals("Albert", rowData.getCell(0).getStringCellValue());
-
- assertEquals("LastName", rowHeadings.getCell(1).getStringCellValue());
- assertEquals("Einstein", rowData.getCell(1).getStringCellValue());
-
- assertEquals("BirthDate", rowHeadings.getCell(2).getStringCellValue());
- assertEquals("1879-03-14", rowData.getCell(2).getStringCellValue());
-
- // Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx
- assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue());
- assertNull("", rowData.getCell(3));
- } finally {
- wb.close();
- }
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx")) {
+ String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
+ "<PersonInfoRoot>" +
+ "<PersonData>" +
+ "<FirstName>Albert</FirstName>" +
+ "<LastName>Einstein</LastName>" +
+ "<BirthDate>1879-03-14</BirthDate>" +
+ "</PersonData>" +
+ "</PersonInfoRoot>";
+
+ XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map");
+ assertNotNull(map);
+ XSSFImportFromXML importer = new XSSFImportFromXML(map);
+
+ importer.importFromXML(testXML);
+
+ XSSFSheet sheet = wb.getSheetAt(0);
+
+ XSSFRow rowHeadings = sheet.getRow(0);
+ XSSFRow rowData = sheet.getRow(1);
+
+ assertEquals("FirstName", rowHeadings.getCell(0).getStringCellValue());
+ assertEquals("Albert", rowData.getCell(0).getStringCellValue());
+
+ assertEquals("LastName", rowHeadings.getCell(1).getStringCellValue());
+ assertEquals("Einstein", rowData.getCell(1).getStringCellValue());
+
+ assertEquals("BirthDate", rowHeadings.getCell(2).getStringCellValue());
+ assertEquals("1879-03-14", rowData.getCell(2).getStringCellValue());
+
+ // Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx
+ assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue());
+ assertNull("", rowData.getCell(3));
+ }
}
@Test
@Test
public void getCellStyleAt() throws IOException{
- XSSFWorkbook workbook = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook workbook = new XSSFWorkbook()) {
short i = 0;
//get default style
CellStyle cellStyleAt = workbook.getCellStyleAt(i);
font.setFontName("Verdana");
customStyle.setFont(font);
int x = styleSource.putStyle(customStyle);
- cellStyleAt = workbook.getCellStyleAt((short)x);
+ cellStyleAt = workbook.getCellStyleAt((short) x);
assertNotNull(cellStyleAt);
- } finally {
- workbook.close();
- }
+ }
}
@Test
public void getFontAt() throws IOException{
- XSSFWorkbook workbook = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook workbook = new XSSFWorkbook()) {
StylesTable styleSource = workbook.getStylesSource();
short i = 0;
//get default font
XSSFFont customFont = new XSSFFont();
customFont.setItalic(true);
int x = styleSource.putFont(customFont);
- fontAt = workbook.getFontAt((short)x);
+ fontAt = workbook.getFontAt((short) x);
assertNotNull(fontAt);
- } finally {
- workbook.close();
- }
+ }
}
@Test
public void getNumCellStyles() throws IOException{
- XSSFWorkbook workbook = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook workbook = new XSSFWorkbook()) {
//get default cellStyles
assertEquals(1, workbook.getNumCellStyles());
- } finally {
- workbook.close();
- }
+ }
}
@Test
@Test
public void incrementSheetId() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- try {
- int sheetId = (int)wb.createSheet().sheet.getSheetId();
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ int sheetId = (int) wb.createSheet().sheet.getSheetId();
assertEquals(1, sheetId);
- sheetId = (int)wb.createSheet().sheet.getSheetId();
+ sheetId = (int) wb.createSheet().sheet.getSheetId();
assertEquals(2, sheetId);
//test file with gaps in the sheetId sequence
- XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm");
- try {
- int lastSheetId = (int)wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId();
- sheetId = (int)wbBack.createSheet().sheet.getSheetId();
- assertEquals(lastSheetId+1, sheetId);
- } finally {
- wbBack.close();
+ try (XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm")) {
+ int lastSheetId = (int) wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId();
+ sheetId = (int) wbBack.createSheet().sheet.getSheetId();
+ assertEquals(lastSheetId + 1, sheetId);
}
- } finally {
- wb.close();
}
}
/**
* Test setting of core properties such as Title and Author
- * @throws IOException
*/
@Test
public void workbookProperties() throws IOException {
- XSSFWorkbook workbook = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook workbook = new XSSFWorkbook()) {
POIXMLProperties props = workbook.getProperties();
assertNotNull(props);
//the Application property must be set for new workbooks, see Bugzilla #47559
assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().getValue());
assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().getValue());
wbBack.close();
- } finally {
- workbook.close();
}
}
/**
* When deleting a sheet make sure that we adjust sheet indices of named ranges
*/
+ @SuppressWarnings("deprecation")
@Test
public void bug47737() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx");
@Test
public void recalcId() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
assertFalse(wb.getForceFormulaRecalculation());
CTWorkbook ctWorkbook = wb.getCTWorkbook();
assertFalse(ctWorkbook.isSetCalcPr());
calcPr.setCalcMode(STCalcMode.MANUAL);
wb.setForceFormulaRecalculation(true);
assertEquals(STCalcMode.AUTO, calcPr.getCalcMode());
- } finally {
- wb.close();
}
}
accessWorkbook(workbook);
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- try {
+ try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
workbook.write(stream);
- } finally {
- stream.close();
}
accessWorkbook(workbook);
@Test
public void bug51158a() throws IOException {
// create a workbook
- final XSSFWorkbook workbook = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook workbook = new XSSFWorkbook()) {
workbook.createSheet("Test Sheet");
XSSFSheet sheetBack = workbook.getSheetAt(0);
sheetBack.commit();
// 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();
}
String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()), "UTF-8");
assertEquals(1, countMatches(str, "<worksheet"));
- } finally {
- workbook.close();
}
}
@Test
public void testAddPivotCache() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
CTWorkbook ctWb = wb.getCTWorkbook();
CTPivotCache pivotCache = wb.addPivotCache("0");
//Ensures that pivotCaches is initiated
assertTrue(ctWb.isSetPivotCaches());
assertSame(pivotCache, ctWb.getPivotCaches().getPivotCacheArray(0));
assertEquals("0", pivotCache.getId());
- } finally {
- wb.close();
}
}
public void testLoadWorkbookWithPivotTable() throws Exception {
File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx");
- XSSFWorkbook wb = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
setPivotData(wb);
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
- } finally {
- wb.close();
}
- XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file);
- try {
+ try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) {
assertTrue(wb2.getPivotTables().size() == 1);
- } finally {
- wb2.close();
}
assertTrue(file.delete());
public void testAddPivotTableToWorkbookWithLoadedPivotTable() throws Exception {
File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx");
- XSSFWorkbook wb = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
setPivotData(wb);
- FileOutputStream fileOut = new FileOutputStream(file);
- try {
+ try (FileOutputStream fileOut = new FileOutputStream(file)) {
wb.write(fileOut);
- } finally {
- fileOut.close();
}
- } finally {
- wb.close();
}
- XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file);
- try {
+ try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) {
setPivotData(wb2);
assertTrue(wb2.getPivotTables().size() == 2);
- } finally {
- wb2.close();
}
assertTrue(file.delete());
@Test
public void testSetFirstVisibleTab_57373() throws IOException {
- Workbook wb = new XSSFWorkbook();
- try {
- /*Sheet sheet1 =*/ wb.createSheet();
+ try (Workbook wb = new XSSFWorkbook()) {
+ /*Sheet sheet1 =*/
+ wb.createSheet();
Sheet sheet2 = wb.createSheet();
int idx2 = wb.getSheetIndex(sheet2);
Sheet sheet3 = wb.createSheet();
int idx3 = wb.getSheetIndex(sheet3);
// add many sheets so "first visible" is relevant
- for(int i = 0; i < 30;i++) {
+ for (int i = 0; i < 30; i++) {
wb.createSheet();
}
Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
sheet2 = wbBack.getSheetAt(idx2);
+ assertNotNull(sheet2);
sheet3 = wbBack.getSheetAt(idx3);
+ assertNotNull(sheet3);
assertEquals(idx2, wb.getFirstVisibleTab());
assertEquals(idx3, wb.getActiveSheetIndex());
wbBack.close();
- } finally {
- wb.close();
}
}
* In order to make code for looping over sheets in workbooks standard, regardless
* of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously
* available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator
- * have been replaced with Iterator<Sheet> {@link #iterator} and
- * Iterator<Sheet> {@link #sheetIterator}. This makes iterating over sheets in a workbook
+ * have been replaced with Iterator<Sheet> {@link Sheet#iterator} and
+ * 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.
*
* Note: this breaks backwards compatibility! Existing codebases will need to
wb.close();
}
+ @SuppressWarnings("deprecation")
@Test
public void testRemoveSheet() throws IOException {
// Test removing a sheet maintains the named ranges correctly