]> source.dussan.org Git - poi.git/commitdiff
Adjust many examples for Java 8: try-with-resource, multi-catch and other code cleanup.
authorDominik Stadler <centic@apache.org>
Fri, 22 Sep 2017 21:16:09 +0000 (21:16 +0000)
committerDominik Stadler <centic@apache.org>
Fri, 22 Sep 2017 21:16:09 +0000 (21:16 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1809354 13f79535-47bb-0310-9956-ffa450edef68

98 files changed:
src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java
src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java
src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java
src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java
src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java
src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java
src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java
src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java
src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java
src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java
src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java
src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java
src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java
src/examples/src/org/apache/poi/hslf/examples/TableDemo.java
src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/Alignment.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/BigExample.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/EmbeddedObjects.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/EventExample.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/InCellLists.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/NewSheet.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/Outlines.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/ReadWriteWorkbook.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/ZoomSheet.java
src/examples/src/org/apache/poi/hwpf/Word2Forrest.java
src/examples/src/org/apache/poi/ss/examples/AligningCells.java
src/examples/src/org/apache/poi/ss/examples/CalendarDemo.java
src/examples/src/org/apache/poi/ss/examples/CellStyleDetails.java
src/examples/src/org/apache/poi/ss/examples/formula/SettingExternalFunction.java
src/examples/src/org/apache/poi/ss/examples/formula/UserDefinedFunctionExample.java
src/examples/src/org/apache/poi/xslf/usermodel/DataExtraction.java
src/examples/src/org/apache/poi/xslf/usermodel/MergePresentations.java
src/examples/src/org/apache/poi/xslf/usermodel/PieChartDemo.java
src/examples/src/org/apache/poi/xslf/usermodel/Tutorial1.java
src/examples/src/org/apache/poi/xslf/usermodel/Tutorial2.java
src/examples/src/org/apache/poi/xslf/usermodel/Tutorial3.java
src/examples/src/org/apache/poi/xslf/usermodel/Tutorial4.java
src/examples/src/org/apache/poi/xslf/usermodel/Tutorial5.java
src/examples/src/org/apache/poi/xslf/usermodel/Tutorial6.java
src/examples/src/org/apache/poi/xslf/usermodel/Tutorial7.java
src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step1.java
src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step2.java
src/examples/src/org/apache/poi/xssf/eventusermodel/examples/FromHowTo.java
src/examples/src/org/apache/poi/xssf/streaming/examples/Outlining.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/AligningCells.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/CalendarDemo.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/CellComments.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateCell.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/CreatePivotTable.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/CreatePivotTable2.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateTable.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/CustomXMLMapping.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/FillsAndColors.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/FitSheetToOnePage.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/HeadersAndFooters.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/HyperlinkExample.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/MergingCells.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/NewLinesInCells.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/Outlining.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/ScatterChart.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/SelectedSheet.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/ShiftRows.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/SplitAndFreezePanes.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkbookProperties.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithBorders.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithFonts.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPageSetup.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPictures.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithRichText.java
src/examples/src/org/apache/poi/xwpf/usermodel/examples/BetterHeaderFooterExample.java
src/examples/src/org/apache/poi/xwpf/usermodel/examples/HeaderFooterTable.java
src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java
src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocumentWithHeader.java
src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleImages.java
src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleTable.java

index 0b7a1fcab6f83974fc62edea48b94ec7c2019fd7..aaeea354abbddd0140069a3025c48825ce2ba9fd 100644 (file)
@@ -69,7 +69,7 @@ public class OOXMLPasswordsTry implements Closeable {
         
         // Try each password in turn, reporting progress
         String valid = null;
-        String password = null;
+        String password;
         while ((password = r.readLine()) != null) {
             if (isValid(password)) {
                 valid = password;
index cfc064c120c474cd31a5e2b09907b3d2e60df075..d2226f52b6e3e3f36ba8eb496f4e6dffb6974515 100644 (file)
@@ -123,9 +123,9 @@ public class CopyCompare
         final CopyFile cf = new CopyFile(copyFileName);
         r.registerListener(cf);
         r.setNotifyEmptyDirectories(true);
-        FileInputStream fis = new FileInputStream(originalFileName);
-        r.read(fis);
-        fis.close();
+        try (FileInputStream fis = new FileInputStream(originalFileName)) {
+            r.read(fis);
+        }
         
         /* Write the new POIFS to disk. */
         cf.close();
@@ -183,7 +183,7 @@ public class CopyCompare
         for (final Entry e1 : d1) {
             final String n1 = e1.getName();
             if (!d2.hasEntry(n1)) {
-                msg.append("Document \"" + n1 + "\" exists only in the source.\n");
+                msg.append("Document \"").append(n1).append("\" exists only in the source.\n");
                 equal = false;
                 break;
             }
@@ -194,8 +194,7 @@ public class CopyCompare
             } else if (e1.isDocumentEntry() && e2.isDocumentEntry()) {
                 equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg);
             } else {
-                msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " +
-                           "document while the other one is a directory.\n");
+                msg.append("One of \"").append(e1).append("\" and \"").append(e2).append("\" is a ").append("document while the other one is a directory.\n");
                 equal = false;
             }
         }
@@ -208,8 +207,7 @@ public class CopyCompare
             try {
                 e1 = d1.getEntry(n2);
             } catch (FileNotFoundException ex) {
-                msg.append("Document \"" + e2 + "\" exitsts, document \"" +
-                           e1 + "\" does not.\n");
+                msg.append("Document \"").append(e2).append("\" exitsts, document \"").append(e1).append("\" does not.\n");
                 equal = false;
                 break;
             }
@@ -243,11 +241,9 @@ public class CopyCompare
     throws NoPropertySetStreamException, MarkUnsupportedException,
            UnsupportedEncodingException, IOException
     {
-        final DocumentInputStream dis1 = new DocumentInputStream(d1);
-        final DocumentInputStream dis2 = new DocumentInputStream(d2);
-        try {
+        try (DocumentInputStream dis1 = new DocumentInputStream(d1); DocumentInputStream dis2 = new DocumentInputStream(d2)) {
             if (PropertySet.isPropertySetStream(dis1) &&
-                PropertySet.isPropertySetStream(dis2)) {
+                    PropertySet.isPropertySetStream(dis2)) {
                 final PropertySet ps1 = PropertySetFactory.create(dis1);
                 final PropertySet ps2 = PropertySetFactory.create(dis2);
                 if (!ps1.equals(ps2)) {
@@ -265,9 +261,6 @@ public class CopyCompare
                     }
                 } while (i1 > -1);
             }
-        } finally {
-            dis2.close();
-            dis1.close();
         }
         return true;
     }
@@ -339,11 +332,7 @@ public class CopyCompare
                      * copy it unmodified to the destination POIFS. */
                     copy(poiFs, path, name, stream);
                 }
-            } catch (MarkUnsupportedException ex) {
-                t = ex;
-            } catch (IOException ex) {
-                t = ex;
-            } catch (WritingNotSupportedException ex) {
+            } catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) {
                 t = ex;
             }
 
index 18054441004995512ac995448fd59f8a7174d6de..d4f38a1d135e1ec0b7a6153bc5f7820371e554a4 100644 (file)
@@ -57,7 +57,7 @@ public class ReadTitle
         @Override
         public void processPOIFSReaderEvent(final POIFSReaderEvent event)
         {
-            SummaryInformation si = null;
+            SummaryInformation si;
             try
             {
                 si = (SummaryInformation)
index 6fa15f9dc12aae609155d439f40ce4877da3af80..b4a333160457e42accac404bebfb5a1b327d67b5 100644 (file)
@@ -187,11 +187,7 @@ public class WriteAuthorAndTitle
                      * copy it unmodified to the destination POIFS. */
                     copy(poiFs, event.getPath(), event.getName(), stream);
                 }
-            } catch (MarkUnsupportedException ex) {
-                t = ex;
-            } catch (IOException ex) {
-                t = ex;
-            } catch (WritingNotSupportedException ex) {
+            } catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) {
                 t = ex;
             }
 
index 464f958b38f298fa4f25a9a08e61acec41070c59..f6d711698c4655259d1d722c5b9ea97073840b3e 100644 (file)
@@ -79,23 +79,21 @@ public class WriteTitle
         ms.setProperty(p);
 
         /* Create the POI file system the property set is to be written to. */
-        final POIFSFileSystem poiFs = new POIFSFileSystem();
-
-        /* For writing the property set into a POI file system it has to be
-         * handed over to the POIFS.createDocument() method as an input stream
-         * which produces the bytes making out the property set stream. */
-        final InputStream is = mps.toInputStream();
-
-        /* Create the summary information property set in the POI file
-         * system. It is given the default name most (if not all) summary
-         * information property sets have. */
-        poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);
-
-        /* Write the whole POI file system to a disk file. */
-        FileOutputStream fos = new FileOutputStream(fileName);
-        poiFs.writeFilesystem(fos);
-        fos.close();
-        poiFs.close();
+        try (final POIFSFileSystem poiFs = new POIFSFileSystem()) {
+            /* For writing the property set into a POI file system it has to be
+             * handed over to the POIFS.createDocument() method as an input stream
+             * which produces the bytes making out the property set stream. */
+            final InputStream is = mps.toInputStream();
+
+            /* Create the summary information property set in the POI file
+             * system. It is given the default name most (if not all) summary
+             * information property sets have. */
+            poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);
+
+            /* Write the whole POI file system to a disk file. */
+            try (FileOutputStream fos = new FileOutputStream(fileName)) {
+                poiFs.writeFilesystem(fos);
+            }
+        }
     }
-
 }
index 578c3a679950dbb18cdec54454d491664b1bfd24..d25282897dbc0ab4c81c3fb4b70b4ef4c1147135 100644 (file)
@@ -51,28 +51,28 @@ import org.apache.poi.sl.usermodel.VerticalAlignment;
 public final class ApacheconEU08 {
 
     public static void main(String[] args) throws IOException {
-        SlideShow<?,?> ppt = new HSLFSlideShow();
-        // SlideShow<?,?> ppt = new XMLSlideShow();
-        ppt.setPageSize(new Dimension(720, 540));
-
-        slide1(ppt);
-        slide2(ppt);
-        slide3(ppt);
-        slide4(ppt);
-        slide5(ppt);
-        slide6(ppt);
-        slide7(ppt);
-        slide8(ppt);
-        slide9(ppt);
-        slide10(ppt);
-        slide11(ppt);
-        slide12(ppt);
-
-        String ext = ppt.getClass().getName().contains("HSLF") ? "ppt" : "pptx";
-        FileOutputStream out = new FileOutputStream("apachecon_eu_08."+ext);
-        ppt.write(out);
-        out.close();
-        ppt.close();
+        try (SlideShow<?,?> ppt = new HSLFSlideShow()) {
+            // SlideShow<?,?> ppt = new XMLSlideShow();
+            ppt.setPageSize(new Dimension(720, 540));
+
+            slide1(ppt);
+            slide2(ppt);
+            slide3(ppt);
+            slide4(ppt);
+            slide5(ppt);
+            slide6(ppt);
+            slide7(ppt);
+            slide8(ppt);
+            slide9(ppt);
+            slide10(ppt);
+            slide11(ppt);
+            slide12(ppt);
+
+            String ext = ppt.getClass().getName().contains("HSLF") ? "ppt" : "pptx";
+            try (FileOutputStream out = new FileOutputStream("apachecon_eu_08." + ext)) {
+                ppt.write(out);
+            }
+        }
     }
 
     public static void slide1(SlideShow<?,?> ppt) throws IOException {
index 53378a17ee25264c6827c85f10d28391c8b4af2b..dc814f35b5c7f8c519bedcd6bcdcd2a8e603e102 100644 (file)
@@ -32,11 +32,9 @@ import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
 public final class BulletsDemo {
 
     public static void main(String[] args) throws IOException {
-
-        HSLFSlideShow ppt = new HSLFSlideShow();
-        try {
+        try (HSLFSlideShow ppt = new HSLFSlideShow()) {
             HSLFSlide slide = ppt.createSlide();
-    
+
             HSLFTextBox shape = new HSLFTextBox();
             HSLFTextParagraph rt = shape.getTextParagraphs().get(0);
             rt.getTextRuns().get(0).setFontSize(42d);
@@ -46,19 +44,17 @@ public final class BulletsDemo {
             rt.setBulletChar('\u263A'); //bullet character
             shape.setText(
                     "January\r" +
-                    "February\r" +
-                    "March\r" +
-                    "April");
+                            "February\r" +
+                            "March\r" +
+                            "April");
             slide.addShape(shape);
-    
+
             shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300));  //position of the text box in the slide
             slide.addShape(shape);
-    
-            FileOutputStream out = new FileOutputStream("bullets.ppt");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("bullets.ppt")) {
+                ppt.write(out);
+            }
         }
    }
 }
index 9ae200f8b27a24772c00e90282acd5afa92cf49d..9227e79e52a21a39d5e6029caafaacf49bd87cc4 100644 (file)
@@ -32,35 +32,31 @@ import org.apache.poi.hslf.usermodel.HSLFTextBox;
 public abstract class CreateHyperlink {
     
     public static void main(String[] args) throws IOException {
-        HSLFSlideShow ppt = new HSLFSlideShow();
-
-        try {
+        try (HSLFSlideShow ppt = new HSLFSlideShow()) {
             HSLFSlide slideA = ppt.createSlide();
             ppt.createSlide();
             HSLFSlide slideC = ppt.createSlide();
-    
+
             // link to a URL
             HSLFTextBox textBox1 = slideA.createTextBox();
             textBox1.setText("Apache POI");
             textBox1.setAnchor(new Rectangle(100, 100, 200, 50));
-    
+
             HSLFHyperlink link1 = textBox1.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
             link1.linkToUrl("http://www.apache.org");
             link1.setLabel(textBox1.getText());
-    
+
             // link to another slide
             HSLFTextBox textBox2 = slideA.createTextBox();
             textBox2.setText("Go to slide #3");
             textBox2.setAnchor(new Rectangle(100, 300, 200, 50));
-    
+
             HSLFHyperlink link2 = textBox2.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
             link2.linkToSlide(slideC);
-    
-            FileOutputStream out = new FileOutputStream("hyperlink.ppt");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("hyperlink.ppt")) {
+                ppt.write(out);
+            }
         }
    }
 }
index ad71ceff6c572d38fd513aba2f5f0c03eff94d0b..3cc995d153d4a19b7ed46dc502764e6ce36078f8 100644 (file)
@@ -52,10 +52,10 @@ public final class DataExtraction {
 
         //extract all sound files embedded in this presentation
         HSLFSoundData[] sound = ppt.getSoundData();
-        for (int i = 0; i < sound.length; i++) {
-            String type = sound[i].getSoundType();  //*.wav
-            String name = sound[i].getSoundName();  //typically file name
-            byte[] data = sound[i].getData();       //raw bytes
+        for (HSLFSoundData aSound : sound) {
+            String type = aSound.getSoundType();  //*.wav
+            String name = aSound.getSoundName();  //typically file name
+            byte[] data = aSound.getData();       //raw bytes
 
             //save the sound  on disk
             FileOutputStream out = new FileOutputStream(name + type);
index c149a9d47d489e72a9f0bc2a26bc778705abb513..b8d84efc3625e99ea3f1a21eabef941dbcf30b5b 100644 (file)
@@ -39,36 +39,34 @@ public final class Graphics2DDemo {
      * A simple bar chart demo
      */
     public static void main(String[] args) throws Exception {
-        HSLFSlideShow ppt = new HSLFSlideShow();
-
-        try {
+        try (HSLFSlideShow ppt = new HSLFSlideShow()) {
             //bar chart data. The first value is the bar color, the second is the width
             Object[] def = new Object[]{
-                Color.yellow, 40,
-                Color.green, 60,
-                Color.gray, 30,
-                Color.red, 80,
+                    Color.yellow, 40,
+                    Color.green, 60,
+                    Color.gray, 30,
+                    Color.red, 80,
             };
-    
+
             HSLFSlide slide = ppt.createSlide();
-    
+
             HSLFGroupShape group = new HSLFGroupShape();
             //define position of the drawing in the slide
-            Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300);
+            Rectangle bounds = new Rectangle(200, 100, 350, 300);
             group.setAnchor(bounds);
-            group.setInteriorAnchor(new java.awt.Rectangle(0, 0, 100, 100));
+            group.setInteriorAnchor(new Rectangle(0, 0, 100, 100));
             slide.addShape(group);
             Graphics2D graphics = new PPGraphics2D(group);
-    
+
             //draw a simple bar graph
             int x = 10, y = 10;
             graphics.setFont(new Font("Arial", Font.BOLD, 10));
-            for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {
+            for (int i = 0, idx = 1; i < def.length; i += 2, idx++) {
                 graphics.setColor(Color.black);
-                int width = ((Integer)def[i+1]).intValue();
-                graphics.drawString("Q" + idx, x-5, y+10);
-                graphics.drawString(width + "%", x + width+3, y + 10);
-                graphics.setColor((Color)def[i]);
+                int width = ((Integer) def[i + 1]).intValue();
+                graphics.drawString("Q" + idx, x - 5, y + 10);
+                graphics.drawString(width + "%", x + width + 3, y + 10);
+                graphics.setColor((Color) def[i]);
                 graphics.fill(new Rectangle(x, y, width, 10));
                 y += 15;
             }
@@ -76,12 +74,10 @@ public final class Graphics2DDemo {
             graphics.setFont(new Font("Arial", Font.BOLD, 14));
             graphics.draw(group.getInteriorAnchor());
             graphics.drawString("Performance", x + 30, y + 10);
-    
-            FileOutputStream out = new FileOutputStream("hslf-graphics.ppt");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("hslf-graphics.ppt")) {
+                ppt.write(out);
+            }
         }
     }
 }
index cc86b760636102fcbbd06c25591d73bdbe04f041..8c9a743c6fd37aeadd393b72103ea45ff0da2577 100644 (file)
@@ -27,25 +27,21 @@ import org.apache.poi.hslf.usermodel.HSLFSlideShow;
  */
 public abstract class HeadersFootersDemo {
     public static void main(String[] args) throws IOException {
-        HSLFSlideShow ppt = new HSLFSlideShow();
-        
-        try {
+        try (HSLFSlideShow ppt = new HSLFSlideShow()) {
             HeadersFooters slideHeaders = ppt.getSlideHeadersFooters();
             slideHeaders.setFootersText("Created by POI-HSLF");
             slideHeaders.setSlideNumberVisible(true);
             slideHeaders.setDateTimeText("custom date time");
-    
+
             HeadersFooters notesHeaders = ppt.getNotesHeadersFooters();
             notesHeaders.setFootersText("My notes footers");
             notesHeaders.setHeaderText("My notes header");
-    
+
             ppt.createSlide();
-    
-            FileOutputStream out = new FileOutputStream("headers_footers.ppt");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("headers_footers.ppt")) {
+                ppt.write(out);
+            }
         }
     }
 
index 812429295a34be04cbe27fc22ba772a7ed3d6794..e0936de3f7c32e18c3e8e43e577a32ffaaf7ce5b 100644 (file)
@@ -37,8 +37,8 @@ import org.apache.poi.hslf.usermodel.HSLFTextRun;
 public final class Hyperlinks {
 
     public static void main(String[] args) throws Exception {
-        for (int i = 0; i < args.length; i++) {
-            FileInputStream is = new FileInputStream(args[i]);
+        for (String arg : args) {
+            FileInputStream is = new FileInputStream(arg);
             HSLFSlideShow ppt = new HSLFSlideShow(is);
             is.close();
 
@@ -64,7 +64,7 @@ public final class Hyperlinks {
                 System.out.println("- reading hyperlinks from the slide's shapes");
                 for (HSLFShape sh : slide.getShapes()) {
                     if (sh instanceof HSLFSimpleShape) {
-                        HSLFHyperlink link = ((HSLFSimpleShape)sh).getHyperlink();
+                        HSLFHyperlink link = ((HSLFSimpleShape) sh).getHyperlink();
                         if (link != null) {
                             System.out.println(toStr(link, null));
                         }
index ec0cec8dc1e99ada7e5801887152a0d5524b001a..112500d97f67746f6816d950e5edcf4666472df0 100644 (file)
@@ -30,23 +30,23 @@ import org.apache.poi.hslf.usermodel.HSLFSoundData;
  */
 public class SoundFinder {
     public static void main(String[] args) throws IOException {
-        FileInputStream fis = new FileInputStream(args[0]);
-        HSLFSlideShow ppt = new HSLFSlideShow(fis);
-        HSLFSoundData[] sounds = ppt.getSoundData();
+        try (FileInputStream fis = new FileInputStream(args[0])) {
+            try (HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
+                HSLFSoundData[] sounds = ppt.getSoundData();
 
-        for (HSLFSlide slide : ppt.getSlides()) {
-            for (HSLFShape shape : slide.getShapes()) {
-                int soundRef = getSoundReference(shape);
-                if(soundRef == -1) continue;
+                for (HSLFSlide slide : ppt.getSlides()) {
+                    for (HSLFShape shape : slide.getShapes()) {
+                        int soundRef = getSoundReference(shape);
+                        if (soundRef == -1) continue;
 
-                
-                System.out.println("Slide["+slide.getSlideNumber()+"], shape["+shape.getShapeId()+"], soundRef: "+soundRef);
-                System.out.println("  " + sounds[soundRef].getSoundName());
-                System.out.println("  " + sounds[soundRef].getSoundType());
+
+                        System.out.println("Slide[" + slide.getSlideNumber() + "], shape[" + shape.getShapeId() + "], soundRef: " + soundRef);
+                        System.out.println("  " + sounds[soundRef].getSoundName());
+                        System.out.println("  " + sounds[soundRef].getSoundType());
+                    }
+                }
             }
         }
-        ppt.close();
-        fis.close();
     }
 
     /**
index ab869dea628ac61262f50f4ffa5f110ffc9d03e6..da8464f586a3ae87053b6d33190125e590e5ab6a 100644 (file)
@@ -54,18 +54,14 @@ public final class TableDemo {
 
 
     public static void main(String[] args) throws Exception {
-        HSLFSlideShow ppt = new HSLFSlideShow();
-
-        try {
+        try (HSLFSlideShow ppt = new HSLFSlideShow()) {
             HSLFSlide slide = ppt.createSlide();
             create1stTable(slide);
             create2ndTable(slide);
-    
-            FileOutputStream out = new FileOutputStream("hslf-table.ppt");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("hslf-table.ppt")) {
+                ppt.write(out);
+            }
         }
     }
     
index 9eeba8ce53bb4cceca19a08a974839ed7acada1a..6c097df1065085e0d9b06e57d268dd2064d813ac 100644 (file)
@@ -157,12 +157,12 @@ public class Msg2txt {
                if(args.length <= 0) {
                        System.err.println("No files names provided");
                } else {
-                       for(int i = 0; i < args.length; i++) {
+                       for (String arg : args) {
                                try {
-                                       Msg2txt processor = new Msg2txt(args[i]);
+                                       Msg2txt processor = new Msg2txt(arg);
                                        processor.processMessage();
                                } catch (IOException e) {
-                                       System.err.println("Could not process "+args[i]+": "+e);
+                                       System.err.println("Could not process " + arg + ": " + e);
                                }
                        }
                }
index 84898383bec892a24d685f185b6cdd22fef2d765..61629d5c445dc0e37fcecd33280297593d666940 100644 (file)
@@ -251,10 +251,10 @@ public class AddDimensionedImage {
             String imageFile, double reqImageWidthMM, double reqImageHeightMM,
             int resizeBehaviour) throws FileNotFoundException, IOException,
                                                      IllegalArgumentException  {
-        HSSFClientAnchor anchor = null;
-        HSSFPatriarch patriarch = null;
-        ClientAnchorDetail rowClientAnchorDetail = null;
-        ClientAnchorDetail colClientAnchorDetail = null;
+        HSSFClientAnchor anchor;
+        HSSFPatriarch patriarch;
+        ClientAnchorDetail rowClientAnchorDetail;
+        ClientAnchorDetail colClientAnchorDetail;
 
         // Validate the resizeBehaviour parameter.
         if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&
@@ -334,9 +334,9 @@ public class AddDimensionedImage {
     private ClientAnchorDetail fitImageToColumns(HSSFSheet 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
@@ -417,21 +417,19 @@ public class AddDimensionedImage {
      */
     private ClientAnchorDetail fitImageToRows(HSSFSheet sheet, int rowNumber,
             double reqImageHeightMM, int resizeBehaviour) {
-        HSSFRow row = null;
-        double rowHeightMM = 0.0D;
-        double rowCoordinatesPerMM = 0.0D;
-        int pictureHeightCoordinates = 0;
+        double rowCoordinatesPerMM;
+        int pictureHeightCoordinates;
         ClientAnchorDetail rowClientAnchorDetail = null;
 
         // Get the row and it's height
-        row = sheet.getRow(rowNumber);
+        HSSFRow row = sheet.getRow(rowNumber);
         if(row == null) {
             // Create row if it does not exist.
             row = sheet.createRow(rowNumber);
         }
 
         // Get the row's height in millimetres
-        rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE;
+        double rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE;
 
         // Check that the row's height will accomodate the image at the required
         // dimensions. If the height of the row is LESS than the required height
@@ -494,13 +492,13 @@ public class AddDimensionedImage {
     private ClientAnchorDetail calculateColumnLocation(HSSFSheet 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.
@@ -593,14 +591,14 @@ public class AddDimensionedImage {
      */
     private ClientAnchorDetail calculateRowLocation(HSSFSheet sheet,
             int startingRow, double reqImageHeightMM) {
-        ClientAnchorDetail clientAnchorDetail = null;
-        HSSFRow row = null;
+        ClientAnchorDetail clientAnchorDetail;
+        HSSFRow 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.
@@ -672,10 +670,10 @@ public class AddDimensionedImage {
      *                             interrupted.
      */
     private byte[] imageToBytes(String imageFilename) throws IOException {
-        File imageFile = null;
+        File imageFile;
         FileInputStream fis = null;
-        ByteArrayOutputStream bos = null;
-        int read = 0;
+        ByteArrayOutputStream bos;
+        int read;
         try {
             imageFile = new File(imageFilename);
             fis = new FileInputStream(imageFile);
@@ -718,10 +716,10 @@ public class AddDimensionedImage {
      * @param args the command line arguments
      */
     public static void main(String[] args) {
-        String imageFile = null;
-        String outputFile = null;
+        String imageFile;
+        String outputFile;
         FileOutputStream fos = null;
-        HSSFSheet sheet = null;
+        HSSFSheet sheet;
         try {
             if(args.length < 2){
                 System.err.println("Usage: AddDimensionedImage imageFile outputFile");
@@ -730,25 +728,15 @@ public class AddDimensionedImage {
             imageFile = args[0];
             outputFile = args[1];
 
-            HSSFWorkbook workbook = new HSSFWorkbook();
-            try  {
+            try (HSSFWorkbook workbook = new HSSFWorkbook()) {
                 sheet = workbook.createSheet("Picture Test");
                 new AddDimensionedImage().addImageToSheet("A1", sheet,
                         imageFile, 125, 125,
                         AddDimensionedImage.EXPAND_ROW_AND_COLUMN);
                 fos = new FileOutputStream(outputFile);
                 workbook.write(fos);
-            } finally {
-                workbook.close();
             }
-        }
-        catch(FileNotFoundException fnfEx) {
-            System.out.println("Caught an: " + fnfEx.getClass().getName());
-            System.out.println("Message: " + fnfEx.getMessage());
-            System.out.println("Stacktrace follows...........");
-            fnfEx.printStackTrace(System.out);
-        }
-        catch(IOException ioEx) {
+        } catch(IOException ioEx) {
             System.out.println("Caught an: " + ioEx.getClass().getName());
             System.out.println("Message: " + ioEx.getMessage());
             System.out.println("Stacktrace follows...........");
index 43fb75db1c56ba8c359d95c5b70ebf7494ef104c..57395b1c46b0c00424b75c7e5ef052d1e77595b6 100644 (file)
@@ -36,23 +36,22 @@ import org.apache.poi.ss.usermodel.HorizontalAlignment;
  */
 public class Alignment {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet = wb.createSheet("new sheet");
-        HSSFRow row = sheet.createRow(2);
-        createCell(wb, row, 0, HorizontalAlignment.CENTER);
-        createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION);
-        createCell(wb, row, 2, HorizontalAlignment.FILL);
-        createCell(wb, row, 3, HorizontalAlignment.GENERAL);
-        createCell(wb, row, 4, HorizontalAlignment.JUSTIFY);
-        createCell(wb, row, 5, HorizontalAlignment.LEFT);
-        createCell(wb, row, 6, HorizontalAlignment.RIGHT);
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet = wb.createSheet("new sheet");
+            HSSFRow row = sheet.createRow(2);
+            createCell(wb, row, 0, HorizontalAlignment.CENTER);
+            createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION);
+            createCell(wb, row, 2, HorizontalAlignment.FILL);
+            createCell(wb, row, 3, HorizontalAlignment.GENERAL);
+            createCell(wb, row, 4, HorizontalAlignment.JUSTIFY);
+            createCell(wb, row, 5, HorizontalAlignment.LEFT);
+            createCell(wb, row, 6, HorizontalAlignment.RIGHT);
 
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        
-        wb.close();
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 
     /**
index 63b8b57dadeee7f5f19e0625e3ea3cea2c8a695b..4804973b4a26e5f94a890c256534c48c4422d9e3 100644 (file)
@@ -39,8 +39,7 @@ public class BigExample {
         int rownum;
 
         // create a new workbook
-        HSSFWorkbook wb = new HSSFWorkbook();
-        try {
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
             // create a new sheet
             HSSFSheet s = wb.createSheet();
             // declare a row object reference
@@ -54,7 +53,7 @@ public class BigExample {
             // create 2 fonts objects
             HSSFFont f = wb.createFont();
             HSSFFont f2 = wb.createFont();
-    
+
             //set font 1 to 12 point type
             f.setFontHeightInPoints((short) 12);
             //make it red
@@ -62,118 +61,110 @@ public class BigExample {
             // make it bold
             //arial is the default font
             f.setBold(true);
-    
+
             //set font 2 to 10 point type
             f2.setFontHeightInPoints((short) 10);
             //make it the color at palette index 0xf (white)
             f2.setColor(HSSFColorPredefined.WHITE.getIndex());
             //make it bold
             f2.setBold(true);
-    
+
             //set cell stlye
             cs.setFont(f);
             //set the cell format see HSSFDataFromat for a full list
             cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
-    
+
             //set a thin border
             cs2.setBorderBottom(BorderStyle.THIN);
             //fill w fg fill color
             cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
             // set foreground fill to red
             cs2.setFillForegroundColor(HSSFColorPredefined.RED.getIndex());
-    
+
             // set the font
             cs2.setFont(f2);
-    
+
             // set the sheet name to HSSF Test
             wb.setSheetName(0, "HSSF Test");
             // create a sheet with 300 rows (0-299)
-            for (rownum = 0; rownum < 300; rownum++)
-            {
+            for (rownum = 0; rownum < 300; rownum++) {
                 // create a row
                 r = s.createRow(rownum);
                 // on every other row
-                if ((rownum % 2) == 0)
-                {
+                if ((rownum % 2) == 0) {
                     // make the row height bigger  (in twips - 1/20 of a point)
                     r.setHeight((short) 0x249);
                 }
-    
+
                 //r.setRowNum(( short ) rownum);
                 // create 50 cells (0-49) (the += 2 becomes apparent later
-                for (int cellnum = 0; cellnum < 50; cellnum += 2)
-                {
+                for (int cellnum = 0; cellnum < 50; cellnum += 2) {
                     // create a numeric cell
                     c = r.createCell(cellnum);
                     // do some goofy math to demonstrate decimals
                     c.setCellValue(rownum * 10000 + cellnum
                             + (((double) rownum / 1000)
                             + ((double) cellnum / 10000)));
-    
+
                     // on every other row
-                    if ((rownum % 2) == 0)
-                    {
+                    if ((rownum % 2) == 0) {
                         // set this cell to the first cell style we defined
                         c.setCellStyle(cs);
                     }
-    
+
                     // create a string cell (see why += 2 in the
                     c = r.createCell(cellnum + 1);
-    
+
                     // set the cell's string value to "TEST"
                     c.setCellValue("TEST");
                     // make this column a bit wider
-                    s.setColumnWidth(cellnum + 1, (int)((50 * 8) / ((double) 1 / 20)));
-    
+                    s.setColumnWidth(cellnum + 1, (int) ((50 * 8) / ((double) 1 / 20)));
+
                     // on every other row
-                    if ((rownum % 2) == 0)
-                    {
+                    if ((rownum % 2) == 0) {
                         // set this to the white on red cell style
                         // we defined above
                         c.setCellStyle(cs2);
                     }
-    
+
                 }
             }
-    
+
             //draw a thick black border on the row at the bottom using BLANKS
             // advance 2 rows
             rownum++;
             rownum++;
-    
+
             r = s.createRow(rownum);
-    
+
             // define the third style to be the default
             // except with a thick black border at the bottom
             cs3.setBorderBottom(BorderStyle.THICK);
-    
+
             //create 50 cells
-            for (int cellnum =0; cellnum < 50; cellnum++) {
+            for (int cellnum = 0; cellnum < 50; cellnum++) {
                 //create a blank type cell (no value)
                 c = r.createCell(cellnum);
                 // set it to the thick black border style
                 c.setCellStyle(cs3);
             }
-    
+
             //end draw thick black border
-    
-    
+
+
             // demonstrate adding/naming and deleting a sheet
             // create a sheet, set its title then delete it
             wb.createSheet();
             wb.setSheetName(1, "DeletedSheet");
             wb.removeSheetAt(1);
             //end deleted sheet
-    
+
             // create a new file
-            FileOutputStream out = new FileOutputStream("workbook.xls");
-    
-            // write the workbook to the output stream
-            // close our file (don't blow out our file handles
-            wb.write(out);
-            out.close();
-        } finally {
-            wb.close();
+            try (FileOutputStream out = new FileOutputStream("workbook.xls")) {
+                // write the workbook to the output stream
+                // close our file (don't blow out our file handles
+                wb.write(out);
+            }
         }
     }
 }
index e332f4f7fbbf5d83770aba4206b304c5ddf3b4fa..9509619cc6d82007c25dcabb0d91743a63dba38d 100644 (file)
@@ -33,8 +33,7 @@ import org.apache.poi.ss.usermodel.BorderStyle;
  */
 public class Borders {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        try {
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
             HSSFSheet sheet = wb.createSheet("new sheet");
 
             // Create a row and put some cells in it. Rows are 0 based.
@@ -57,11 +56,9 @@ public class Borders {
             cell.setCellStyle(style);
 
             // Write the output to a file
-            FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-            wb.write(fileOut);
-            fileOut.close();
-        } finally {
-            wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
         }
     }
 }
index 2368591392ba6daf8211be5255395e1f7a424121..b14cc53abe42f9ddd2e4bb1551c43bebcf181a45 100644 (file)
@@ -39,68 +39,64 @@ import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
 public class CellComments {
 
     public static void main(String[] args) throws IOException  {
-
-        HSSFWorkbook wb = new HSSFWorkbook();
-        try {
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
             HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF");
-    
+
             // Create the drawing patriarch. This is the top level container for all shapes including cell comments.
             HSSFPatriarch patr = sheet.createDrawingPatriarch();
-    
+
             //create a cell in row 3
             HSSFCell cell1 = sheet.createRow(3).createCell(1);
             cell1.setCellValue(new HSSFRichTextString("Hello, World"));
-    
+
             //anchor defines size and position of the comment in worksheet
-            HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
-    
-             // set text in the comment
+            HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
+
+            // set text in the comment
             comment1.setString(new HSSFRichTextString("We can set comments in POI"));
-    
+
             //set comment author.
             //you can see it in the status bar when moving mouse over the commented cell
             comment1.setAuthor("Apache Software Foundation");
-    
+
             // The first way to assign comment to a cell is via HSSFCell.setCellComment method
             cell1.setCellComment(comment1);
-    
+
             //create another cell in row 6
             HSSFCell cell2 = sheet.createRow(6).createCell(1);
             cell2.setCellValue(36.6);
-    
-    
-            HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 8, (short) 6, 11));
+
+
+            HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 8, (short) 6, 11));
             //modify background color of the comment
             comment2.setFillColor(204, 236, 255);
-    
+
             HSSFRichTextString string = new HSSFRichTextString("Normal body temperature");
-    
+
             //apply custom font to the text in the comment
             HSSFFont font = wb.createFont();
             font.setFontName("Arial");
-            font.setFontHeightInPoints((short)10);
+            font.setFontHeightInPoints((short) 10);
             font.setBold(true);
             font.setColor(HSSFColorPredefined.RED.getIndex());
             string.applyFont(font);
-    
+
             comment2.setString(string);
             comment2.setVisible(true); //by default comments are hidden. This one is always visible.
-    
+
             comment2.setAuthor("Bill Gates");
-    
-            /**
+
+            /*
              * The second way to assign comment to a cell is to implicitly specify its row and column.
              * Note, it is possible to set row and column of a non-existing cell.
              * It works, the comment is visible.
              */
             comment2.setRow(6);
             comment2.setColumn(1);
-    
-            FileOutputStream out = new FileOutputStream("poi_comment.xls");
-            wb.write(out);
-            out.close();
-        } finally {
-            wb.close();
+
+            try (FileOutputStream out = new FileOutputStream("poi_comment.xls")) {
+                wb.write(out);
+            }
         }
     }
 }
index fd29e34e0ead58bc414debd06240ee69ceb86300..51dc89cc5d8c4a7dc5e0101849933fb369136041 100644 (file)
@@ -28,8 +28,7 @@ import org.apache.poi.ss.usermodel.CellType;
 
 public class CellTypes {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        try {
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
             HSSFSheet sheet = wb.createSheet("new sheet");
             HSSFRow row = sheet.createRow(2);
             row.createCell(0).setCellValue(1.1);
@@ -37,13 +36,11 @@ public class CellTypes {
             row.createCell(2).setCellValue("a string");
             row.createCell(3).setCellValue(true);
             row.createCell(4).setCellType(CellType.ERROR);
-    
+
             // Write the output to a file
-            FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-            wb.write(fileOut);
-            fileOut.close();
-        } finally {
-            wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
         }
     }
 }
index d2141b05056d4f02339fb7373fa71f5e238858a1..b2b803f111f4b4af74bc2b2ea282f1b3ad963963 100644 (file)
@@ -32,25 +32,24 @@ import java.io.IOException;
  */
 public class CreateCells {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet = wb.createSheet("new sheet");
-
-        // Create a row and put some cells in it. Rows are 0 based.
-        HSSFRow row = sheet.createRow(0);
-        // Create a cell and put a value in it.
-        HSSFCell cell = row.createCell(0);
-        cell.setCellValue(1);
-
-        // Or do it on one line.
-        row.createCell(1).setCellValue(1.2);
-        row.createCell(2).setCellValue("This is a string");
-        row.createCell(3).setCellValue(true);
-
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-
-        wb.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet = wb.createSheet("new sheet");
+
+            // Create a row and put some cells in it. Rows are 0 based.
+            HSSFRow row = sheet.createRow(0);
+            // Create a cell and put a value in it.
+            HSSFCell cell = row.createCell(0);
+            cell.setCellValue(1);
+
+            // Or do it on one line.
+            row.createCell(1).setCellValue(1.2);
+            row.createCell(2).setCellValue("This is a string");
+            row.createCell(3).setCellValue(true);
+
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 8afe085f1ed648236a475f20a11264dadb0a2d48..9fea613aad265f888e995769bfe9df109d938673 100644 (file)
@@ -35,29 +35,28 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  */
 public class CreateDateCells {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet = wb.createSheet("new sheet");
-
-        // Create a row and put some cells in it. Rows are 0 based.
-        HSSFRow row = sheet.createRow(0);
-
-        // Create a cell and put a date value in it.  The first cell is not styled as a date.
-        HSSFCell cell = row.createCell(0);
-        cell.setCellValue(new Date());
-
-        // we style the second cell as a date (and time).  It is important to create a new cell style from the workbook
-        // otherwise you can end up modifying the built in style and effecting not only this cell but other cells.
-        HSSFCellStyle cellStyle = wb.createCellStyle();
-        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
-        cell = row.createCell(1);
-        cell.setCellValue(new Date());
-        cell.setCellStyle(cellStyle);
-
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        
-        wb.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet = wb.createSheet("new sheet");
+
+            // Create a row and put some cells in it. Rows are 0 based.
+            HSSFRow row = sheet.createRow(0);
+
+            // Create a cell and put a date value in it.  The first cell is not styled as a date.
+            HSSFCell cell = row.createCell(0);
+            cell.setCellValue(new Date());
+
+            // we style the second cell as a date (and time).  It is important to create a new cell style from the workbook
+            // otherwise you can end up modifying the built in style and effecting not only this cell but other cells.
+            HSSFCellStyle cellStyle = wb.createCellStyle();
+            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
+            cell = row.createCell(1);
+            cell.setCellValue(new Date());
+            cell.setCellStyle(cellStyle);
+
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 4f0a707b2f83980107e4f791255648db23796c1d..79d9a2d3b7ea2bf01102a505caf5b70a1a8f6559 100644 (file)
@@ -34,34 +34,34 @@ public class EmbeddedObjects {
     @SuppressWarnings("unused")
     public static void main(String[] args) throws Exception {
         POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));
-        HSSFWorkbook workbook = new HSSFWorkbook(fs);
-        for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
-            //the OLE2 Class Name of the object
-            String oleName = obj.getOLE2ClassName();
-            DirectoryNode dn = (obj.hasDirectoryEntry()) ? (DirectoryNode) obj.getDirectory() : null;
-            Closeable document = null;
-            if (oleName.equals("Worksheet")) {
-                document = new HSSFWorkbook(dn, fs, false);
-            } else if (oleName.equals("Document")) {
-                document = new HWPFDocument(dn);
-            }  else if (oleName.equals("Presentation")) {
-                document = new HSLFSlideShow(dn);
-            } else {
-                if(dn != null){
-                    // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
-                    for (Entry entry : dn) {
-                         String name = entry.getName();
-                    }
+        try (HSSFWorkbook workbook = new HSSFWorkbook(fs)) {
+            for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
+                //the OLE2 Class Name of the object
+                String oleName = obj.getOLE2ClassName();
+                DirectoryNode dn = (obj.hasDirectoryEntry()) ? (DirectoryNode) obj.getDirectory() : null;
+                Closeable document = null;
+                if (oleName.equals("Worksheet")) {
+                    document = new HSSFWorkbook(dn, fs, false);
+                } else if (oleName.equals("Document")) {
+                    document = new HWPFDocument(dn);
+                } else if (oleName.equals("Presentation")) {
+                    document = new HSLFSlideShow(dn);
                 } else {
-                    // There is no DirectoryEntry
-                    // Recover the object's data from the HSSFObjectData instance.
-                    byte[] objectData = obj.getObjectData();
+                    if (dn != null) {
+                        // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
+                        for (Entry entry : dn) {
+                            String name = entry.getName();
+                        }
+                    } else {
+                        // There is no DirectoryEntry
+                        // Recover the object's data from the HSSFObjectData instance.
+                        byte[] objectData = obj.getObjectData();
+                    }
+                }
+                if (document != null) {
+                    document.close();
                 }
-            }
-            if (document != null) {
-                document.close();
             }
         }
-        workbook.close();
     }
 }
index 38c7503e0c004d1f97062330f738115a2c2e4829..857e1baea64e65cdc00019c4354b71db675edd41 100644 (file)
@@ -31,9 +31,7 @@ import java.io.InputStream;
 /**
  * This example shows how to use the event API for reading a file.
  */
-public class EventExample
-        implements HSSFListener
-{
+public class EventExample implements HSSFListener {
     private SSTRecord sstrec;
 
     /**
@@ -97,24 +95,22 @@ public class EventExample
     {
         // create a new file input stream with the input file specified
         // at the command line
-        FileInputStream fin = new FileInputStream(args[0]);
-        // create a new org.apache.poi.poifs.filesystem.Filesystem
-        POIFSFileSystem poifs = new POIFSFileSystem(fin);
-        // get the Workbook (excel part) stream in a InputStream
-        InputStream din = poifs.createDocumentInputStream("Workbook");
-        // construct out HSSFRequest object
-        HSSFRequest req = new HSSFRequest();
-        // lazy listen for ALL records with the listener shown above
-        req.addListenerForAllRecords(new EventExample());
-        // create our event factory
-        HSSFEventFactory factory = new HSSFEventFactory();
-        // process our events based on the document input stream
-        factory.processEvents(req, din);
-        // once all the events are processed close our file input stream
-        fin.close();
-        // and our document input stream (don't want to leak these!)
-        din.close();
-        poifs.close();
+        try (FileInputStream fin = new FileInputStream(args[0])) {
+            // create a new org.apache.poi.poifs.filesystem.Filesystem
+            try (POIFSFileSystem poifs = new POIFSFileSystem(fin)) {
+                // get the Workbook (excel part) stream in a InputStream
+                try (InputStream din = poifs.createDocumentInputStream("Workbook")) {
+                    // construct out HSSFRequest object
+                    HSSFRequest req = new HSSFRequest();
+                    // lazy listen for ALL records with the listener shown above
+                    req.addListenerForAllRecords(new EventExample());
+                    // create our event factory
+                    HSSFEventFactory factory = new HSSFEventFactory();
+                    // process our events based on the document input stream
+                    factory.processEvents(req, din);
+                }
+            }
+        }
         System.out.println("done.");
     }
 }
index 9b05853e4ff498f585711f49746e49f75d941238..9627780e1f4f0db7bab5d6c6784de2471308706f 100644 (file)
@@ -33,33 +33,32 @@ import org.apache.poi.ss.usermodel.FillPatternType;
  */
 public class FrillsAndFills {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet = wb.createSheet("new sheet");
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet = wb.createSheet("new sheet");
 
-        // Create a row and put some cells in it. Rows are 0 based.
-        HSSFRow row = sheet.createRow(1);
+            // Create a row and put some cells in it. Rows are 0 based.
+            HSSFRow row = sheet.createRow(1);
 
-        // Aqua background
-        HSSFCellStyle style = wb.createCellStyle();
-        style.setFillBackgroundColor(HSSFColorPredefined.AQUA.getIndex());
-        style.setFillPattern(FillPatternType.BIG_SPOTS);
-        HSSFCell cell = row.createCell(1);
-        cell.setCellValue("X");
-        cell.setCellStyle(style);
+            // Aqua background
+            HSSFCellStyle style = wb.createCellStyle();
+            style.setFillBackgroundColor(HSSFColorPredefined.AQUA.getIndex());
+            style.setFillPattern(FillPatternType.BIG_SPOTS);
+            HSSFCell cell = row.createCell(1);
+            cell.setCellValue("X");
+            cell.setCellStyle(style);
 
-        // Orange "foreground", foreground being the fill foreground not the font color.
-        style = wb.createCellStyle();
-        style.setFillForegroundColor(HSSFColorPredefined.ORANGE.getIndex());
-        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
-        cell = row.createCell(2);
-        cell.setCellValue("X");
-        cell.setCellStyle(style);
+            // Orange "foreground", foreground being the fill foreground not the font color.
+            style = wb.createCellStyle();
+            style.setFillForegroundColor(HSSFColorPredefined.ORANGE.getIndex());
+            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+            cell = row.createCell(2);
+            cell.setCellValue("X");
+            cell.setCellStyle(style);
 
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        
-        wb.close();
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index ab848d3dd6cb0b3ec5deaee2b466c51723ccb9f7..6e6fc5b3694381b4f9c7a907d0650c50d0ddcbe3 100644 (file)
@@ -47,12 +47,9 @@ public final class HSSFReadWrite {
         * creates an {@link HSSFWorkbook} with the specified OS filename.
         */
        private static HSSFWorkbook readFile(String filename) throws IOException {
-           FileInputStream fis = new FileInputStream(filename);
-           try {
-               return new HSSFWorkbook(fis);           // NOSONAR - should not be closed here
-           } finally {
-               fis.close();
-           }
+               try (FileInputStream fis = new FileInputStream(filename)) {
+                       return new HSSFWorkbook(fis);        // NOSONAR - should not be closed here
+               }
        }
 
        /**
@@ -60,8 +57,7 @@ public final class HSSFReadWrite {
         * rows/cells.
         */
        private static void testCreateSampleSheet(String outputFilename) throws IOException {
-               HSSFWorkbook wb = new HSSFWorkbook();
-               try {
+               try (HSSFWorkbook wb = new HSSFWorkbook()) {
                        HSSFSheet s = wb.createSheet();
                        HSSFCellStyle cs = wb.createCellStyle();
                        HSSFCellStyle cs2 = wb.createCellStyle();
@@ -125,14 +121,9 @@ public final class HSSFReadWrite {
                        wb.removeSheetAt(1);
 
                        // end deleted sheet
-                       FileOutputStream out = new FileOutputStream(outputFilename);
-                       try {
+                       try (FileOutputStream out = new FileOutputStream(outputFilename)) {
                                wb.write(out);
-                       } finally {
-                               out.close();
                        }
-               } finally {
-                       wb.close();
                }
        }
 
@@ -166,9 +157,7 @@ public final class HSSFReadWrite {
                try {
                        if (args.length < 2) {
 
-                               HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
-
-                               try {
+                               try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
                                        System.out.println("Data dump:\n");
 
                                        for (int k = 0; k < wb.getNumberOfSheets(); k++) {
@@ -187,7 +176,7 @@ public final class HSSFReadWrite {
                                                                HSSFCell cell = row.getCell(c);
                                                                String value;
 
-                                                               if(cell != null) {
+                                                               if (cell != null) {
                                                                        switch (cell.getCellType()) {
 
                                                                                case FORMULA:
@@ -223,8 +212,6 @@ public final class HSSFReadWrite {
                                                        }
                                                }
                                        }
-                               } finally {
-                                       wb.close();
                                }
                        } else if (args.length == 2) {
                                if (args[1].toLowerCase(Locale.ROOT).equals("write")) {
@@ -236,23 +223,16 @@ public final class HSSFReadWrite {
                                                        + " ms generation time");
                                } else {
                                        System.out.println("readwrite test");
-                                       HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
-                                       try {
-                                               FileOutputStream stream = new FileOutputStream(args[1]);
-                                               try {
+                                       try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
+                                               try (FileOutputStream stream = new FileOutputStream(args[1])) {
                                                        wb.write(stream);
-                                               } finally {
-                                                       stream.close();
                                                }
-                                       } finally {
-                                               wb.close();
                                        }
                                }
                        } else if (args.length == 3 && args[2].equalsIgnoreCase("modify1")) {
                                // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"
 
-                               HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
-                               try {
+                               try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
                                        HSSFSheet sheet = wb.getSheetAt(0);
 
                                        for (int k = 0; k < 25; k++) {
@@ -269,14 +249,9 @@ public final class HSSFReadWrite {
                                        HSSFCell cell = row.getCell(3);
                                        cell.setCellValue("MODIFIED CELL!!!!!");
 
-                                       FileOutputStream stream = new FileOutputStream(args[1]);
-                                       try {
+                                       try (FileOutputStream stream = new FileOutputStream(args[1])) {
                                                wb.write(stream);
-                                       } finally {
-                                               stream.close();
                                        }
-                               } finally {
-                                       wb.close();
                                }
                        }
                } catch (Exception e) {
index 003c09f688dfd18f652ce2d78f5913ec0960cd4a..5d4b18a3c201b1073dde65224dd51a4c6aa86bb7 100644 (file)
@@ -31,17 +31,17 @@ import org.apache.poi.ss.usermodel.CellType;
  */
 public class HyperlinkFormula {
     public static void main(String[] args) throws IOException {
-       HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet = wb.createSheet("new sheet");
-        HSSFRow row = sheet.createRow(0);
-
-        HSSFCell cell = row.createCell(0);
-        cell.setCellType(CellType.FORMULA);
-        cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")");
-
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+       try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet = wb.createSheet("new sheet");
+            HSSFRow row = sheet.createRow(0);
+
+            HSSFCell cell = row.createCell(0);
+            cell.setCellType(CellType.FORMULA);
+            cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")");
+
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 9a71bcd22248ba7508a215d5eb5bd55319bbb3eb..a6502df30447be50bd6392dbb58462cd1d689065 100644 (file)
@@ -37,61 +37,61 @@ import org.apache.poi.ss.usermodel.Font;
 public class Hyperlinks {
 
     public static void main(String[] args) throws IOException  {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFCreationHelper helper = wb.getCreationHelper();
-
-        //cell style for hyperlinks
-        //by default hyperlinks are blue and underlined
-        HSSFCellStyle hlink_style = wb.createCellStyle();
-        HSSFFont hlink_font = wb.createFont();
-        hlink_font.setUnderline(Font.U_SINGLE);
-        hlink_font.setColor(HSSFColorPredefined.BLUE.getIndex());
-        hlink_style.setFont(hlink_font);
-
-        HSSFCell cell;
-        HSSFSheet sheet = wb.createSheet("Hyperlinks");
-
-        //URL
-        cell = sheet.createRow(0).createCell(0);
-        cell.setCellValue("URL Link");
-        HSSFHyperlink link = helper.createHyperlink(HyperlinkType.URL);
-        link.setAddress("http://poi.apache.org/");
-        cell.setHyperlink(link);
-        cell.setCellStyle(hlink_style);
-
-        //link to a file in the current directory
-        cell = sheet.createRow(1).createCell(0);
-        cell.setCellValue("File Link");
-        link = helper.createHyperlink(HyperlinkType.FILE);
-        link.setAddress("link1.xls");
-        cell.setHyperlink(link);
-        cell.setCellStyle(hlink_style);
-
-        //e-mail link
-        cell = sheet.createRow(2).createCell(0);
-        cell.setCellValue("Email Link");
-        link = helper.createHyperlink(HyperlinkType.EMAIL);
-        //note, if subject contains white spaces, make sure they are url-encoded
-        link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
-        cell.setHyperlink(link);
-        cell.setCellStyle(hlink_style);
-
-        //link to a place in this workbook
-
-        //create a target sheet and cell
-        HSSFSheet sheet2 = wb.createSheet("Target Sheet");
-        sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
-
-        cell = sheet.createRow(3).createCell(0);
-        cell.setCellValue("Worksheet Link");
-        link = helper.createHyperlink(HyperlinkType.DOCUMENT);
-        link.setAddress("'Target Sheet'!A1");
-        cell.setHyperlink(link);
-        cell.setCellStyle(hlink_style);
-
-        FileOutputStream out = new FileOutputStream("hssf-links.xls");
-        wb.write(out);
-        out.close();
-        wb.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFCreationHelper helper = wb.getCreationHelper();
+
+            //cell style for hyperlinks
+            //by default hyperlinks are blue and underlined
+            HSSFCellStyle hlink_style = wb.createCellStyle();
+            HSSFFont hlink_font = wb.createFont();
+            hlink_font.setUnderline(Font.U_SINGLE);
+            hlink_font.setColor(HSSFColorPredefined.BLUE.getIndex());
+            hlink_style.setFont(hlink_font);
+
+            HSSFCell cell;
+            HSSFSheet sheet = wb.createSheet("Hyperlinks");
+
+            //URL
+            cell = sheet.createRow(0).createCell(0);
+            cell.setCellValue("URL Link");
+            HSSFHyperlink link = helper.createHyperlink(HyperlinkType.URL);
+            link.setAddress("http://poi.apache.org/");
+            cell.setHyperlink(link);
+            cell.setCellStyle(hlink_style);
+
+            //link to a file in the current directory
+            cell = sheet.createRow(1).createCell(0);
+            cell.setCellValue("File Link");
+            link = helper.createHyperlink(HyperlinkType.FILE);
+            link.setAddress("link1.xls");
+            cell.setHyperlink(link);
+            cell.setCellStyle(hlink_style);
+
+            //e-mail link
+            cell = sheet.createRow(2).createCell(0);
+            cell.setCellValue("Email Link");
+            link = helper.createHyperlink(HyperlinkType.EMAIL);
+            //note, if subject contains white spaces, make sure they are url-encoded
+            link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
+            cell.setHyperlink(link);
+            cell.setCellStyle(hlink_style);
+
+            //link to a place in this workbook
+
+            //create a target sheet and cell
+            HSSFSheet sheet2 = wb.createSheet("Target Sheet");
+            sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
+
+            cell = sheet.createRow(3).createCell(0);
+            cell.setCellValue("Worksheet Link");
+            link = helper.createHyperlink(HyperlinkType.DOCUMENT);
+            link.setAddress("'Target Sheet'!A1");
+            cell.setHyperlink(link);
+            cell.setCellStyle(hlink_style);
+
+            try (FileOutputStream out = new FileOutputStream("hssf-links.xls")) {
+                wb.write(out);
+            }
+        }
     }
 }
index 81733a3424438dfbefe7753cff344d26b5eb8468..4850e368a5bbc06d6cf959dbfd457197204ef63b 100644 (file)
@@ -67,8 +67,7 @@ public class InCellLists {
      *                       the Excel spreadsheet file this code will create.
      */
     public void demonstrateMethodCalls(String outputFilename) throws IOException {
-        HSSFWorkbook workbook = new HSSFWorkbook();
-        try {
+        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
             HSSFSheet sheet = workbook.createSheet("In Cell Lists");
             HSSFRow row = sheet.createRow(0);
 
@@ -89,7 +88,7 @@ public class InCellLists {
             this.listInCell(workbook, listItems, cell);
             // The row height and cell width are set here to ensure that the
             // list may be seen.
-            row.setHeight((short)1100);
+            row.setHeight((short) 1100);
             sheet.setColumnWidth(0, 9500);
 
             // Create a cell at A3 and insert a numbered list into that cell.
@@ -100,7 +99,7 @@ public class InCellLists {
             listItems.add("List Item Five.");
             listItems.add("List Item Six.");
             this.numberedListInCell(workbook, listItems, cell, 1, 2);
-            row.setHeight((short)1550);
+            row.setHeight((short) 1550);
 
             // Create a cell at A4 and insert a numbered list into that cell.
             // Note that a couple of items have been added to the listItems
@@ -112,7 +111,7 @@ public class InCellLists {
             listItems.add("List Item Nine.");
             listItems.add("List Item Ten.");
             this.bulletedListInCell(workbook, listItems, cell);
-            row.setHeight((short)2550);
+            row.setHeight((short) 2550);
 
             // Insert a plain, multi-level list into cell A5. Note that
             // the major difference here is that the list items are passed as
@@ -143,7 +142,7 @@ public class InCellLists {
             listItems.add("ML List Item Four - Sub Item Three.");
             multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems));
             this.multiLevelListInCell(workbook, multiLevelListItems, cell);
-            row.setHeight((short)2800);
+            row.setHeight((short) 2800);
 
             // Insert a numbered multi-level list into cell A6. Note that the
             // same ArrayList as constructed for the above plain multi-level
@@ -151,8 +150,8 @@ public class InCellLists {
             row = sheet.createRow(5);
             cell = row.createCell(0);
             this.multiLevelNumberedListInCell(workbook, multiLevelListItems,
-                                              cell, 1, 1, 1, 2);
-            row.setHeight((short)2800);
+                    cell, 1, 1, 1, 2);
+            row.setHeight((short) 2800);
 
             // Insert a numbered multi-level list into cell A7. Note that the
             // same ArrayList as constructed for the plain multi-level list
@@ -160,31 +159,18 @@ public class InCellLists {
             row = sheet.createRow(6);
             cell = row.createCell(0);
             this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell);
-            row.setHeight((short)2800);
+            row.setHeight((short) 2800);
 
             // Save the completed workbook
-            FileOutputStream fos = new FileOutputStream(new File(outputFilename));
-            try {
+            try (FileOutputStream fos = new FileOutputStream(new File(outputFilename))) {
                 workbook.write(fos);
-            } finally {
-                fos.close();
             }
-        }
-        catch(FileNotFoundException fnfEx) {
-            System.out.println("Caught a: " + fnfEx.getClass().getName());
-            System.out.println("Message: " + fnfEx.getMessage());
-            System.out.println("Stacktrace follows...........");
-            fnfEx.printStackTrace(System.out);
-        }
-        catch(IOException ioEx) {
+        } catch (IOException ioEx) {
             System.out.println("Caught a: " + ioEx.getClass().getName());
             System.out.println("Message: " + ioEx.getMessage());
             System.out.println("Stacktrace follows...........");
             ioEx.printStackTrace(System.out);
         }
-        finally {
-            workbook.close();
-        }
     }
 
     /**
index 09d08dd257dcf927ece2c3047a5da1c8888c0439..af1d8dd98af1392655ca80e216520a5424913b66 100644 (file)
@@ -31,19 +31,19 @@ import org.apache.poi.ss.util.CellRangeAddress;
  */
 public class MergedCells {
    public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet = wb.createSheet("new sheet");
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+             HSSFSheet sheet = wb.createSheet("new sheet");
 
-        HSSFRow row = sheet.createRow(1);
-        HSSFCell cell = row.createCell(1);
-        cell.setCellValue("This is a test of merging");
+             HSSFRow row = sheet.createRow(1);
+             HSSFCell cell = row.createCell(1);
+             cell.setCellValue("This is a test of merging");
 
-        sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
+             sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
 
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+             // Write the output to a file
+             try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                  wb.write(fileOut);
+             }
+        }
     }
 }
index 00f60c4dafe222eb08cbba008c9cef82bf862b88..24f1f3dbc038c8565bfdeef3e63e4db0f612fdcf 100644 (file)
@@ -33,31 +33,27 @@ import org.apache.poi.ss.usermodel.CellType;
  */
 public class NewLinesInCells {
     public static void main( String[] args ) throws IOException {
-
-        HSSFWorkbook wb = new HSSFWorkbook();
-               HSSFSheet s = wb.createSheet();
-               HSSFRow r = null;
-               HSSFCell c = null;
-               HSSFCellStyle cs = wb.createCellStyle();
-               HSSFFont f2 = wb.createFont();
-
-               cs = wb.createCellStyle();
-
-               cs.setFont(f2);
-               // Word Wrap MUST be turned on
-               cs.setWrapText(true);
-
-               r = s.createRow(2);
-               r.setHeight((short) 0x349);
-               c = r.createCell(2);
-               c.setCellType(CellType.STRING);
-               c.setCellValue("Use \n with word wrap on to create a new line");
-               c.setCellStyle(cs);
-               s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20)));
-
-               FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-               wb.write(fileOut);
-               fileOut.close();
-               wb.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+                       HSSFSheet s = wb.createSheet();
+                       HSSFFont f2 = wb.createFont();
+
+                       HSSFCellStyle cs = wb.createCellStyle();
+
+                       cs.setFont(f2);
+                       // Word Wrap MUST be turned on
+                       cs.setWrapText(true);
+
+                       HSSFRow r = s.createRow(2);
+                       r.setHeight((short) 0x349);
+                       HSSFCell c = r.createCell(2);
+                       c.setCellType(CellType.STRING);
+                       c.setCellValue("Use \n with word wrap on to create a new line");
+                       c.setCellStyle(cs);
+                       s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20)));
+
+                       try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                               wb.write(fileOut);
+                       }
+               }
     }
 }
index 495543e49a31d57fd8556c31398d7659801b4cd8..225425445d4a0fdc5e0d8448f44e051a08c40431 100644 (file)
@@ -28,16 +28,17 @@ import org.apache.poi.ss.util.WorkbookUtil;
  */
 public abstract class NewSheet {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        wb.createSheet("new sheet");
-        // create with default name
-        wb.createSheet();
-        final String name = "second sheet";
-        // setting sheet name later
-        wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name));
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            wb.createSheet("new sheet");
+            // create with default name
+            wb.createSheet();
+            final String name = "second sheet";
+            // setting sheet name later
+            wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name));
+
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index e6e0e4137e0b87a9cec2ed49d370006f9d74530c..3e61aaf3425bff25935b500f2cf4096d8cce49b0 100644 (file)
@@ -29,10 +29,10 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  */
 public class NewWorkbook {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 68aafbc7cfa8df39539b780c318da9649cb37824..ce4935230c1b4e484c3579407b86f45838341de5 100644 (file)
@@ -30,24 +30,25 @@ import java.io.*;
 public class OfficeDrawing {
     public static void main(String[] args) throws IOException {
         // Create the workbook and sheets.
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet1 = wb.createSheet("new sheet");
-        HSSFSheet sheet2 = wb.createSheet("second sheet");
-        HSSFSheet sheet3 = wb.createSheet("third sheet");
-        HSSFSheet sheet4 = wb.createSheet("fourth sheet");
-        HSSFSheet sheet5 = wb.createSheet("fifth sheet");
-
-        // Draw stuff in them
-        drawSheet1( sheet1 );
-        drawSheet2( sheet2 );
-        drawSheet3( sheet3 );
-        drawSheet4( sheet4, wb );
-        drawSheet5( sheet5, wb );
-
-        // Write the file out.
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet1 = wb.createSheet("new sheet");
+            HSSFSheet sheet2 = wb.createSheet("second sheet");
+            HSSFSheet sheet3 = wb.createSheet("third sheet");
+            HSSFSheet sheet4 = wb.createSheet("fourth sheet");
+            HSSFSheet sheet5 = wb.createSheet("fifth sheet");
+
+            // Draw stuff in them
+            drawSheet1(sheet1);
+            drawSheet2(sheet2);
+            drawSheet3(sheet3);
+            drawSheet4(sheet4, wb);
+            drawSheet5(sheet5, wb);
+
+            // Write the file out.
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 
     private static void drawSheet1( HSSFSheet sheet1 )
index 301d7ed784d171c1a588b50070e73f17ae562582..b437371ac15f67694502325e1670b69b503a1803 100644 (file)
@@ -32,51 +32,51 @@ public class OfficeDrawingWithGraphics {
     public static void main( String[] args ) throws IOException {
         // Create a workbook with one sheet and size the first three somewhat
         // larger so we can fit the chemical structure diagram in.
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet = wb.createSheet( "my drawing" );
-        sheet.setColumnWidth(1, 256 * 27);
-        HSSFRow row1 = sheet.createRow(0);
-        row1.setHeightInPoints(10 * 15f);
-        HSSFRow row2 = sheet.createRow(1);
-        row2.setHeightInPoints(5 * 15f);
-        HSSFRow row3 = sheet.createRow(2);
-        row3.setHeightInPoints(10 * 15f);
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet = wb.createSheet("my drawing");
+            sheet.setColumnWidth(1, 256 * 27);
+            HSSFRow row1 = sheet.createRow(0);
+            row1.setHeightInPoints(10 * 15f);
+            HSSFRow row2 = sheet.createRow(1);
+            row2.setHeightInPoints(5 * 15f);
+            HSSFRow row3 = sheet.createRow(2);
+            row3.setHeightInPoints(10 * 15f);
 
-        // Add some cells so we can test that the anchoring works when we
-        // sort them.
-        row1.createCell(0).setCellValue("C");
-        row2.createCell(0).setCellValue("A");
-        row3.createCell(0).setCellValue("B");
+            // Add some cells so we can test that the anchoring works when we
+            // sort them.
+            row1.createCell(0).setCellValue("C");
+            row2.createCell(0).setCellValue("A");
+            row3.createCell(0).setCellValue("B");
 
-        // Create the top level drawing patriarch.
-        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
+            // Create the top level drawing patriarch.
+            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
 
-        HSSFClientAnchor a;
-        HSSFShapeGroup group;
-        EscherGraphics g;
-        EscherGraphics2d g2d;
-        // Anchor entirely within one cell.
-        a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 );
-        group = patriarch.createGroup( a );
-        group.setCoordinates( 0, 0, 320, 276 );
-        float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
-        g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel );
-        g2d = new EscherGraphics2d( g );
-        drawStar( g2d );
+            HSSFClientAnchor a;
+            HSSFShapeGroup group;
+            EscherGraphics g;
+            EscherGraphics2d g2d;
+            // Anchor entirely within one cell.
+            a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 1, 0, (short) 1, 0);
+            group = patriarch.createGroup(a);
+            group.setCoordinates(0, 0, 320, 276);
+            float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
+            g = new EscherGraphics(group, wb, Color.black, verticalPointsPerPixel);
+            g2d = new EscherGraphics2d(g);
+            drawStar(g2d);
 
-        a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 1, (short) 1, 1 );
-        group = patriarch.createGroup( a );
-        group.setCoordinates( 0, 0, 640, 276 );
-        verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
+            a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 1, 1, (short) 1, 1);
+            group = patriarch.createGroup(a);
+            group.setCoordinates(0, 0, 640, 276);
+            verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
 //        verticalPixelsPerPoint = (float)Math.abs(group.getY2() - group.getY1()) / a.getAnchorHeightInPoints(sheet);
-        g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel );
-        g2d = new EscherGraphics2d( g );
-        drawStar( g2d );
-
-        FileOutputStream out = new FileOutputStream("workbook.xls");
-        wb.write(out);
-        out.close();
+            g = new EscherGraphics(group, wb, Color.black, verticalPointsPerPixel);
+            g2d = new EscherGraphics2d(g);
+            drawStar(g2d);
 
+            try (FileOutputStream out = new FileOutputStream("workbook.xls")) {
+                wb.write(out);
+            }
+        }
     }
 
     private static void drawStar( EscherGraphics2d g2d )
index ad93f5e717a38a6d3a467f1e656985a15f471000..9630957232c19d9a42f0c5358aab90bd2c9e0534 100644 (file)
@@ -37,14 +37,11 @@ public class Outlines implements Closeable {
     throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
         POILogger LOGGER = POILogFactory.getLogger(Outlines.class);
         for (int i=1; i<=13; i++) {
-            Outlines o = new Outlines();
-            try {
-                String log = (String)Outlines.class.getDeclaredMethod("test"+i).invoke(o);
-                String filename = "outline"+i+".xls";
+            try (Outlines o = new Outlines()) {
+                String log = (String) Outlines.class.getDeclaredMethod("test" + i).invoke(o);
+                String filename = "outline" + i + ".xls";
                 o.writeOut(filename);
-                LOGGER.log(POILogger.INFO, filename+" written. "+log);
-            } finally {
-                o.close();
+                LOGGER.log(POILogger.INFO, filename + " written. " + log);
             }
         }
     }
@@ -53,11 +50,8 @@ public class Outlines implements Closeable {
     private final HSSFSheet sheet1 = wb.createSheet("new sheet");
 
     public void writeOut(String filename) throws IOException {
-        FileOutputStream fileOut = new FileOutputStream(filename);
-        try {
+        try (FileOutputStream fileOut = new FileOutputStream(filename)) {
             wb.write(fileOut);
-        } finally {
-            fileOut.close();
         }
     }
     
index 2b3553f768de73851b7c4408cf812bd0fa437ae1..2979ef06675696cfc75f377b5f05cfacbfe27284 100644 (file)
@@ -36,12 +36,7 @@ import org.apache.poi.ss.usermodel.CellType;
  */
 public class ReadWriteWorkbook {
     public static void main(String[] args) throws IOException {
-        FileInputStream fileIn = null;
-        FileOutputStream fileOut = null;
-
-        try
-        {
-            fileIn = new FileInputStream("workbook.xls");
+        try (FileInputStream fileIn = new FileInputStream("workbook.xls")) {
             POIFSFileSystem fs = new POIFSFileSystem(fileIn);
             HSSFWorkbook wb = new HSSFWorkbook(fs);
             HSSFSheet sheet = wb.getSheetAt(0);
@@ -55,13 +50,9 @@ public class ReadWriteWorkbook {
             cell.setCellValue("a test");
 
             // Write the output to a file
-            fileOut = new FileOutputStream("workbookout.xls");
-            wb.write(fileOut);
-        } finally {
-            if (fileOut != null)
-                fileOut.close();
-            if (fileIn != null)
-                fileIn.close();
+            try (FileOutputStream fileOut = new FileOutputStream("workbookout.xls")) {
+                wb.write(fileOut);
+            }
         }
     }
 }
index 9299b7cbded1459ba53df22b6f4dd826b6ef6fb6..5d6b4d5f90319990e799758d8a2397465b5fa3c5 100644 (file)
@@ -30,35 +30,35 @@ import org.apache.poi.ss.util.CellRangeAddress;
 
 public class RepeatingRowsAndColumns {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet1 = wb.createSheet("first sheet");
-        HSSFSheet sheet2 = wb.createSheet("second sheet");
-        HSSFSheet sheet3 = wb.createSheet("third sheet");
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet1 = wb.createSheet("first sheet");
+            HSSFSheet sheet2 = wb.createSheet("second sheet");
+            HSSFSheet sheet3 = wb.createSheet("third sheet");
 
-        HSSFFont boldFont = wb.createFont();
-        boldFont.setFontHeightInPoints((short)22);
-        boldFont.setBold(true);
+            HSSFFont boldFont = wb.createFont();
+            boldFont.setFontHeightInPoints((short) 22);
+            boldFont.setBold(true);
 
-        HSSFCellStyle boldStyle = wb.createCellStyle();
-        boldStyle.setFont(boldFont);
+            HSSFCellStyle boldStyle = wb.createCellStyle();
+            boldStyle.setFont(boldFont);
 
-        HSSFRow row = sheet1.createRow(1);
-        HSSFCell cell = row.createCell(0);
-        cell.setCellValue("This quick brown fox");
-        cell.setCellStyle(boldStyle);
+            HSSFRow row = sheet1.createRow(1);
+            HSSFCell cell = row.createCell(0);
+            cell.setCellValue("This quick brown fox");
+            cell.setCellStyle(boldStyle);
 
-        // Set the columns to repeat from column 0 to 2 on the first sheet
-        sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
-        // Set the rows to repeat from row 0 to 2 on the second sheet.
-        sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:3"));
-        // Set the the repeating rows and columns on the third sheet.
-        CellRangeAddress cra = CellRangeAddress.valueOf("D1:E2"); 
-        sheet3.setRepeatingColumns(cra);
-        sheet3.setRepeatingRows(cra);
+            // Set the columns to repeat from column 0 to 2 on the first sheet
+            sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
+            // Set the rows to repeat from row 0 to 2 on the second sheet.
+            sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:3"));
+            // Set the the repeating rows and columns on the third sheet.
+            CellRangeAddress cra = CellRangeAddress.valueOf("D1:E2");
+            sheet3.setRepeatingColumns(cra);
+            sheet3.setRepeatingRows(cra);
 
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 85cba2eb98cad43ea52d9799a634341975e2e6dc..a76864094b3af5e0918b750c3b1978191e7f05a6 100644 (file)
@@ -28,24 +28,24 @@ import org.apache.poi.ss.usermodel.Sheet;
 
 public class SplitAndFreezePanes {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet1 = wb.createSheet("new sheet");
-        HSSFSheet sheet2 = wb.createSheet("second sheet");
-        HSSFSheet sheet3 = wb.createSheet("third sheet");
-        HSSFSheet sheet4 = wb.createSheet("fourth sheet");
-
-        // Freeze just one row
-        sheet1.createFreezePane( 0, 1, 0, 1 );
-        // Freeze just one column
-        sheet2.createFreezePane( 1, 0, 1, 0 );
-        // Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
-        sheet3.createFreezePane( 2, 2 );
-        // Create a split with the lower left side being the active quadrant
-        sheet4.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
-
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet1 = wb.createSheet("new sheet");
+            HSSFSheet sheet2 = wb.createSheet("second sheet");
+            HSSFSheet sheet3 = wb.createSheet("third sheet");
+            HSSFSheet sheet4 = wb.createSheet("fourth sheet");
+
+            // Freeze just one row
+            sheet1.createFreezePane(0, 1, 0, 1);
+            // Freeze just one column
+            sheet2.createFreezePane(1, 0, 1, 0);
+            // Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
+            sheet3.createFreezePane(2, 2);
+            // Create a split with the lower left side being the active quadrant
+            sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
+
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index d3c674a756d0e268da467e44439fbbdb9acc5cf4..f0e114a1a08d86efed652bf7833511f74310c421 100644 (file)
@@ -32,32 +32,32 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  */
 public class WorkingWithFonts {
     public static void main(String[] args) throws IOException {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet = wb.createSheet("new sheet");
-
-        // Create a row and put some cells in it. Rows are 0 based.
-        HSSFRow row = sheet.createRow(1);
-
-        // Create a new font and alter it.
-        HSSFFont font = wb.createFont();
-        font.setFontHeightInPoints((short)24);
-        font.setFontName("Courier New");
-        font.setItalic(true);
-        font.setStrikeout(true);
-
-        // Fonts are set into a style so create a new one to use.
-        HSSFCellStyle style = wb.createCellStyle();
-        style.setFont(font);
-
-        // Create a cell and put a value in it.
-        HSSFCell cell = row.createCell(1);
-        cell.setCellValue("This is a test of fonts");
-        cell.setCellStyle(style);
-
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet = wb.createSheet("new sheet");
+
+            // Create a row and put some cells in it. Rows are 0 based.
+            HSSFRow row = sheet.createRow(1);
+
+            // Create a new font and alter it.
+            HSSFFont font = wb.createFont();
+            font.setFontHeightInPoints((short) 24);
+            font.setFontName("Courier New");
+            font.setItalic(true);
+            font.setStrikeout(true);
+
+            // Fonts are set into a style so create a new one to use.
+            HSSFCellStyle style = wb.createCellStyle();
+            style.setFont(font);
+
+            // Create a cell and put a value in it.
+            HSSFCell cell = row.createCell(1);
+            cell.setCellValue("This is a test of fonts");
+            cell.setCellStyle(style);
+
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index f83b5900e83ed53fe76441489f29b6bbb8583be5..600041fc29de8c208c22dc6d507112dfdb0f45bc 100644 (file)
@@ -32,15 +32,14 @@ import java.io.FileOutputStream;
  */
 public class ZoomSheet
 {
-    public static void main(String[] args)
-        throws IOException
-    {
-        HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFSheet sheet1 = wb.createSheet("new sheet");
-        sheet1.setZoom(75);   // 75 percent magnification
-        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+    public static void main(String[] args) throws IOException {
+        try (HSSFWorkbook wb = new HSSFWorkbook()) {
+            HSSFSheet sheet1 = wb.createSheet("new sheet");
+            sheet1.setZoom(75);   // 75 percent magnification
+
+            try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index c187a1b415aa8eaf91d95dd2d2d8d4473017d28c..4a8ef5ad1ffa1b57210a5e9fcfe2c9a59dc82391 100644 (file)
@@ -216,13 +216,9 @@ public final class Word2Forrest
 
 
     public static void main(String[] args) throws IOException {
-        InputStream is = new FileInputStream(args[0]);
-        OutputStream out = new FileOutputStream("test.xml");
-        try {
-            new Word2Forrest(new HWPFDocument(is), out);
-        } finally {
-            out.close();
-            is.close();
-        }
+      try (InputStream is = new FileInputStream(args[0]);
+           OutputStream out = new FileOutputStream("test.xml")) {
+        new Word2Forrest(new HWPFDocument(is), out);
+      }
     }
 }
index c767f24d9616c1403d4c07ca45a9f4ed74be5c1e..cdd2bbc4c0f750f7ce2b6004b2230ebaba56726e 100644 (file)
@@ -29,30 +29,29 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class AligningCells {
 
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
+        try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
 
-        Sheet sheet = wb.createSheet();
-        Row row = sheet.createRow(2);
-        row.setHeightInPoints(30);
-        for (int i = 0; i < 8; i++) {
-            //column width is set in units of 1/256th of a character width
-            sheet.setColumnWidth(i, 256 * 15);
-        }
-
-        createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
-        createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
-        createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
-        createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
-        createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
-        createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
-        createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
+            Sheet sheet = wb.createSheet();
+            Row row = sheet.createRow(2);
+            row.setHeightInPoints(30);
+            for (int i = 0; i < 8; i++) {
+                //column width is set in units of 1/256th of a character width
+                sheet.setColumnWidth(i, 256 * 15);
+            }
 
-        // Write the output to a file
-        OutputStream fileOut = new FileOutputStream("ss-example-align.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
+            createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
+            createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
+            createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
+            createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
+            createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
+            createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
+            createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
 
-        wb.close();
+            // Write the output to a file
+            try (OutputStream fileOut = new FileOutputStream("ss-example-align.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 
     /**
index 3cf0d2d36d1ed2d12ef68ef00f0f375eed9c46fd..bd7a95d05f8e94f66eb5caecd1300574ec00597e 100644 (file)
@@ -51,97 +51,97 @@ public class CalendarDemo {
 
         Calendar calendar = Calendar.getInstance();
         boolean xlsx = true;
-        for (int i = 0; i < args.length; i++) {
-            if(args[i].charAt(0) == '-'){
-                xlsx = args[i].equals("-xlsx");
+        for (String arg : args) {
+            if (arg.charAt(0) == '-') {
+                xlsx = arg.equals("-xlsx");
             } else {
-              calendar.set(Calendar.YEAR, Integer.parseInt(args[i]));
+                calendar.set(Calendar.YEAR, Integer.parseInt(arg));
             }
         }
         int year = calendar.get(Calendar.YEAR);
 
-        Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook();
-
-        Map<String, CellStyle> styles = createStyles(wb);
-
-        for (int month = 0; month < 12; month++) {
-            calendar.set(Calendar.MONTH, month);
-            calendar.set(Calendar.DAY_OF_MONTH, 1);
-            //create a sheet for each month
-            Sheet sheet = wb.createSheet(months[month]);
-
-            //turn off gridlines
-            sheet.setDisplayGridlines(false);
-            sheet.setPrintGridlines(false);
-            sheet.setFitToPage(true);
-            sheet.setHorizontallyCenter(true);
-            PrintSetup printSetup = sheet.getPrintSetup();
-            printSetup.setLandscape(true);
-
-            //the following three statements are required only for HSSF
-            sheet.setAutobreaks(true);
-            printSetup.setFitHeight((short)1);
-            printSetup.setFitWidth((short)1);
-
-            //the header row: centered text in 48pt font
-            Row headerRow = sheet.createRow(0);
-            headerRow.setHeightInPoints(80);
-            Cell titleCell = headerRow.createCell(0);
-            titleCell.setCellValue(months[month] + " " + year);
-            titleCell.setCellStyle(styles.get("title"));
-            sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
-
-            //header with month titles
-            Row monthRow = sheet.createRow(1);
-            for (int i = 0; i < days.length; i++) {
-                //set column widths, the width is measured in units of 1/256th of a character width
-                sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide
-                sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide
-                sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1));
-                Cell monthCell = monthRow.createCell(i*2);
-                monthCell.setCellValue(days[i]);
-                monthCell.setCellStyle(styles.get("month"));
-            }
-
-            int cnt = 1, day=1;
-            int rownum = 2;
-            for (int j = 0; j < 6; j++) {
-                Row row = sheet.createRow(rownum++);
-                row.setHeightInPoints(100);
+        try (Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook()) {
+
+            Map<String, CellStyle> styles = createStyles(wb);
+
+            for (int month = 0; month < 12; month++) {
+                calendar.set(Calendar.MONTH, month);
+                calendar.set(Calendar.DAY_OF_MONTH, 1);
+                //create a sheet for each month
+                Sheet sheet = wb.createSheet(months[month]);
+
+                //turn off gridlines
+                sheet.setDisplayGridlines(false);
+                sheet.setPrintGridlines(false);
+                sheet.setFitToPage(true);
+                sheet.setHorizontallyCenter(true);
+                PrintSetup printSetup = sheet.getPrintSetup();
+                printSetup.setLandscape(true);
+
+                //the following three statements are required only for HSSF
+                sheet.setAutobreaks(true);
+                printSetup.setFitHeight((short) 1);
+                printSetup.setFitWidth((short) 1);
+
+                //the header row: centered text in 48pt font
+                Row headerRow = sheet.createRow(0);
+                headerRow.setHeightInPoints(80);
+                Cell titleCell = headerRow.createCell(0);
+                titleCell.setCellValue(months[month] + " " + year);
+                titleCell.setCellStyle(styles.get("title"));
+                sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
+
+                //header with month titles
+                Row monthRow = sheet.createRow(1);
                 for (int i = 0; i < days.length; i++) {
-                    Cell dayCell_1 = row.createCell(i*2);
-                    Cell dayCell_2 = row.createCell(i*2 + 1);
-
-                    int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
-                    if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
-                        dayCell_1.setCellValue(day);
-                        calendar.set(Calendar.DAY_OF_MONTH, ++day);
+                    //set column widths, the width is measured in units of 1/256th of a character width
+                    sheet.setColumnWidth(i * 2, 5 * 256); //the column is 5 characters wide
+                    sheet.setColumnWidth(i * 2 + 1, 13 * 256); //the column is 13 characters wide
+                    sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1));
+                    Cell monthCell = monthRow.createCell(i * 2);
+                    monthCell.setCellValue(days[i]);
+                    monthCell.setCellStyle(styles.get("month"));
+                }
 
-                        if(i == 0 || i == days.length-1) {
-                            dayCell_1.setCellStyle(styles.get("weekend_left"));
-                            dayCell_2.setCellStyle(styles.get("weekend_right"));
+                int cnt = 1, day = 1;
+                int rownum = 2;
+                for (int j = 0; j < 6; j++) {
+                    Row row = sheet.createRow(rownum++);
+                    row.setHeightInPoints(100);
+                    for (int i = 0; i < days.length; i++) {
+                        Cell dayCell_1 = row.createCell(i * 2);
+                        Cell dayCell_2 = row.createCell(i * 2 + 1);
+
+                        int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
+                        if (cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
+                            dayCell_1.setCellValue(day);
+                            calendar.set(Calendar.DAY_OF_MONTH, ++day);
+
+                            if (i == 0 || i == days.length - 1) {
+                                dayCell_1.setCellStyle(styles.get("weekend_left"));
+                                dayCell_2.setCellStyle(styles.get("weekend_right"));
+                            } else {
+                                dayCell_1.setCellStyle(styles.get("workday_left"));
+                                dayCell_2.setCellStyle(styles.get("workday_right"));
+                            }
                         } else {
-                            dayCell_1.setCellStyle(styles.get("workday_left"));
-                            dayCell_2.setCellStyle(styles.get("workday_right"));
+                            dayCell_1.setCellStyle(styles.get("grey_left"));
+                            dayCell_2.setCellStyle(styles.get("grey_right"));
                         }
-                    } else {
-                        dayCell_1.setCellStyle(styles.get("grey_left"));
-                        dayCell_2.setCellStyle(styles.get("grey_right"));
+                        cnt++;
                     }
-                    cnt++;
+                    if (calendar.get(Calendar.MONTH) > month) break;
                 }
-                if(calendar.get(Calendar.MONTH) > month) break;
             }
-        }
 
-        // Write the output to a file
-        String file = "calendar.xls";
-        if(wb instanceof XSSFWorkbook) file += "x";
-        FileOutputStream out = new FileOutputStream(file);
-        wb.write(out);
-        out.close();
-        
-        wb.close();
+            // Write the output to a file
+            String file = "calendar.xls";
+            if (wb instanceof XSSFWorkbook) file += "x";
+
+            try (FileOutputStream out = new FileOutputStream(file)) {
+                wb.write(out);
+            }
+        }
     }
 
     /**
index 55b85a291bdcd00d6759f99344414aabea62e10b..9090b5ddf46ebc1d6a69c17b87b30fb55df52148 100644 (file)
@@ -43,45 +43,44 @@ public class CellStyleDetails {
            throw new IllegalArgumentException("Filename must be given");
         }
         
-        Workbook wb = WorkbookFactory.create(new File(args[0]));
-        DataFormatter formatter = new DataFormatter();
-       
-        for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {
-           Sheet sheet = wb.getSheetAt(sn);
-           System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());
-           
-           for(Row row : sheet) {
-              System.out.println("  Row " + row.getRowNum());
-              
-              for(Cell cell : row) {
-                 CellReference ref = new CellReference(cell);
-                 System.out.print("    " + ref.formatAsString());
-                 System.out.print(" (" + cell.getColumnIndex() + ") ");
-                 
-                 CellStyle style = cell.getCellStyle();
-                 System.out.print("Format=" + style.getDataFormatString() + " ");
-                 System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
-                 System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");
-                 
-                 Font font = wb.getFontAt( style.getFontIndex() );
-                 System.out.print("Font=" + font.getFontName() + " ");
-                 System.out.print("FontColor=");
-                 if(font instanceof HSSFFont) {
-                    System.out.print( renderColor( ((HSSFFont)font).getHSSFColor((HSSFWorkbook)wb)) );
-                 }
-                 if(font instanceof XSSFFont) {
-                    System.out.print( renderColor( ((XSSFFont)font).getXSSFColor()) );
-                 }
-                 
-                 System.out.println();
-                 System.out.println("        " + formatter.formatCellValue(cell));
-              }
-           }
-           
-           System.out.println();
+        try (Workbook wb = WorkbookFactory.create(new File(args[0]))) {
+            DataFormatter formatter = new DataFormatter();
+
+            for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) {
+                Sheet sheet = wb.getSheetAt(sn);
+                System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());
+
+                for (Row row : sheet) {
+                    System.out.println("  Row " + row.getRowNum());
+
+                    for (Cell cell : row) {
+                        CellReference ref = new CellReference(cell);
+                        System.out.print("    " + ref.formatAsString());
+                        System.out.print(" (" + cell.getColumnIndex() + ") ");
+
+                        CellStyle style = cell.getCellStyle();
+                        System.out.print("Format=" + style.getDataFormatString() + " ");
+                        System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
+                        System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");
+
+                        Font font = wb.getFontAt(style.getFontIndex());
+                        System.out.print("Font=" + font.getFontName() + " ");
+                        System.out.print("FontColor=");
+                        if (font instanceof HSSFFont) {
+                            System.out.print(renderColor(((HSSFFont) font).getHSSFColor((HSSFWorkbook) wb)));
+                        }
+                        if (font instanceof XSSFFont) {
+                            System.out.print(renderColor(((XSSFFont) font).getXSSFColor()));
+                        }
+
+                        System.out.println();
+                        System.out.println("        " + formatter.formatCellValue(cell));
+                    }
+                }
+
+                System.out.println();
+            }
         }
-        
-        wb.close();
     }
     
     private static String renderColor(Color color) {
index e94a679e47f1795ec4ecfd1ee4bbe5b7790d18c0..992d0f0552da1fa28cade3c442ddbf0f65f08118 100644 (file)
@@ -74,22 +74,20 @@ public class SettingExternalFunction {
 
     public static void main( String[] args ) throws IOException {
 
-        Workbook wb = new XSSFWorkbook();  // or new HSSFWorkbook()
+        try (Workbook wb = new XSSFWorkbook()) {  // or new HSSFWorkbook()
 
-        // register the add-in
-        wb.addToolPack(new BloombergAddIn());
+            // register the add-in
+            wb.addToolPack(new BloombergAddIn());
 
-        Sheet sheet = wb.createSheet();
-        Row row = sheet.createRow(0);
-        row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100");
-        row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") ");
-        row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") ");
+            Sheet sheet = wb.createSheet();
+            Row row = sheet.createRow(0);
+            row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100");
+            row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") ");
+            row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") ");
 
-        FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx");
-        wb.write(out);
-        out.close();
-        
-        wb.close();
+            try (FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx")) {
+                wb.write(out);
+            }
+        }
     }
-
 }
index cfbc0941c05e3bc70d8d222c3cf37f3e103f657b..a76dbebf1d3f08f5df70b9b20860733e3a2a5add 100644 (file)
@@ -17,7 +17,6 @@
 package org.apache.poi.ss.examples.formula;
 
 import java.io.File ;
-import java.io.FileInputStream ;
 
 import org.apache.poi.ss.formula.functions.FreeRefFunction ;
 import org.apache.poi.ss.formula.udf.DefaultUDFFinder ;
@@ -50,33 +49,29 @@ public class UserDefinedFunctionExample {
         System.out.println( "cell: " + args[1] ) ;
         
         File workbookFile = new File( args[0] ) ;
-        
-        Workbook workbook = WorkbookFactory.create(workbookFile, null, true);
 
-        try {
-            String[] functionNames = { "calculatePayment" } ;
-            FreeRefFunction[] functionImpls = { new CalculateMortgage() } ;
-            
-            UDFFinder udfToolpack = new DefaultUDFFinder( functionNames, functionImpls ) ;
-    
+        try (Workbook workbook = WorkbookFactory.create(workbookFile, null, true)) {
+            String[] functionNames = {"calculatePayment"};
+            FreeRefFunction[] functionImpls = {new CalculateMortgage()};
+
+            UDFFinder udfToolpack = new DefaultUDFFinder(functionNames, functionImpls);
+
             // register the user-defined function in the workbook
             workbook.addToolPack(udfToolpack);
-    
+
             FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
-    
-            CellReference cr = new CellReference( args[1] ) ;
-            String sheetName = cr.getSheetName() ;
-            Sheet sheet = workbook.getSheet( sheetName ) ;
-            int rowIdx = cr.getRow() ;
-            int colIdx = cr.getCol() ;
-            Row row = sheet.getRow( rowIdx ) ;
-            Cell cell = row.getCell( colIdx ) ;
-            
-            CellValue value = evaluator.evaluate( cell ) ;
-            
-            System.out.println("returns value: " +  value ) ;
-        } finally {
-            workbook.close();
+
+            CellReference cr = new CellReference(args[1]);
+            String sheetName = cr.getSheetName();
+            Sheet sheet = workbook.getSheet(sheetName);
+            int rowIdx = cr.getRow();
+            int colIdx = cr.getCol();
+            Row row = sheet.getRow(rowIdx);
+            Cell cell = row.getCell(colIdx);
+
+            CellValue value = evaluator.evaluate(cell);
+
+            System.out.println("returns value: " + value);
         }
     }
 }
index ec8fe23428706f18053f44bb375ec6609c692651..5716679dbbf767030c2fd6f85a35687aafca16b2 100644 (file)
@@ -43,53 +43,52 @@ public final class DataExtraction {
         }
         
         FileInputStream is = new FileInputStream(args[0]);
-        XMLSlideShow ppt = new XMLSlideShow(is);
-        is.close();
+        try (XMLSlideShow ppt = new XMLSlideShow(is)) {
+            is.close();
 
-        // Get the document's embedded files.
-        for (PackagePart p : ppt.getAllEmbedds()) {
-            String type = p.getContentType();
-            // typically file name
-            String name = p.getPartName().getName();  
-            out.println("Embedded file ("+type+"): "+name);
-            
-            InputStream pIs = p.getInputStream();
-            // make sense of the part data
-            pIs.close();
-            
-        }
+            // Get the document's embedded files.
+            for (PackagePart p : ppt.getAllEmbedds()) {
+                String type = p.getContentType();
+                // typically file name
+                String name = p.getPartName().getName();
+                out.println("Embedded file (" + type + "): " + name);
 
-        // Get the document's embedded files.
-        for (XSLFPictureData data : ppt.getPictureData()) {
-            String type = data.getContentType();
-            String name = data.getFileName();
-            out.println("Picture ("+type+"): "+name);
+                InputStream pIs = p.getInputStream();
+                // make sense of the part data
+                pIs.close();
 
-            InputStream pIs = data.getInputStream();
-            // make sense of the image data
-            pIs.close();
-        }
+            }
 
-        // size of the canvas in points
-        Dimension pageSize = ppt.getPageSize();
-        out.println("Pagesize: "+pageSize);
-        
-        for(XSLFSlide slide : ppt.getSlides()) {
-            for(XSLFShape shape : slide){
-                if(shape instanceof XSLFTextShape) {
-                    XSLFTextShape txShape = (XSLFTextShape)shape;
-                    out.println(txShape.getText());
-                } else if (shape instanceof XSLFPictureShape){
-                    XSLFPictureShape pShape = (XSLFPictureShape)shape;
-                    XSLFPictureData pData = pShape.getPictureData();
-                    out.println(pData.getFileName());
-                } else {
-                    out.println("Process me: " + shape.getClass());
+            // Get the document's embedded files.
+            for (XSLFPictureData data : ppt.getPictureData()) {
+                String type = data.getContentType();
+                String name = data.getFileName();
+                out.println("Picture (" + type + "): " + name);
+
+                InputStream pIs = data.getInputStream();
+                // make sense of the image data
+                pIs.close();
+            }
+
+            // size of the canvas in points
+            Dimension pageSize = ppt.getPageSize();
+            out.println("Pagesize: " + pageSize);
+
+            for (XSLFSlide slide : ppt.getSlides()) {
+                for (XSLFShape shape : slide) {
+                    if (shape instanceof XSLFTextShape) {
+                        XSLFTextShape txShape = (XSLFTextShape) shape;
+                        out.println(txShape.getText());
+                    } else if (shape instanceof XSLFPictureShape) {
+                        XSLFPictureShape pShape = (XSLFPictureShape) shape;
+                        XSLFPictureData pData = pShape.getPictureData();
+                        out.println(pData.getFileName());
+                    } else {
+                        out.println("Process me: " + shape.getClass());
+                    }
                 }
             }
         }
-        
-        ppt.close();
     }
 
 }
index de48a7df4cc729212df9a504a01cfa2322775675..711f6fc21f94e7d2a3cab8b7c08aff6777bac2eb 100644 (file)
@@ -28,26 +28,22 @@ import java.io.FileOutputStream;
 public final class MergePresentations {
 
     public static void main(String args[]) throws Exception {
-        XMLSlideShow ppt = new XMLSlideShow();
-
-        try {
-            for (String arg : args){
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
+            for (String arg : args) {
                 FileInputStream is = new FileInputStream(arg);
                 XMLSlideShow src = new XMLSlideShow(is);
                 is.close();
-    
-                for(XSLFSlide srcSlide : src.getSlides()){
+
+                for (XSLFSlide srcSlide : src.getSlides()) {
                     ppt.createSlide().importContent(srcSlide);
                 }
-                
+
                 src.close();
             }
-    
-            FileOutputStream out = new FileOutputStream("merged.pptx");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("merged.pptx")) {
+                ppt.write(out);
+            }
         }
     }
 }
index 4ea36e56ec7cc2c43274530902051cdd26d22d64..9ba7461915be9de73f68d72a10bef3b3ff747b82 100644 (file)
@@ -62,104 +62,91 @@ public class PieChartDemo {
             return;
         }
 
-        BufferedReader modelReader = new BufferedReader(new FileReader(args[1]));
-        XMLSlideShow pptx = null;
-        try {
+        try (BufferedReader modelReader = new BufferedReader(new FileReader(args[1]))) {
             String chartTitle = modelReader.readLine();  // first line is chart title
-    
-            pptx = new XMLSlideShow(new FileInputStream(args[0]));
-            XSLFSlide slide = pptx.getSlides().get(0);
-    
-            // find chart in the slide
-            XSLFChart chart = null;
-            for(POIXMLDocumentPart part : slide.getRelations()){
-                if(part instanceof XSLFChart){
-                    chart = (XSLFChart) part;
-                    break;
-                }
-            }
-    
-            if(chart == null) throw new IllegalStateException("chart not found in the template");
-    
-            // embedded Excel workbook that holds the chart data
-            POIXMLDocumentPart xlsPart = chart.getRelations().get(0);
-            XSSFWorkbook wb = new XSSFWorkbook();
-            try {
-                XSSFSheet sheet = wb.createSheet();
-        
-                CTChart ctChart = chart.getCTChart();
-                CTPlotArea plotArea = ctChart.getPlotArea();
-        
-                CTPieChart pieChart = plotArea.getPieChartArray(0);
-                //Pie Chart Series
-                CTPieSer ser = pieChart.getSerArray(0);
-        
-                // Series Text
-                CTSerTx tx = ser.getTx();
-                tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle);
-                sheet.createRow(0).createCell(1).setCellValue(chartTitle);
-                String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString();
-                tx.getStrRef().setF(titleRef);
-        
-                // Category Axis Data
-                CTAxDataSource cat = ser.getCat();
-                CTStrData strData = cat.getStrRef().getStrCache();
-        
-                // Values
-                CTNumDataSource val = ser.getVal();
-                CTNumData numData = val.getNumRef().getNumCache();
-        
-                strData.setPtArray(null);  // unset old axis text
-                numData.setPtArray(null);  // unset old values
-        
-                // set model
-                int idx = 0;
-                int rownum = 1;
-                String ln;
-                while((ln = modelReader.readLine()) != null){
-                    String[] vals = ln.split("\\s+");
-                    CTNumVal numVal = numData.addNewPt();
-                    numVal.setIdx(idx);
-                    numVal.setV(vals[1]);
-        
-                    CTStrVal sVal = strData.addNewPt();
-                    sVal.setIdx(idx);
-                    sVal.setV(vals[0]);
-        
-                    idx++;
-                    XSSFRow row = sheet.createRow(rownum++);
-                    row.createCell(0).setCellValue(vals[0]);
-                    row.createCell(1).setCellValue(Double.valueOf(vals[1]));
-                }
-                numData.getPtCount().setVal(idx);
-                strData.getPtCount().setVal(idx);
-        
-                String numDataRange = new CellRangeAddress(1, rownum-1, 1, 1).formatAsString(sheet.getSheetName(), true);
-                val.getNumRef().setF(numDataRange);
-                String axisDataRange = new CellRangeAddress(1, rownum-1, 0, 0).formatAsString(sheet.getSheetName(), true);
-                cat.getStrRef().setF(axisDataRange);
-        
-                // updated the embedded workbook with the data
-                OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream();
-                try {
-                    wb.write(xlsOut);
-                } finally {
-                    xlsOut.close();
+
+            try (XMLSlideShow pptx = new XMLSlideShow(new FileInputStream(args[0]))) {
+                XSLFSlide slide = pptx.getSlides().get(0);
+
+                // find chart in the slide
+                XSLFChart chart = null;
+                for (POIXMLDocumentPart part : slide.getRelations()) {
+                    if (part instanceof XSLFChart) {
+                        chart = (XSLFChart) part;
+                        break;
+                    }
                 }
-        
-                // save the result
-                OutputStream out = new FileOutputStream("pie-chart-demo-output.pptx");
-                try {
-                    pptx.write(out);
-                } finally {
-                    out.close();
+
+                if (chart == null) throw new IllegalStateException("chart not found in the template");
+
+                // embedded Excel workbook that holds the chart data
+                POIXMLDocumentPart xlsPart = chart.getRelations().get(0);
+                try (XSSFWorkbook wb = new XSSFWorkbook()) {
+                    XSSFSheet sheet = wb.createSheet();
+
+                    CTChart ctChart = chart.getCTChart();
+                    CTPlotArea plotArea = ctChart.getPlotArea();
+
+                    CTPieChart pieChart = plotArea.getPieChartArray(0);
+                    //Pie Chart Series
+                    CTPieSer ser = pieChart.getSerArray(0);
+
+                    // Series Text
+                    CTSerTx tx = ser.getTx();
+                    tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle);
+                    sheet.createRow(0).createCell(1).setCellValue(chartTitle);
+                    String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString();
+                    tx.getStrRef().setF(titleRef);
+
+                    // Category Axis Data
+                    CTAxDataSource cat = ser.getCat();
+                    CTStrData strData = cat.getStrRef().getStrCache();
+
+                    // Values
+                    CTNumDataSource val = ser.getVal();
+                    CTNumData numData = val.getNumRef().getNumCache();
+
+                    strData.setPtArray(null);  // unset old axis text
+                    numData.setPtArray(null);  // unset old values
+
+                    // set model
+                    int idx = 0;
+                    int rownum = 1;
+                    String ln;
+                    while ((ln = modelReader.readLine()) != null) {
+                        String[] vals = ln.split("\\s+");
+                        CTNumVal numVal = numData.addNewPt();
+                        numVal.setIdx(idx);
+                        numVal.setV(vals[1]);
+
+                        CTStrVal sVal = strData.addNewPt();
+                        sVal.setIdx(idx);
+                        sVal.setV(vals[0]);
+
+                        idx++;
+                        XSSFRow row = sheet.createRow(rownum++);
+                        row.createCell(0).setCellValue(vals[0]);
+                        row.createCell(1).setCellValue(Double.valueOf(vals[1]));
+                    }
+                    numData.getPtCount().setVal(idx);
+                    strData.getPtCount().setVal(idx);
+
+                    String numDataRange = new CellRangeAddress(1, rownum - 1, 1, 1).formatAsString(sheet.getSheetName(), true);
+                    val.getNumRef().setF(numDataRange);
+                    String axisDataRange = new CellRangeAddress(1, rownum - 1, 0, 0).formatAsString(sheet.getSheetName(), true);
+                    cat.getStrRef().setF(axisDataRange);
+
+                    // updated the embedded workbook with the data
+                    try (OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream()) {
+                        wb.write(xlsOut);
+                    }
+
+                    // save the result
+                    try (OutputStream out = new FileOutputStream("pie-chart-demo-output.pptx")) {
+                        pptx.write(out);
+                    }
                 }
-            } finally {
-                wb.close();
             }
-        } finally {
-            if (pptx != null) pptx.close();
-            modelReader.close();
         }
     }
 }
index ed39f3051947fd01b425ceeb3edd447acb19861e..0a8d830bc4fe56d333f4ecb33c4f376030eb3d2a 100644 (file)
@@ -29,25 +29,24 @@ import java.io.IOException;
 public class Tutorial1 {
 
     public static void main(String[] args) throws IOException{
-        XMLSlideShow ppt = new XMLSlideShow();
-
-        try {
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
             // XSLFSlide#createSlide() with no arguments creates a blank slide
-            /*XSLFSlide blankSlide =*/ ppt.createSlide();
-    
-            
+            /*XSLFSlide blankSlide =*/
+            ppt.createSlide();
+
+
             XSLFSlideMaster master = ppt.getSlideMasters().get(0);
-    
+
             XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);
-            XSLFSlide slide1 = ppt.createSlide(layout1) ;
+            XSLFSlide slide1 = ppt.createSlide(layout1);
             XSLFTextShape[] ph1 = slide1.getPlaceholders();
             XSLFTextShape titlePlaceholder1 = ph1[0];
             titlePlaceholder1.setText("This is a title");
             XSLFTextShape subtitlePlaceholder1 = ph1[1];
             subtitlePlaceholder1.setText("this is a subtitle");
-    
+
             XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);
-            XSLFSlide slide2 = ppt.createSlide(layout2) ;
+            XSLFSlide slide2 = ppt.createSlide(layout2);
             XSLFTextShape[] ph2 = slide2.getPlaceholders();
             XSLFTextShape titlePlaceholder2 = ph2[0];
             titlePlaceholder2.setText("This is a title");
@@ -63,12 +62,10 @@ public class Tutorial1 {
             XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph();
             p3.setIndentLevel(2);
             p3.addNewTextRun().setText("Level3 text");
-    
-            FileOutputStream out = new FileOutputStream("slides.pptx");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("slides.pptx")) {
+                ppt.write(out);
+            }
         }
     }
 }
index 86ce72eba66d430ae233384d732084f75e08dde9..aaf48c3336589a829b82d8767c3a0fcb6530d8a3 100644 (file)
@@ -30,21 +30,19 @@ import java.io.IOException;
 public class Tutorial2 {
 
     public static void main(String[] args) throws IOException{
-        XMLSlideShow ppt = new XMLSlideShow();
-
-        try {
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
             XSLFSlide slide1 = ppt.createSlide();
             XSLFTextBox shape1 = slide1.createTextBox();
             // initial height of the text box is 100 pt but
             Rectangle anchor = new Rectangle(10, 100, 300, 100);
             shape1.setAnchor(anchor);
-    
+
             XSLFTextParagraph p1 = shape1.addNewTextParagraph();
             XSLFTextRun r1 = p1.addNewTextRun();
             r1.setText("Paragraph Formatting");
             r1.setFontSize(24d);
             r1.setFontColor(new Color(85, 142, 213));
-    
+
             XSLFTextParagraph p2 = shape1.addNewTextParagraph();
             // If spaceBefore >= 0, then space is a percentage of normal line height.
             // If spaceBefore < 0, the absolute value of linespacing is the spacing in points
@@ -53,14 +51,14 @@ public class Tutorial2 {
             XSLFTextRun r2 = p2.addNewTextRun();
             r2.setText("Paragraph  properties apply to all text residing within the corresponding paragraph.");
             r2.setFontSize(16d);
-    
+
             XSLFTextParagraph p3 = shape1.addNewTextParagraph();
-    
+
             XSLFTextRun r3 = p3.addNewTextRun();
             r3.setText("Run Formatting");
             r3.setFontSize(24d);
             r3.setFontColor(new Color(85, 142, 213));
-    
+
             XSLFTextParagraph p4 = shape1.addNewTextParagraph();
             p4.setSpaceBefore(-20d); // 20 pt from the previous paragraph
             p4.setSpaceAfter(300d); // 3 lines after the paragraph
@@ -68,18 +66,16 @@ public class Tutorial2 {
             r4.setFontSize(16d);
             r4.setText(
                     "Run level formatting is the most granular property level and allows " +
-                    "for the specifying of all low level text properties. The text run is " +
-                    "what all paragraphs are derived from and thus specifying various " +
-                    "properties per run will allow for a diversely formatted text paragraph.");
-    
+                            "for the specifying of all low level text properties. The text run is " +
+                            "what all paragraphs are derived from and thus specifying various " +
+                            "properties per run will allow for a diversely formatted text paragraph.");
+
             // resize the shape to fit text
             shape1.resizeToFitText();
-    
-            FileOutputStream out = new FileOutputStream("text.pptx");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("text.pptx")) {
+                ppt.write(out);
+            }
         }
     }
 }
index d561a9f5fdb7f74c7fbf47a07977f473d8f9bf52..4a81b83b8953253d1e77ed0dc4a9cb9e05465ef5 100644 (file)
@@ -31,21 +31,17 @@ import org.apache.poi.sl.usermodel.Placeholder;
 public class Tutorial3 {
 
     public static void main(String[] args) throws IOException{
-        XMLSlideShow ppt = new XMLSlideShow();
-
-        try {
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
             XSLFSlide slide = ppt.createSlide();
-    
+
             XSLFTextShape titleShape = slide.createTextBox();
             titleShape.setPlaceholder(Placeholder.TITLE);
             titleShape.setText("This is a slide title");
             titleShape.setAnchor(new Rectangle(50, 50, 400, 100));
-    
-            FileOutputStream out = new FileOutputStream("title.pptx");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("title.pptx")) {
+                ppt.write(out);
+            }
         }
     }
 }
index 3db718d679c5b2b04d208049cb1aa371f5cbbc4a..19d0cc98597ad16397a8e8eda626f1bffad44256 100644 (file)
@@ -33,60 +33,56 @@ import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;
 public class Tutorial4 {
 
     public static void main(String[] args) throws IOException{
-        XMLSlideShow ppt = new XMLSlideShow();
-
-        try {
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
             // XSLFSlide#createSlide() with no arguments creates a blank slide
             XSLFSlide slide = ppt.createSlide();
-    
+
             XSLFTable tbl = slide.createTable();
             tbl.setAnchor(new Rectangle(50, 50, 450, 300));
-    
+
             int numColumns = 3;
             int numRows = 5;
             XSLFTableRow headerRow = tbl.addRow();
             headerRow.setHeight(50);
             // header
-            for(int i = 0; i < numColumns; i++) {
+            for (int i = 0; i < numColumns; i++) {
                 XSLFTableCell th = headerRow.addCell();
                 XSLFTextParagraph p = th.addNewTextParagraph();
                 p.setTextAlign(TextAlign.CENTER);
                 XSLFTextRun r = p.addNewTextRun();
-                r.setText("Header " + (i+1));
+                r.setText("Header " + (i + 1));
                 r.setBold(true);
                 r.setFontColor(Color.white);
                 th.setFillColor(new Color(79, 129, 189));
                 th.setBorderWidth(BorderEdge.bottom, 2.0);
                 th.setBorderColor(BorderEdge.bottom, Color.white);
-    
+
                 tbl.setColumnWidth(i, 150);  // all columns are equally sized
             }
-            
+
             // rows
-            
-            for(int rownum = 0; rownum < numRows; rownum ++){
+
+            for (int rownum = 0; rownum < numRows; rownum++) {
                 XSLFTableRow tr = tbl.addRow();
                 tr.setHeight(50);
                 // header
-                for(int i = 0; i < numColumns; i++) {
+                for (int i = 0; i < numColumns; i++) {
                     XSLFTableCell cell = tr.addCell();
                     XSLFTextParagraph p = cell.addNewTextParagraph();
                     XSLFTextRun r = p.addNewTextRun();
-    
-                    r.setText("Cell " + (i+1));
-                    if(rownum % 2 == 0)
+
+                    r.setText("Cell " + (i + 1));
+                    if (rownum % 2 == 0)
                         cell.setFillColor(new Color(208, 216, 232));
                     else
                         cell.setFillColor(new Color(233, 247, 244));
-    
+
                 }
             }
-    
-            FileOutputStream out = new FileOutputStream("table.pptx");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("table.pptx")) {
+                ppt.write(out);
+            }
         }
     }
 }
index d5dbddf7326e816c15f275c4a4f2a41b7a4ae881..ccd25c53c9253717efb7b7c3fadbf859f730824e 100644 (file)
@@ -31,21 +31,18 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType;
 public class Tutorial5 {
 
     public static void main(String[] args) throws IOException{
-        XMLSlideShow ppt = new XMLSlideShow();
-
-        try {
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
             XSLFSlide slide = ppt.createSlide();
-    
+
             File img = new File(System.getProperty("POI.testdata.path", "test-data"), "slideshow/clock.jpg");
             XSLFPictureData pictureData = ppt.addPicture(img, PictureType.PNG);
-    
-            /*XSLFPictureShape shape =*/ slide.createPicture(pictureData);
-    
-            FileOutputStream out = new FileOutputStream("images.pptx");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            /*XSLFPictureShape shape =*/
+            slide.createPicture(pictureData);
+
+            try (FileOutputStream out = new FileOutputStream("images.pptx")) {
+                ppt.write(out);
+            }
         }
     }
 }
index 5eaff4541b9ae52aab57de5465fdf911c65a6596..56caa60ff28c6efa764cf02380efca5329a7a975 100644 (file)
@@ -29,33 +29,28 @@ import java.io.IOException;
 public class Tutorial6 {
 
     public static void main(String[] args) throws IOException{
-        XMLSlideShow ppt = new XMLSlideShow();
-
-        try {
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
             XSLFSlide slide1 = ppt.createSlide();
             XSLFSlide slide2 = ppt.createSlide();
-    
+
             XSLFTextBox shape1 = slide1.createTextBox();
             shape1.setAnchor(new Rectangle(50, 50, 200, 50));
             XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun();
             XSLFHyperlink link1 = r1.createHyperlink();
             r1.setText("http://poi.apache.org"); // visible text
             link1.setAddress("http://poi.apache.org");  // link address
-    
+
             XSLFTextBox shape2 = slide1.createTextBox();
             shape2.setAnchor(new Rectangle(300, 50, 200, 50));
             XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun();
             XSLFHyperlink link2 = r2.createHyperlink();
             r2.setText("Go to the second slide"); // visible text
             link2.linkToSlide(slide2);  // link address
-    
-    
-    
-            FileOutputStream out = new FileOutputStream("hyperlinks.pptx");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+
+            try (FileOutputStream out = new FileOutputStream("hyperlinks.pptx")) {
+                ppt.write(out);
+            }
         }
     }
 }
index 4fee5bafea560b16fcf8ef78f43f6534f67134e7..bc58d82a4eea385411b647522a09306a40b4fe4b 100644 (file)
@@ -32,19 +32,17 @@ import org.apache.poi.sl.usermodel.AutoNumberingScheme;
 public class Tutorial7 {
 
     public static void main(String[] args) throws IOException {
-        XMLSlideShow ppt = new XMLSlideShow();
-
-        try {
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
             XSLFSlide slide = ppt.createSlide();
             XSLFTextBox shape = slide.createTextBox();
             shape.setAnchor(new Rectangle(50, 50, 400, 200));
-    
+
             XSLFTextParagraph p1 = shape.addNewTextParagraph();
             p1.setIndentLevel(0);
             p1.setBullet(true);
             XSLFTextRun r1 = p1.addNewTextRun();
             r1.setText("Bullet1");
-    
+
             XSLFTextParagraph p2 = shape.addNewTextParagraph();
             // indentation before text
             p2.setLeftMargin(60d);
@@ -58,33 +56,31 @@ public class Tutorial7 {
             p2.setIndentLevel(1);
             XSLFTextRun r2 = p2.addNewTextRun();
             r2.setText("Bullet2");
-    
+
             // the next three paragraphs form an auto-numbered list
             XSLFTextParagraph p3 = shape.addNewTextParagraph();
             p3.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
             p3.setIndentLevel(2);
             XSLFTextRun r3 = p3.addNewTextRun();
             r3.setText("Numbered List Item - 1");
-    
+
             XSLFTextParagraph p4 = shape.addNewTextParagraph();
             p4.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 2);
             p4.setIndentLevel(2);
             XSLFTextRun r4 = p4.addNewTextRun();
             r4.setText("Numbered List Item - 2");
-    
+
             XSLFTextParagraph p5 = shape.addNewTextParagraph();
             p5.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 3);
             p5.setIndentLevel(2);
             XSLFTextRun r5 = p5.addNewTextRun();
             r5.setText("Numbered List Item - 3");
-    
+
             shape.resizeToFitText();
-    
-            FileOutputStream out = new FileOutputStream("list.pptx");
-            ppt.write(out);
-            out.close();
-        } finally {
-            ppt.close();
+
+            try (FileOutputStream out = new FileOutputStream("list.pptx")) {
+                ppt.write(out);
+            }
         }
     }
 }
index 8552ff943efa67b52e0be912f798384039c9bb51..13fc96ce59973a7cd5add515015514f154169a65 100644 (file)
@@ -40,31 +40,30 @@ public class Step1 {
         }
 
         FileInputStream fis = new FileInputStream(args[0]);
-        XMLSlideShow ppt = new XMLSlideShow(fis);
-        fis.close();
+        try (XMLSlideShow ppt = new XMLSlideShow(fis)) {
+            fis.close();
 
-        for(XSLFSlide slide : ppt.getSlides()){
-            System.out.println("Title: " + slide.getTitle());
+            for (XSLFSlide slide : ppt.getSlides()) {
+                System.out.println("Title: " + slide.getTitle());
 
-            for(XSLFShape shape : slide.getShapes()){
-                if(shape instanceof XSLFTextShape) {
-                    XSLFTextShape tsh = (XSLFTextShape)shape;
-                    for(XSLFTextParagraph p : tsh){
-                        System.out.println("Paragraph level: " + p.getIndentLevel());
-                        for(XSLFTextRun r : p){
-                            System.out.println(r.getRawText());
-                            System.out.println("  bold: " + r.isBold());
-                            System.out.println("  italic: " + r.isItalic());
-                            System.out.println("  underline: " + r.isUnderlined());
-                            System.out.println("  font.family: " + r.getFontFamily());
-                            System.out.println("  font.size: " + r.getFontSize());
-                            System.out.println("  font.color: " + r.getFontColor());
+                for (XSLFShape shape : slide.getShapes()) {
+                    if (shape instanceof XSLFTextShape) {
+                        XSLFTextShape tsh = (XSLFTextShape) shape;
+                        for (XSLFTextParagraph p : tsh) {
+                            System.out.println("Paragraph level: " + p.getIndentLevel());
+                            for (XSLFTextRun r : p) {
+                                System.out.println(r.getRawText());
+                                System.out.println("  bold: " + r.isBold());
+                                System.out.println("  italic: " + r.isItalic());
+                                System.out.println("  underline: " + r.isUnderlined());
+                                System.out.println("  font.family: " + r.getFontFamily());
+                                System.out.println("  font.size: " + r.getFontSize());
+                                System.out.println("  font.color: " + r.getFontColor());
+                            }
                         }
                     }
                 }
             }
         }
-        
-        ppt.close();
     }
 }
index 792f7554539a716a793add98b9416dd4646ae4e5..a989ef28cf8a710da4b9dccb77343a4838f23c04 100644 (file)
@@ -33,45 +33,45 @@ import java.io.FileOutputStream;
  */
 public class Step2 {
     public static void main(String[] args) throws Exception{
-        XMLSlideShow ppt = new XMLSlideShow();
+        try (XMLSlideShow ppt = new XMLSlideShow()) {
 
-        // first see what slide layouts are available by default
-        System.out.println("Available slide layouts:");
-        for(XSLFSlideMaster master : ppt.getSlideMasters()){
-            for(XSLFSlideLayout layout : master.getSlideLayouts()){
-                System.out.println(layout.getType());
+            // first see what slide layouts are available by default
+            System.out.println("Available slide layouts:");
+            for (XSLFSlideMaster master : ppt.getSlideMasters()) {
+                for (XSLFSlideLayout layout : master.getSlideLayouts()) {
+                    System.out.println(layout.getType());
+                }
             }
-        }
-
-        // blank slide
-        /*XSLFSlide blankSlide =*/ ppt.createSlide();
 
-        XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);
+            // blank slide
+        /*XSLFSlide blankSlide =*/
+            ppt.createSlide();
 
-        // title slide
-        XSLFSlideLayout titleLayout = defaultMaster.getLayout(SlideLayout.TITLE);
-        XSLFSlide slide1 = ppt.createSlide(titleLayout);
-        XSLFTextShape title1 = slide1.getPlaceholder(0);
-        title1.setText("First Title");
+            XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);
 
-        // title and content
-        XSLFSlideLayout titleBodyLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
-        XSLFSlide slide2 = ppt.createSlide(titleBodyLayout);
+            // title slide
+            XSLFSlideLayout titleLayout = defaultMaster.getLayout(SlideLayout.TITLE);
+            XSLFSlide slide1 = ppt.createSlide(titleLayout);
+            XSLFTextShape title1 = slide1.getPlaceholder(0);
+            title1.setText("First Title");
 
-        XSLFTextShape title2 = slide2.getPlaceholder(0);
-        title2.setText("Second Title");
+            // title and content
+            XSLFSlideLayout titleBodyLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
+            XSLFSlide slide2 = ppt.createSlide(titleBodyLayout);
 
-        XSLFTextShape body2 = slide2.getPlaceholder(1);
-        body2.clearText(); // unset any existing text
-        body2.addNewTextParagraph().addNewTextRun().setText("First paragraph");
-        body2.addNewTextParagraph().addNewTextRun().setText("Second paragraph");
-        body2.addNewTextParagraph().addNewTextRun().setText("Third paragraph");
+            XSLFTextShape title2 = slide2.getPlaceholder(0);
+            title2.setText("Second Title");
 
+            XSLFTextShape body2 = slide2.getPlaceholder(1);
+            body2.clearText(); // unset any existing text
+            body2.addNewTextParagraph().addNewTextRun().setText("First paragraph");
+            body2.addNewTextParagraph().addNewTextRun().setText("Second paragraph");
+            body2.addNewTextParagraph().addNewTextRun().setText("Third paragraph");
 
 
-        FileOutputStream out = new FileOutputStream("step2.pptx");
-        ppt.write(out);
-        out.close();
-        ppt.close();
+            try (FileOutputStream out = new FileOutputStream("step2.pptx")) {
+                ppt.write(out);
+            }
+        }
     }
 }
index 98773eaa5678352ea7f5c049fae65cbeb433458d..3b91385c212ba2ca61e89a9de136453e5fe80471 100644 (file)
@@ -42,8 +42,7 @@ import org.xml.sax.helpers.XMLReaderFactory;
  */
 public class FromHowTo {
        public void processFirstSheet(String filename) throws Exception {
-               OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
-               try {
+               try (OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ)) {
                        XSSFReader r = new XSSFReader(pkg);
                        SharedStringsTable sst = r.getSharedStringsTable();
 
@@ -54,14 +53,11 @@ public class FromHowTo {
                        InputSource sheetSource = new InputSource(sheet2);
                        parser.parse(sheetSource);
                        sheet2.close();
-               } finally {
-                       pkg.close();
                }
        }
 
        public void processAllSheets(String filename) throws Exception {
-               OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
-               try {
+               try (OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ)) {
                        XSSFReader r = new XSSFReader(pkg);
                        SharedStringsTable sst = r.getSharedStringsTable();
 
@@ -76,8 +72,6 @@ public class FromHowTo {
                                sheet.close();
                                System.out.println("");
                        }
-               } finally {
-                       pkg.close();
                }
        }
 
index 4c0b35c8546b731bf79ca5c4ab74c246880e6aab..7c892a89a8b4c8b9848879ac737c8f04bbfde987 100644 (file)
@@ -31,26 +31,24 @@ public class Outlining {
        }
 
        private void collapseRow() throws IOException {
-               SXSSFWorkbook wb2 = new SXSSFWorkbook(100);
-               SXSSFSheet sheet2 = wb2.createSheet("new sheet");
+               try (SXSSFWorkbook wb2 = new SXSSFWorkbook(100)) {
+                       SXSSFSheet sheet2 = wb2.createSheet("new sheet");
 
-               int rowCount = 20;
-               for (int i = 0; i < rowCount; i++) {
-                       sheet2.createRow(i);
-               }
+                       int rowCount = 20;
+                       for (int i = 0; i < rowCount; i++) {
+                               sheet2.createRow(i);
+                       }
 
-               sheet2.groupRow(4, 9);
-               sheet2.groupRow(11, 19);
+                       sheet2.groupRow(4, 9);
+                       sheet2.groupRow(11, 19);
 
-               sheet2.setRowGroupCollapsed(4, true);
+                       sheet2.setRowGroupCollapsed(4, true);
 
-               FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx");
-               try {
-                   wb2.write(fileOut);
-               } finally {
-               fileOut.close();
-               wb2.dispose();
-               wb2.close();
+                       try (FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx")) {
+                               wb2.write(fileOut);
+                       } finally {
+                               wb2.dispose();
+                       }
                }
        }
 }
index 05e653ee397a97fce16e895f0d536e69f59819a1..bee89d1dfbd337dc0e180eb6729410364f555c60 100644 (file)
@@ -45,34 +45,33 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl;
 public class AligningCells {
 
     public static void main(String[] args) throws IOException {
-        XSSFWorkbook wb = new XSSFWorkbook();
-
-        XSSFSheet sheet = wb.createSheet();
-        XSSFRow row = sheet.createRow(2);
-        row.setHeightInPoints(30);
-        for (int i = 0; i < 8; i++) {
-            //column width is set in units of 1/256th of a character width
-            sheet.setColumnWidth(i, 256 * 15);
+        try (XSSFWorkbook wb = new XSSFWorkbook()) {
+
+            XSSFSheet sheet = wb.createSheet();
+            XSSFRow row = sheet.createRow(2);
+            row.setHeightInPoints(30);
+            for (int i = 0; i < 8; i++) {
+                //column width is set in units of 1/256th of a character width
+                sheet.setColumnWidth(i, 256 * 15);
+            }
+
+            createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
+            createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
+            createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
+            createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
+            createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
+            createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
+            createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
+
+            //center text over B4, C4, D4
+            row = sheet.createRow(3);
+            centerAcrossSelection(wb, row, 1, 3, VerticalAlignment.CENTER);
+
+            // Write the output to a file
+            try (OutputStream fileOut = new FileOutputStream("xssf-align.xlsx")) {
+                wb.write(fileOut);
+            }
         }
-
-        createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
-        createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
-        createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
-        createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
-        createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
-        createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
-        createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
-
-        //center text over B4, C4, D4
-        row = sheet.createRow(3);
-        centerAcrossSelection(wb, row, 1, 3, VerticalAlignment.CENTER);
-
-        // Write the output to a file
-        OutputStream fileOut = new FileOutputStream("xssf-align.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        
-        wb.close();
     }
 
     /**
index 69dc765033f1e5af6fb277bcd436e44afea52163..a005f16781e3fb77dc826cb51129d8d7a7a75b56 100644 (file)
@@ -86,30 +86,29 @@ public class BigGridDemo {
         // Step 1. Create a template file. Setup sheets and workbook-level objects such as
         // cell styles, number formats, etc.
 
-        XSSFWorkbook wb = new XSSFWorkbook();
-        XSSFSheet sheet = wb.createSheet("Big Grid");
-
-        Map<String, XSSFCellStyle> styles = createStyles(wb);
-        //name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml
-        String sheetRef = sheet.getPackagePart().getPartName().getName();
-
-        //save the template
-        FileOutputStream os = new FileOutputStream("template.xlsx");
-        wb.write(os);
-        os.close();
-
-        //Step 2. Generate XML file.
-        File tmp = File.createTempFile("sheet", ".xml");
-        Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING);
-        generate(fw, styles);
-        fw.close();
-
-        //Step 3. Substitute the template entry with the generated data
-        FileOutputStream out = new FileOutputStream("big-grid.xlsx");
-        substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out);
-        out.close();
-        
-        wb.close();
+        try (XSSFWorkbook wb = new XSSFWorkbook()) {
+            XSSFSheet sheet = wb.createSheet("Big Grid");
+
+            Map<String, XSSFCellStyle> styles = createStyles(wb);
+            //name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml
+            String sheetRef = sheet.getPackagePart().getPartName().getName();
+
+            //save the template
+            FileOutputStream os = new FileOutputStream("template.xlsx");
+            wb.write(os);
+            os.close();
+
+            //Step 2. Generate XML file.
+            File tmp = File.createTempFile("sheet", ".xml");
+            Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING);
+            generate(fw, styles);
+            fw.close();
+
+            //Step 3. Substitute the template entry with the generated data
+            try (FileOutputStream out = new FileOutputStream("big-grid.xlsx")) {
+                substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out);
+            }
+        }
     }
 
     /**
@@ -194,28 +193,23 @@ public class BigGridDemo {
      * @param out the stream to write the result to
      */
     private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException {
-        ZipFile zip = ZipHelper.openZipFile(zipfile);
-        try {
-            ZipOutputStream zos = new ZipOutputStream(out);
-    
-            Enumeration<? extends ZipEntry> en = zip.entries();
-            while (en.hasMoreElements()) {
-                ZipEntry ze = en.nextElement();
-                if(!ze.getName().equals(entry)){
-                    zos.putNextEntry(new ZipEntry(ze.getName()));
-                    InputStream is = zip.getInputStream(ze);
+        try (ZipFile zip = ZipHelper.openZipFile(zipfile)) {
+            try (ZipOutputStream zos = new ZipOutputStream(out)) {
+                Enumeration<? extends ZipEntry> en = zip.entries();
+                while (en.hasMoreElements()) {
+                    ZipEntry ze = en.nextElement();
+                    if (!ze.getName().equals(entry)) {
+                        zos.putNextEntry(new ZipEntry(ze.getName()));
+                        try (InputStream is = zip.getInputStream(ze)) {
+                            copyStream(is, zos);
+                        }
+                    }
+                }
+                zos.putNextEntry(new ZipEntry(entry));
+                try (InputStream is = new FileInputStream(tmpfile)) {
                     copyStream(is, zos);
-                    is.close();
                 }
             }
-            zos.putNextEntry(new ZipEntry(entry));
-            InputStream is = new FileInputStream(tmpfile);
-            copyStream(is, zos);
-            is.close();
-    
-            zos.close();
-        } finally {
-            zip.close();
         }
     }
 
index 99c3c49758df3c53f613bec1eb3efc0158dd1355..ac0dfc0835056f9f4a310af2155880b32772c8f7 100644 (file)
@@ -55,80 +55,80 @@ public class CalendarDemo {
 
         int year = calendar.get(Calendar.YEAR);
 
-        XSSFWorkbook wb = new XSSFWorkbook();
-        Map<String, XSSFCellStyle> styles = createStyles(wb);
-
-        for (int month = 0; month < 12; month++) {
-            calendar.set(Calendar.MONTH, month);
-            calendar.set(Calendar.DAY_OF_MONTH, 1);
-            //create a sheet for each month
-            XSSFSheet sheet = wb.createSheet(months[month]);
-
-            //turn off gridlines
-            sheet.setDisplayGridlines(false);
-            sheet.setPrintGridlines(false);
-            XSSFPrintSetup printSetup = sheet.getPrintSetup();
-            printSetup.setOrientation(PrintOrientation.LANDSCAPE);
-            sheet.setFitToPage(true);
-            sheet.setHorizontallyCenter(true);
-
-            //the header row: centered text in 48pt font
-            XSSFRow headerRow = sheet.createRow(0);
-            headerRow.setHeightInPoints(80);
-            XSSFCell titleCell = headerRow.createCell(0);
-            titleCell.setCellValue(months[month] + " " + year);
-            titleCell.setCellStyle(styles.get("title"));
-            sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
-
-            //header with month titles
-            XSSFRow monthRow = sheet.createRow(1);
-            for (int i = 0; i < days.length; i++) {
-                //for compatibility with HSSF we have to set column width in units of 1/256th of a character width
-                sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide
-                sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide
-                sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1));
-                XSSFCell monthCell = monthRow.createCell(i*2);
-                monthCell.setCellValue(days[i]);
-                monthCell.setCellStyle(styles.get("month"));
-            }
-
-            int cnt = 1, day=1;
-            int rownum = 2;
-            for (int j = 0; j < 6; j++) {
-                XSSFRow row = sheet.createRow(rownum++);
-                row.setHeightInPoints(100);
+        try (XSSFWorkbook wb = new XSSFWorkbook()) {
+            Map<String, XSSFCellStyle> styles = createStyles(wb);
+
+            for (int month = 0; month < 12; month++) {
+                calendar.set(Calendar.MONTH, month);
+                calendar.set(Calendar.DAY_OF_MONTH, 1);
+                //create a sheet for each month
+                XSSFSheet sheet = wb.createSheet(months[month]);
+
+                //turn off gridlines
+                sheet.setDisplayGridlines(false);
+                sheet.setPrintGridlines(false);
+                XSSFPrintSetup printSetup = sheet.getPrintSetup();
+                printSetup.setOrientation(PrintOrientation.LANDSCAPE);
+                sheet.setFitToPage(true);
+                sheet.setHorizontallyCenter(true);
+
+                //the header row: centered text in 48pt font
+                XSSFRow headerRow = sheet.createRow(0);
+                headerRow.setHeightInPoints(80);
+                XSSFCell titleCell = headerRow.createCell(0);
+                titleCell.setCellValue(months[month] + " " + year);
+                titleCell.setCellStyle(styles.get("title"));
+                sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
+
+                //header with month titles
+                XSSFRow monthRow = sheet.createRow(1);
                 for (int i = 0; i < days.length; i++) {
-                    XSSFCell dayCell_1 = row.createCell(i*2);
-                    XSSFCell dayCell_2 = row.createCell(i*2 + 1);
-
-                    int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
-                    if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
-                        dayCell_1.setCellValue(day);
-                        calendar.set(Calendar.DAY_OF_MONTH, ++day);
+                    //for compatibility with HSSF we have to set column width in units of 1/256th of a character width
+                    sheet.setColumnWidth(i * 2, 5 * 256); //the column is 5 characters wide
+                    sheet.setColumnWidth(i * 2 + 1, 13 * 256); //the column is 13 characters wide
+                    sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1));
+                    XSSFCell monthCell = monthRow.createCell(i * 2);
+                    monthCell.setCellValue(days[i]);
+                    monthCell.setCellStyle(styles.get("month"));
+                }
 
-                        if(i == 0 || i == days.length-1) {
-                            dayCell_1.setCellStyle(styles.get("weekend_left"));
-                            dayCell_2.setCellStyle(styles.get("weekend_right"));
+                int cnt = 1, day = 1;
+                int rownum = 2;
+                for (int j = 0; j < 6; j++) {
+                    XSSFRow row = sheet.createRow(rownum++);
+                    row.setHeightInPoints(100);
+                    for (int i = 0; i < days.length; i++) {
+                        XSSFCell dayCell_1 = row.createCell(i * 2);
+                        XSSFCell dayCell_2 = row.createCell(i * 2 + 1);
+
+                        int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
+                        if (cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
+                            dayCell_1.setCellValue(day);
+                            calendar.set(Calendar.DAY_OF_MONTH, ++day);
+
+                            if (i == 0 || i == days.length - 1) {
+                                dayCell_1.setCellStyle(styles.get("weekend_left"));
+                                dayCell_2.setCellStyle(styles.get("weekend_right"));
+                            } else {
+                                dayCell_1.setCellStyle(styles.get("workday_left"));
+                                dayCell_2.setCellStyle(styles.get("workday_right"));
+                            }
                         } else {
-                            dayCell_1.setCellStyle(styles.get("workday_left"));
-                            dayCell_2.setCellStyle(styles.get("workday_right"));
+                            dayCell_1.setCellStyle(styles.get("grey_left"));
+                            dayCell_2.setCellStyle(styles.get("grey_right"));
                         }
-                    } else {
-                        dayCell_1.setCellStyle(styles.get("grey_left"));
-                        dayCell_2.setCellStyle(styles.get("grey_right"));
+                        cnt++;
                     }
-                    cnt++;
+                    if (calendar.get(Calendar.MONTH) > month) break;
                 }
-                if(calendar.get(Calendar.MONTH) > month) break;
             }
-        }
 
-        // Write the output to a file
-        FileOutputStream out = new FileOutputStream("calendar-"+year+".xlsx");
-        wb.write(out);
-        out.close();
-        
-        wb.close();
+            // Write the output to a file
+            try (FileOutputStream out = new FileOutputStream("calendar-" + year + ".xlsx")) {
+                wb.write(out);
+            }
+
+        }
     }
 
     /**
index e2eab81f53a1968415e5fec95be5c29bc293d891..40f490520bed0b22ecc348b4ce38acb622f62252 100644 (file)
@@ -44,47 +44,45 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  */
 public class CellComments {
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook();
+        try (Workbook wb = new XSSFWorkbook()) {
 
-        CreationHelper factory = wb.getCreationHelper();
+            CreationHelper factory = wb.getCreationHelper();
 
-        Sheet sheet = wb.createSheet();
+            Sheet sheet = wb.createSheet();
 
-        Cell cell1 = sheet.createRow(3).createCell(5);
-        cell1.setCellValue("F4");
+            Cell cell1 = sheet.createRow(3).createCell(5);
+            cell1.setCellValue("F4");
 
-        Drawing<?> drawing = sheet.createDrawingPatriarch();
+            Drawing<?> drawing = sheet.createDrawingPatriarch();
 
-        ClientAnchor anchor = factory.createClientAnchor();
+            ClientAnchor anchor = factory.createClientAnchor();
 
-        Comment comment1 = drawing.createCellComment(anchor);
-        RichTextString str1 = factory.createRichTextString("Hello, World!");
-        comment1.setString(str1);
-        comment1.setAuthor("Apache POI");
-        cell1.setCellComment(comment1);
+            Comment comment1 = drawing.createCellComment(anchor);
+            RichTextString str1 = factory.createRichTextString("Hello, World!");
+            comment1.setString(str1);
+            comment1.setAuthor("Apache POI");
+            cell1.setCellComment(comment1);
 
-        Cell cell2 = sheet.createRow(2).createCell(2);
-        cell2.setCellValue("C3");
+            Cell cell2 = sheet.createRow(2).createCell(2);
+            cell2.setCellValue("C3");
 
-        Comment comment2 = drawing.createCellComment(anchor);
-        RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
-        //apply custom font to the text in the comment
-        Font font = wb.createFont();
-        font.setFontName("Arial");
-        font.setFontHeightInPoints((short)14);
-        font.setBold(true);
-        font.setColor(IndexedColors.RED.getIndex());
-        str2.applyFont(font);
+            Comment comment2 = drawing.createCellComment(anchor);
+            RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
+            //apply custom font to the text in the comment
+            Font font = wb.createFont();
+            font.setFontName("Arial");
+            font.setFontHeightInPoints((short) 14);
+            font.setBold(true);
+            font.setColor(IndexedColors.RED.getIndex());
+            str2.applyFont(font);
 
-        comment2.setString(str2);
-        comment2.setAuthor("Apache POI");
-        comment2.setAddress(new CellAddress("C3"));
+            comment2.setString(str2);
+            comment2.setAuthor("Apache POI");
+            comment2.setAddress(new CellAddress("C3"));
 
-        String fname = "comments.xlsx";
-        FileOutputStream out = new FileOutputStream(fname);
-        wb.write(out);
-        out.close();
-
-        wb.close();
+            try (FileOutputStream out = new FileOutputStream("comments.xlsx")) {
+                wb.write(out);
+            }
+        }
     }
 }
index b84814f1be7a9a872397dc3e130fce64b8fbe2ec..27bc0601f1f239257c8877ab0e354b98055a9756 100644 (file)
@@ -36,54 +36,53 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  */
 public class CreateCell {
 
-
-       public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
-        CreationHelper creationHelper = wb.getCreationHelper();
-        Sheet sheet = wb.createSheet("new sheet");
-
-        // Create a row and put some cells in it. Rows are 0 based.
-        Row row = sheet.createRow((short)0);
-        // Create a cell and put a value in it.
-        Cell cell = row.createCell((short)0);
-        cell.setCellValue(1);
-
-        //numeric value
-        row.createCell(1).setCellValue(1.2);
-
-        //plain string value
-        row.createCell(2).setCellValue("This is a string cell");
-
-        //rich text string
-        RichTextString str = creationHelper.createRichTextString("Apache");
-        Font font = wb.createFont();
-        font.setItalic(true);
-        font.setUnderline(Font.U_SINGLE);
-        str.applyFont(font);
-        row.createCell(3).setCellValue(str);
-
-        //boolean value
-        row.createCell(4).setCellValue(true);
-
-        //formula
-        row.createCell(5).setCellFormula("SUM(A1:B1)");
-
-        //date
-        CellStyle style = wb.createCellStyle();
-        style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
-        cell = row.createCell(6);
-        cell.setCellValue(new Date());
-        cell.setCellStyle(style);
-
-        //hyperlink
-        row.createCell(7).setCellFormula("SUM(A1:B1)");
-        cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")");
-
-
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
-       }
+    public static void main(String[] args) throws IOException {
+        try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
+            CreationHelper creationHelper = wb.getCreationHelper();
+            Sheet sheet = wb.createSheet("new sheet");
+
+            // Create a row and put some cells in it. Rows are 0 based.
+            Row row = sheet.createRow((short) 0);
+            // Create a cell and put a value in it.
+            Cell cell = row.createCell((short) 0);
+            cell.setCellValue(1);
+
+            //numeric value
+            row.createCell(1).setCellValue(1.2);
+
+            //plain string value
+            row.createCell(2).setCellValue("This is a string cell");
+
+            //rich text string
+            RichTextString str = creationHelper.createRichTextString("Apache");
+            Font font = wb.createFont();
+            font.setItalic(true);
+            font.setUnderline(Font.U_SINGLE);
+            str.applyFont(font);
+            row.createCell(3).setCellValue(str);
+
+            //boolean value
+            row.createCell(4).setCellValue(true);
+
+            //formula
+            row.createCell(5).setCellFormula("SUM(A1:B1)");
+
+            //date
+            CellStyle style = wb.createCellStyle();
+            style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
+            cell = row.createCell(6);
+            cell.setCellValue(new Date());
+            cell.setCellStyle(style);
+
+            //hyperlink
+            row.createCell(7).setCellFormula("SUM(A1:B1)");
+            cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")");
+
+
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
+    }
 }
index a855feedae47d1922f57d9ad8ac173ad58339720..a048ae4014aba31c350776043fb606fe1121adce 100644 (file)
@@ -34,31 +34,31 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class CreatePivotTable {
 
     public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
-        XSSFWorkbook wb = new XSSFWorkbook();
-        XSSFSheet sheet = wb.createSheet();
+        try (XSSFWorkbook wb = new XSSFWorkbook()) {
+            XSSFSheet sheet = wb.createSheet();
 
-        //Create some data to build the pivot table on
-        setCellData(sheet);
+            //Create some data to build the pivot table on
+            setCellData(sheet);
 
-        AreaReference source = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
-        CellReference position = new CellReference("H5");
-        // Create a pivot table on this sheet, with H5 as the top-left cell..
-        // The pivot table's data source is on the same sheet in A1:D4
-        XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
-        //Configure the pivot table
-        //Use first column as row label
-        pivotTable.addRowLabel(0);
-        //Sum up the second column
-        pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
-        //Set the third column as filter
-        pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
-        //Add filter on forth column
-        pivotTable.addReportFilter(3);
+            AreaReference source = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
+            CellReference position = new CellReference("H5");
+            // Create a pivot table on this sheet, with H5 as the top-left cell..
+            // The pivot table's data source is on the same sheet in A1:D4
+            XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
+            //Configure the pivot table
+            //Use first column as row label
+            pivotTable.addRowLabel(0);
+            //Sum up the second column
+            pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
+            //Set the third column as filter
+            pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
+            //Add filter on forth column
+            pivotTable.addReportFilter(3);
 
-        FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 
     public static void setCellData(XSSFSheet sheet){
index 316b8f8a223b4ddef5d4c6fa295cbbdd3dd5284f..27ff990c37bd9b0abd8ac3dd51805703161cf318 100644 (file)
@@ -38,32 +38,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class CreatePivotTable2 {
 
     public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
-        XSSFWorkbook wb = new XSSFWorkbook();
-        XSSFSheet sheet = wb.createSheet();
-
-        //Create some data to build the pivot table on
-        setCellData(sheet);
-
-        AreaReference source = new AreaReference("A1:E7", SpreadsheetVersion.EXCEL2007);
-        CellReference position = new CellReference("H1");
-        // Create a pivot table on this sheet, with H1 as the top-left cell..
-        // The pivot table's data source is on the same sheet in A1:E7
-        XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
-        //Configure the pivot table
-        //Use first column as row label
-        pivotTable.addRowLabel(0);
-        //Sum up the second column with column title and data format
-        pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1, "Values", "#,##0.00");
-        //Use third column (month) as columns (side by side)
-        pivotTable.addColLabel(3, "DD.MM.YYYY");
-
-        //Add filter on forth column
-        pivotTable.addReportFilter(4);
-
-        FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable2.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+        try (XSSFWorkbook wb = new XSSFWorkbook()) {
+            XSSFSheet sheet = wb.createSheet();
+
+            //Create some data to build the pivot table on
+            setCellData(sheet);
+
+            AreaReference source = new AreaReference("A1:E7", SpreadsheetVersion.EXCEL2007);
+            CellReference position = new CellReference("H1");
+            // Create a pivot table on this sheet, with H1 as the top-left cell..
+            // The pivot table's data source is on the same sheet in A1:E7
+            XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
+            //Configure the pivot table
+            //Use first column as row label
+            pivotTable.addRowLabel(0);
+            //Sum up the second column with column title and data format
+            pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1, "Values", "#,##0.00");
+            //Use third column (month) as columns (side by side)
+            pivotTable.addColLabel(3, "DD.MM.YYYY");
+
+            //Add filter on forth column
+            pivotTable.addReportFilter(4);
+
+            try (FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable2.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 
     public static void setCellData(XSSFSheet sheet){
index c0b1d395365d064c12cd832c0c937442987a7e22..e1905f5be25d790d5c0f3ad9cad969d9e83705ad 100644 (file)
@@ -36,58 +36,58 @@ public class CreateTable {
         
     public static void main(String[] args) throws IOException {
         
-        Workbook wb = new XSSFWorkbook();
-        XSSFSheet sheet = (XSSFSheet) wb.createSheet();
-        
-        // Create 
-        XSSFTable table = sheet.createTable();
-        table.setName("Test");
-        table.setDisplayName("Test_Table");
-        
-        // For now, create the initial style in a low-level way
-        table.getCTTable().addNewTableStyleInfo();
-        table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
-        
-        // Style the table
-        XSSFTableStyleInfo style = (XSSFTableStyleInfo)table.getStyle();
-        style.setName("TableStyleMedium2");
-        style.setShowColumnStripes(false);
-        style.setShowRowStripes(true);
-        style.setFirstColumn(false);
-        style.setLastColumn(false);
-        style.setShowRowStripes(true);
-        style.setShowColumnStripes(true);
-        
-        // Set the values for the table
-        XSSFRow row;
-        XSSFCell cell;
-        for(int i=0; i<3; i++) {
-            // Create row
-            row = sheet.createRow(i);
-            for(int j=0; j<3; j++) {
-                // Create cell
-                cell = row.createCell(j);
-                if(i == 0) {
-                    cell.setCellValue("Column"+(j+1));
-                } else {
-                    cell.setCellValue((i+1)*(j+1));
+        try (Workbook wb = new XSSFWorkbook()) {
+            XSSFSheet sheet = (XSSFSheet) wb.createSheet();
+
+            // Create
+            XSSFTable table = sheet.createTable();
+            table.setName("Test");
+            table.setDisplayName("Test_Table");
+
+            // For now, create the initial style in a low-level way
+            table.getCTTable().addNewTableStyleInfo();
+            table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
+
+            // Style the table
+            XSSFTableStyleInfo style = (XSSFTableStyleInfo) table.getStyle();
+            style.setName("TableStyleMedium2");
+            style.setShowColumnStripes(false);
+            style.setShowRowStripes(true);
+            style.setFirstColumn(false);
+            style.setLastColumn(false);
+            style.setShowRowStripes(true);
+            style.setShowColumnStripes(true);
+
+            // Set the values for the table
+            XSSFRow row;
+            XSSFCell cell;
+            for (int i = 0; i < 3; i++) {
+                // Create row
+                row = sheet.createRow(i);
+                for (int j = 0; j < 3; j++) {
+                    // Create cell
+                    cell = row.createCell(j);
+                    if (i == 0) {
+                        cell.setCellValue("Column" + (j + 1));
+                    } else {
+                        cell.setCellValue((i + 1) * (j + 1));
+                    }
                 }
             }
-        }
-        // Create the columns
-        table.addColumn();
-        table.addColumn();
-        table.addColumn();
-        
-        // Set which area the table should be placed in
-        AreaReference reference = wb.getCreationHelper().createAreaReference(
-                new CellReference(0, 0), new CellReference(2, 2));
-        table.setCellReferences(reference);
+            // Create the columns
+            table.addColumn();
+            table.addColumn();
+            table.addColumn();
 
-        // Save
-        FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            // Set which area the table should be placed in
+            AreaReference reference = wb.getCreationHelper().createAreaReference(
+                    new CellReference(0, 0), new CellReference(2, 2));
+            table.setCellReferences(reference);
+
+            // Save
+            try (FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 4ebaa46fc5a10a01adccab4e466d7c88d1b59423..134560b45cf2b4ab7c0e33ba4d59bd17e61273f4 100644 (file)
@@ -35,34 +35,33 @@ public class CreateUserDefinedDataFormats {
 
 
     public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook();  //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet("format sheet");
-        CellStyle style;
-        DataFormat format = wb.createDataFormat();
-        Row row;
-        Cell cell;
-        short rowNum = 0;
-        short colNum = 0;
+        try (Workbook wb = new XSSFWorkbook()) {  //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet("format sheet");
+            CellStyle style;
+            DataFormat format = wb.createDataFormat();
+            Row row;
+            Cell cell;
+            short rowNum = 0;
+            short colNum = 0;
 
-        row = sheet.createRow(rowNum);
-        cell = row.createCell(colNum);
-        cell.setCellValue(11111.25);
-        style = wb.createCellStyle();
-        style.setDataFormat(format.getFormat("0.0"));
-        cell.setCellStyle(style);
+            row = sheet.createRow(rowNum);
+            cell = row.createCell(colNum);
+            cell.setCellValue(11111.25);
+            style = wb.createCellStyle();
+            style.setDataFormat(format.getFormat("0.0"));
+            cell.setCellStyle(style);
 
-        row = sheet.createRow(++rowNum);
-        cell = row.createCell(colNum);
-        cell.setCellValue(11111.25);
-        style = wb.createCellStyle();
-        style.setDataFormat(format.getFormat("#,##0.0000"));
-        cell.setCellStyle(style);
+            row = sheet.createRow(++rowNum);
+            cell = row.createCell(colNum);
+            cell.setCellValue(11111.25);
+            style = wb.createCellStyle();
+            style.setDataFormat(format.getFormat("#,##0.0000"));
+            cell.setCellStyle(style);
 
-        FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        
-        wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 
 }
index e834e4e9739ac5a5aa0f6b87fea22de0193546ef..70b235413ff03a300c1de9bf5dc4408d0878344d 100644 (file)
@@ -29,18 +29,16 @@ import java.io.ByteArrayOutputStream;
 public class CustomXMLMapping {
 
     public static void main(String[] args) throws Exception {
-        OPCPackage pkg = OPCPackage.open(args[0]);
-        XSSFWorkbook wb = new XSSFWorkbook(pkg);
-
-        for (XSSFMap map : wb.getCustomXMLMappings()) {
-            XSSFExportToXml exporter = new XSSFExportToXml(map);
-
-            ByteArrayOutputStream os = new ByteArrayOutputStream();
-            exporter.exportToXML(os, true);
-            String xml = os.toString("UTF-8");
-            System.out.println(xml);
+        try (OPCPackage pkg = OPCPackage.open(args[0]);
+             XSSFWorkbook wb = new XSSFWorkbook(pkg)) {
+            for (XSSFMap map : wb.getCustomXMLMappings()) {
+                XSSFExportToXml exporter = new XSSFExportToXml(map);
+
+                ByteArrayOutputStream os = new ByteArrayOutputStream();
+                exporter.exportToXML(os, true);
+                String xml = os.toString("UTF-8");
+                System.out.println(xml);
+            }
         }
-        pkg.close();
-        wb.close();
     }
 }
index 916c2ec50d324080b8dda0a2bd8a3d661d0ac37e..b760acac03bee993573125f6d1c5ef7d5ef7aaad 100644 (file)
@@ -32,36 +32,36 @@ import org.apache.poi.xwpf.usermodel.XWPFDocument;
  */
 public class EmbeddedObjects {
     public static void main(String[] args) throws Exception {
-        XSSFWorkbook workbook = new XSSFWorkbook(args[0]);
-        for (PackagePart pPart : workbook.getAllEmbedds()) {
-            String contentType = pPart.getContentType();
-            InputStream is = pPart.getInputStream();
-            Closeable document;
-            if (contentType.equals("application/vnd.ms-excel")) {
-                // Excel Workbook - either binary or OpenXML
-                document = new HSSFWorkbook(is);
-            } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
-                // Excel Workbook - OpenXML file format
-                document = new XSSFWorkbook(is);
-            } else if (contentType.equals("application/msword")) {
-                // Word Document - binary (OLE2CDF) file format
-                document = new HWPFDocument(is);
-            } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
-                // Word Document - OpenXML file format
-                document = new XWPFDocument(is);
-            } else if (contentType.equals("application/vnd.ms-powerpoint")) {
-                // PowerPoint Document - binary file format
-                document = new HSLFSlideShow(is);
-            } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
-                // PowerPoint Document - OpenXML file format
-                document = new XMLSlideShow(is);
-            } else {
-                // Any other type of embedded object.
-                document = is;
+        try (XSSFWorkbook workbook = new XSSFWorkbook(args[0])) {
+            for (PackagePart pPart : workbook.getAllEmbedds()) {
+                String contentType = pPart.getContentType();
+                try (InputStream is = pPart.getInputStream()) {
+                    Closeable document;
+                    if (contentType.equals("application/vnd.ms-excel")) {
+                        // Excel Workbook - either binary or OpenXML
+                        document = new HSSFWorkbook(is);
+                    } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
+                        // Excel Workbook - OpenXML file format
+                        document = new XSSFWorkbook(is);
+                    } else if (contentType.equals("application/msword")) {
+                        // Word Document - binary (OLE2CDF) file format
+                        document = new HWPFDocument(is);
+                    } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
+                        // Word Document - OpenXML file format
+                        document = new XWPFDocument(is);
+                    } else if (contentType.equals("application/vnd.ms-powerpoint")) {
+                        // PowerPoint Document - binary file format
+                        document = new HSLFSlideShow(is);
+                    } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
+                        // PowerPoint Document - OpenXML file format
+                        document = new XMLSlideShow(is);
+                    } else {
+                        // Any other type of embedded object.
+                        document = is;
+                    }
+                    document.close();
+                }
             }
-            document.close();
-            is.close();
         }
-        workbook.close();
     }
 }
\ No newline at end of file
index e93d997eda8077a4452784cc52427767f9c31c9a..f7ffcf5d42c3d437d92ab9fdde5c9281ce6cb156 100644 (file)
@@ -34,32 +34,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  */
 public class FillsAndColors {
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet("new sheet");
+        try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet("new sheet");
 
-        // Create a row and put some cells in it. Rows are 0 based.
-        Row row = sheet.createRow(1);
+            // Create a row and put some cells in it. Rows are 0 based.
+            Row row = sheet.createRow(1);
 
-        // Aqua background
-        CellStyle style = wb.createCellStyle();
-        style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
-        style.setFillPattern(FillPatternType.BIG_SPOTS);
-        Cell cell = row.createCell(1);
-        cell.setCellValue(new XSSFRichTextString("X"));
-        cell.setCellStyle(style);
+            // Aqua background
+            CellStyle style = wb.createCellStyle();
+            style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
+            style.setFillPattern(FillPatternType.BIG_SPOTS);
+            Cell cell = row.createCell(1);
+            cell.setCellValue(new XSSFRichTextString("X"));
+            cell.setCellStyle(style);
 
-        // Orange "foreground", foreground being the fill foreground not the font color.
-        style = wb.createCellStyle();
-        style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
-        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
-        cell = row.createCell(2);
-        cell.setCellValue(new XSSFRichTextString("X"));
-        cell.setCellStyle(style);
+            // Orange "foreground", foreground being the fill foreground not the font color.
+            style = wb.createCellStyle();
+            style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
+            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+            cell = row.createCell(2);
+            cell.setCellValue(new XSSFRichTextString("X"));
+            cell.setCellStyle(style);
 
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index a27ebb8633fd82d7ab0f68f11e0386514a98c751..398b8de8fda9ca82b6f51bd81da2c902a3fc3b00 100644 (file)
@@ -27,20 +27,20 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class FitSheetToOnePage {
 
     public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook();  //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet("format sheet");
-        PrintSetup ps = sheet.getPrintSetup();
+        try (Workbook wb = new XSSFWorkbook()) {  //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet("format sheet");
+            PrintSetup ps = sheet.getPrintSetup();
 
-        sheet.setAutobreaks(true);
+            sheet.setAutobreaks(true);
 
-        ps.setFitHeight((short) 1);
-        ps.setFitWidth((short) 1);
+            ps.setFitHeight((short) 1);
+            ps.setFitWidth((short) 1);
 
-        // Create various cells and rows for spreadsheet.
+            // Create various cells and rows for spreadsheet.
 
-        FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 057a87a771591891c7226eb78dcee21a50026b3b..fc9860dec0870c6ec73f728776c88afc8c74f1fa 100644 (file)
@@ -28,58 +28,57 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
 public class HeadersAndFooters {
 
-
     public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet("first-header - format sheet");
-        sheet.createRow(0).createCell(0).setCellValue(123);
-
-        //set page numbers in the footer
-        Footer footer = sheet.getFooter();
-        //&P == current page number
-        //&N == page numbers
-        footer.setRight("Page &P of &N");
-
-        
-        Header firstHeader=((XSSFSheet)sheet).getFirstHeader();
-        //&F == workbook file name
-        firstHeader.setLeft("&F ......... first header");
-        
-        for(int i=0;i<100;i=i+10){
-            sheet.createRow(i).createCell(0).setCellValue(123);
-        }
-        
-        
-        XSSFSheet sheet2 = (XSSFSheet)wb.createSheet("odd header-even footer");
-        Header oddHeader=sheet2.getOddHeader();
-        //&B == bold
-        //&E == double underline
-        //&D == date
-        oddHeader.setCenter("&B &E oddHeader     &D ");
-        
-        Footer evenFooter=sheet2.getEvenFooter();
-        evenFooter.setRight("even footer &P");
-        sheet2.createRow(10).createCell(0).setCellValue("Second sheet with an oddHeader and an evenFooter");
-
-        for(int i=0;i<200;i=i+10){
-            sheet2.createRow(i).createCell(0).setCellValue(123);
+        try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet("first-header - format sheet");
+            sheet.createRow(0).createCell(0).setCellValue(123);
+
+            //set page numbers in the footer
+            Footer footer = sheet.getFooter();
+            //&P == current page number
+            //&N == page numbers
+            footer.setRight("Page &P of &N");
+
+
+            Header firstHeader = ((XSSFSheet) sheet).getFirstHeader();
+            //&F == workbook file name
+            firstHeader.setLeft("&F ......... first header");
+
+            for (int i = 0; i < 100; i = i + 10) {
+                sheet.createRow(i).createCell(0).setCellValue(123);
+            }
+
+
+            XSSFSheet sheet2 = (XSSFSheet) wb.createSheet("odd header-even footer");
+            Header oddHeader = sheet2.getOddHeader();
+            //&B == bold
+            //&E == double underline
+            //&D == date
+            oddHeader.setCenter("&B &E oddHeader     &D ");
+
+            Footer evenFooter = sheet2.getEvenFooter();
+            evenFooter.setRight("even footer &P");
+            sheet2.createRow(10).createCell(0).setCellValue("Second sheet with an oddHeader and an evenFooter");
+
+            for (int i = 0; i < 200; i = i + 10) {
+                sheet2.createRow(i).createCell(0).setCellValue(123);
+            }
+
+            XSSFSheet sheet3 = (XSSFSheet) wb.createSheet("odd header- odd footer");
+            sheet3.createRow(10).createCell(0).setCellValue("Third sheet with oddHeader and oddFooter");
+            Header oddH = sheet3.getOddHeader();
+            //&C == centered
+            oddH.setCenter("centered oddHeader");
+            oddH.setLeft("left ");
+            oddH.setRight("right ");
+
+            Footer oddF = sheet3.getOddFooter();
+            oddF.setLeft("Page &P");
+            oddF.setRight("Pages &N ");
+
+            try (FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx")) {
+                wb.write(fileOut);
+            }
         }
-        
-        XSSFSheet sheet3 = (XSSFSheet)wb.createSheet("odd header- odd footer");
-        sheet3.createRow(10).createCell(0).setCellValue("Third sheet with oddHeader and oddFooter");
-        Header oddH=sheet3.getOddHeader();
-        //&C == centered
-        oddH.setCenter("centered oddHeader");
-        oddH.setLeft("left ");
-        oddH.setRight("right ");
-        
-        Footer oddF=sheet3.getOddFooter();
-        oddF.setLeft("Page &P");
-        oddF.setRight("Pages &N ");
-        
-        FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
     }
 }
index bd86e7129c1280b7911299ba2a5d28b966fbe939..34586fb97e43ef2238549b9246554fb35b9d2015 100644 (file)
@@ -35,64 +35,62 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  */
 public class HyperlinkExample {
 
-
     public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
-        CreationHelper createHelper = wb.getCreationHelper();
-
-        //cell style for hyperlinks
-        //by default hyperlinks are blue and underlined
-        CellStyle hlink_style = wb.createCellStyle();
-        Font hlink_font = wb.createFont();
-        hlink_font.setUnderline(Font.U_SINGLE);
-        hlink_font.setColor(IndexedColors.BLUE.getIndex());
-        hlink_style.setFont(hlink_font);
-
-        Cell cell;
-        Sheet sheet = wb.createSheet("Hyperlinks");
-        //URL
-        cell = sheet.createRow(0).createCell(0);
-        cell.setCellValue("URL Link");
-
-        Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL);
-        link.setAddress("http://poi.apache.org/");
-        cell.setHyperlink(link);
-        cell.setCellStyle(hlink_style);
-
-        //link to a file in the current directory
-        cell = sheet.createRow(1).createCell(0);
-        cell.setCellValue("File Link");
-        link = createHelper.createHyperlink(HyperlinkType.FILE);
-        link.setAddress("link1.xls");
-        cell.setHyperlink(link);
-        cell.setCellStyle(hlink_style);
-
-        //e-mail link
-        cell = sheet.createRow(2).createCell(0);
-        cell.setCellValue("Email Link");
-        link = createHelper.createHyperlink(HyperlinkType.EMAIL);
-        //note, if subject contains white spaces, make sure they are url-encoded
-        link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
-        cell.setHyperlink(link);
-        cell.setCellStyle(hlink_style);
-
-        //link to a place in this workbook
-
-        //create a target sheet and cell
-        Sheet sheet2 = wb.createSheet("Target Sheet");
-        sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
-
-        cell = sheet.createRow(3).createCell(0);
-        cell.setCellValue("Worksheet Link");
-        Hyperlink link2 = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
-        link2.setAddress("'Target Sheet'!A1");
-        cell.setHyperlink(link2);
-        cell.setCellStyle(hlink_style);
-
-        FileOutputStream out = new FileOutputStream("hyperinks.xlsx");
-        wb.write(out);
-        out.close();
-        
-        wb.close();
+        try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
+            CreationHelper createHelper = wb.getCreationHelper();
+
+            //cell style for hyperlinks
+            //by default hyperlinks are blue and underlined
+            CellStyle hlink_style = wb.createCellStyle();
+            Font hlink_font = wb.createFont();
+            hlink_font.setUnderline(Font.U_SINGLE);
+            hlink_font.setColor(IndexedColors.BLUE.getIndex());
+            hlink_style.setFont(hlink_font);
+
+            Cell cell;
+            Sheet sheet = wb.createSheet("Hyperlinks");
+            //URL
+            cell = sheet.createRow(0).createCell(0);
+            cell.setCellValue("URL Link");
+
+            Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL);
+            link.setAddress("http://poi.apache.org/");
+            cell.setHyperlink(link);
+            cell.setCellStyle(hlink_style);
+
+            //link to a file in the current directory
+            cell = sheet.createRow(1).createCell(0);
+            cell.setCellValue("File Link");
+            link = createHelper.createHyperlink(HyperlinkType.FILE);
+            link.setAddress("link1.xls");
+            cell.setHyperlink(link);
+            cell.setCellStyle(hlink_style);
+
+            //e-mail link
+            cell = sheet.createRow(2).createCell(0);
+            cell.setCellValue("Email Link");
+            link = createHelper.createHyperlink(HyperlinkType.EMAIL);
+            //note, if subject contains white spaces, make sure they are url-encoded
+            link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
+            cell.setHyperlink(link);
+            cell.setCellStyle(hlink_style);
+
+            //link to a place in this workbook
+
+            //create a target sheet and cell
+            Sheet sheet2 = wb.createSheet("Target Sheet");
+            sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
+
+            cell = sheet.createRow(3).createCell(0);
+            cell.setCellValue("Worksheet Link");
+            Hyperlink link2 = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
+            link2.setAddress("'Target Sheet'!A1");
+            cell.setHyperlink(link2);
+            cell.setCellStyle(hlink_style);
+
+            try (FileOutputStream out = new FileOutputStream("hyperinks.xlsx")) {
+                wb.write(out);
+            }
+        }
     }
 }
index dfd1f89114ef892347c1f909a5ca0e32604aca2c..e8b310fb2b6ee42396daffb70b9493f201143148 100644 (file)
@@ -32,17 +32,17 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class IterateCells {
 
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook(new FileInputStream(args[0]));
-        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
-            Sheet sheet = wb.getSheetAt(i);
-            System.out.println(wb.getSheetName(i));
-            for (Row row : sheet) {
-                System.out.println("rownum: " + row.getRowNum());
-                for (Cell cell : row) {
-                    System.out.println(cell);
+        try (Workbook wb = new XSSFWorkbook(new FileInputStream(args[0]))) {
+            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
+                Sheet sheet = wb.getSheetAt(i);
+                System.out.println(wb.getSheetName(i));
+                for (Row row : sheet) {
+                    System.out.println("rownum: " + row.getRowNum());
+                    for (Cell cell : row) {
+                        System.out.println(cell);
+                    }
                 }
             }
         }
-        wb.close();
     }
 }
index 051af64ec7473cd264d22807220b72f34d8db95e..fa14a9d3be0b629d5fa13067acdb27b34abee161 100644 (file)
@@ -44,50 +44,50 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class LineChart {
 
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook();
-        Sheet sheet = wb.createSheet("linechart");
-        final int NUM_OF_ROWS = 3;
-        final int NUM_OF_COLUMNS = 10;
-
-        // Create a row and put some cells in it. Rows are 0 based.
-        Row row;
-        Cell cell;
-        for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
-            row = sheet.createRow((short) rowIndex);
-            for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
-                cell = row.createCell((short) colIndex);
-                cell.setCellValue(colIndex * (rowIndex + 1));
+        try (Workbook wb = new XSSFWorkbook()) {
+            Sheet sheet = wb.createSheet("linechart");
+            final int NUM_OF_ROWS = 3;
+            final int NUM_OF_COLUMNS = 10;
+
+            // Create a row and put some cells in it. Rows are 0 based.
+            Row row;
+            Cell cell;
+            for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
+                row = sheet.createRow((short) rowIndex);
+                for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
+                    cell = row.createCell((short) colIndex);
+                    cell.setCellValue(colIndex * (rowIndex + 1));
+                }
             }
-        }
 
-        Drawing<?> drawing = sheet.createDrawingPatriarch();
-        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
+            Drawing<?> drawing = sheet.createDrawingPatriarch();
+            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
 
-        Chart chart = drawing.createChart(anchor);
-        ChartLegend legend = chart.getOrCreateLegend();
-        legend.setPosition(LegendPosition.TOP_RIGHT);
+            Chart chart = drawing.createChart(anchor);
+            ChartLegend legend = chart.getOrCreateLegend();
+            legend.setPosition(LegendPosition.TOP_RIGHT);
 
-        LineChartData data = chart.getChartDataFactory().createLineChartData();
+            LineChartData data = chart.getChartDataFactory().createLineChartData();
 
-        // Use a category axis for the bottom axis.
-        ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
-        ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
-        leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
+            // Use a category axis for the bottom axis.
+            ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
+            ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
+            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
 
-        ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
-        ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
-        ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
+            ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
+            ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
+            ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
 
 
-        data.addSeries(xs, ys1);
-        data.addSeries(xs, ys2);
+            data.addSeries(xs, ys1);
+            data.addSeries(xs, ys2);
 
-        chart.plot(data, bottomAxis, leftAxis);
+            chart.plot(data, bottomAxis, leftAxis);
 
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index b6bca2e8d70311a7c2fbe0eb65a4d03bda5db1c2..f9abb80005013f7332b036c65e7fdfb6f8b71b5b 100644 (file)
@@ -33,19 +33,19 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  */
 public class MergingCells {
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet("new sheet");
+        try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet("new sheet");
 
-        Row row = sheet.createRow((short) 1);
-        Cell cell = row.createCell((short) 1);
-        cell.setCellValue(new XSSFRichTextString("This is a test of merging"));
+            Row row = sheet.createRow((short) 1);
+            Cell cell = row.createCell((short) 1);
+            cell.setCellValue(new XSSFRichTextString("This is a test of merging"));
 
-        sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
+            sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
 
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 35d26918c71c2b54b71d887927b86ee43c686734..08684ca1c09ca4ac69d0bb592f5092057827da01 100644 (file)
@@ -32,28 +32,28 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class NewLinesInCells {
 
     public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook();   //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet();
+        try (Workbook wb = new XSSFWorkbook()) {   //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet();
 
-        Row row = sheet.createRow(2);
-        Cell cell = row.createCell(2);
-        cell.setCellValue("Use \n with word wrap on to create a new line");
+            Row row = sheet.createRow(2);
+            Cell cell = row.createCell(2);
+            cell.setCellValue("Use \n with word wrap on to create a new line");
 
-        //to enable newlines you need set a cell styles with wrap=true
-        CellStyle cs = wb.createCellStyle();
-        cs.setWrapText(true);
-        cell.setCellStyle(cs);
+            //to enable newlines you need set a cell styles with wrap=true
+            CellStyle cs = wb.createCellStyle();
+            cs.setWrapText(true);
+            cell.setCellStyle(cs);
 
-        //increase row height to accomodate two lines of text
-        row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
+            //increase row height to accomodate two lines of text
+            row.setHeightInPoints((2 * sheet.getDefaultRowHeightInPoints()));
 
-        //adjust column width to fit the content
-        sheet.autoSizeColumn(2);
+            //adjust column width to fit the content
+            sheet.autoSizeColumn(2);
 
-        FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 
 }
index f859c9eb5131425602aa6bd3eb698a688fbaa42c..b00b59a3081de7a36de66a5a55124cc0f4a1b36b 100644 (file)
@@ -35,50 +35,44 @@ public class Outlining {
 
 
     private void groupRowColumn() throws IOException {
-        Workbook wb = new XSSFWorkbook();
-        Sheet sheet1 = wb.createSheet("new sheet");
-
-        sheet1.groupRow( 5, 14 );
-        sheet1.groupRow( 7, 14 );
-        sheet1.groupRow( 16, 19 );
-
-        sheet1.groupColumn( (short)4, (short)7 );
-        sheet1.groupColumn( (short)9, (short)12 );
-        sheet1.groupColumn( (short)10, (short)11 );
-
-        OutputStream fileOut = new FileOutputStream("outlining.xlsx");
-        try {
-            wb.write(fileOut);
-        } finally {
-            fileOut.close();
-            wb.close();
+        try (Workbook wb = new XSSFWorkbook()) {
+            Sheet sheet1 = wb.createSheet("new sheet");
+
+            sheet1.groupRow(5, 14);
+            sheet1.groupRow(7, 14);
+            sheet1.groupRow(16, 19);
+
+            sheet1.groupColumn((short) 4, (short) 7);
+            sheet1.groupColumn((short) 9, (short) 12);
+            sheet1.groupColumn((short) 10, (short) 11);
+
+            try (OutputStream fileOut = new FileOutputStream("outlining.xlsx")) {
+                wb.write(fileOut);
+            }
         }
     }
 
     private void collapseExpandRowColumn() throws IOException {
-        Workbook wb2 = new XSSFWorkbook();
-        Sheet sheet2 = wb2.createSheet("new sheet");
-        sheet2.groupRow( 5, 14 );
-        sheet2.groupRow( 7, 14 );
-        sheet2.groupRow( 16, 19 );
+        try (Workbook wb2 = new XSSFWorkbook()) {
+            Sheet sheet2 = wb2.createSheet("new sheet");
+            sheet2.groupRow(5, 14);
+            sheet2.groupRow(7, 14);
+            sheet2.groupRow(16, 19);
 
-        sheet2.groupColumn( (short)4, (short)7 );
-        sheet2.groupColumn( (short)9, (short)12 );
-        sheet2.groupColumn( (short)10, (short)11 );
+            sheet2.groupColumn((short) 4, (short) 7);
+            sheet2.groupColumn((short) 9, (short) 12);
+            sheet2.groupColumn((short) 10, (short) 11);
 
 
-        sheet2.setRowGroupCollapsed( 7, true );
-        //sheet1.setRowGroupCollapsed(7,false);
+            sheet2.setRowGroupCollapsed(7, true);
+            //sheet1.setRowGroupCollapsed(7,false);
 
-        sheet2.setColumnGroupCollapsed( (short)4, true );
-        sheet2.setColumnGroupCollapsed( (short)4, false );
+            sheet2.setColumnGroupCollapsed((short) 4, true);
+            sheet2.setColumnGroupCollapsed((short) 4, false);
 
-        OutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx");
-        try {
-            wb2.write(fileOut);
-        } finally {
-            fileOut.close();
-            wb2.close();
+            try (OutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx")) {
+                wb2.write(fileOut);
+            }
         }
     }
 }
index 8b02eba307b06f2f005a6323f0b448c5a23a2572..ccd23cf9a7aa345c00ace7b828f72da9f63c4e53 100644 (file)
@@ -46,49 +46,49 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class ScatterChart {
 
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook();
-        Sheet sheet = wb.createSheet("Sheet 1");
-        final int NUM_OF_ROWS = 3;
-        final int NUM_OF_COLUMNS = 10;
+        try (Workbook wb = new XSSFWorkbook()) {
+            Sheet sheet = wb.createSheet("Sheet 1");
+            final int NUM_OF_ROWS = 3;
+            final int NUM_OF_COLUMNS = 10;
 
-        // Create a row and put some cells in it. Rows are 0 based.
-        Row row;
-        Cell cell;
-        for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
-            row = sheet.createRow((short) rowIndex);
-            for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
-                cell = row.createCell((short) colIndex);
-                cell.setCellValue(colIndex * (rowIndex + 1));
+            // Create a row and put some cells in it. Rows are 0 based.
+            Row row;
+            Cell cell;
+            for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
+                row = sheet.createRow((short) rowIndex);
+                for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
+                    cell = row.createCell((short) colIndex);
+                    cell.setCellValue(colIndex * (rowIndex + 1));
+                }
             }
-        }
 
-        Drawing<?> drawing = sheet.createDrawingPatriarch();
-        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
+            Drawing<?> drawing = sheet.createDrawingPatriarch();
+            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
 
-        Chart chart = drawing.createChart(anchor);
-        ChartLegend legend = chart.getOrCreateLegend();
-        legend.setPosition(LegendPosition.TOP_RIGHT);
+            Chart chart = drawing.createChart(anchor);
+            ChartLegend legend = chart.getOrCreateLegend();
+            legend.setPosition(LegendPosition.TOP_RIGHT);
 
-        ScatterChartData data = chart.getChartDataFactory().createScatterChartData();
+            ScatterChartData data = chart.getChartDataFactory().createScatterChartData();
 
-        ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
-        ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
-        leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
+            ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
+            ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
+            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
 
-        ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
-        ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
-        ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
+            ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
+            ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
+            ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
 
 
-        data.addSerie(xs, ys1);
-        data.addSerie(xs, ys2);
+            data.addSerie(xs, ys1);
+            data.addSerie(xs, ys2);
 
-        chart.plot(data, bottomAxis, leftAxis);
+            chart.plot(data, bottomAxis, leftAxis);
 
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 43a6b48475ec87195e48e8f671041cbd080a9242..ffe384f828f652972d37f8e0ab77c669b6de2e81 100644 (file)
@@ -26,21 +26,20 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public abstract class SelectedSheet {
     
     public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
+        try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
 
-        wb.createSheet("row sheet");
-        wb.createSheet("another sheet");
-        Sheet sheet3 = wb.createSheet(" sheet 3 ");
-        sheet3.setSelected(true);
-        wb.setActiveSheet(2);
+            wb.createSheet("row sheet");
+            wb.createSheet("another sheet");
+            Sheet sheet3 = wb.createSheet(" sheet 3 ");
+            sheet3.setSelected(true);
+            wb.setActiveSheet(2);
 
-        // Create various cells and rows for spreadsheet.
+            // Create various cells and rows for spreadsheet.
 
-        FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        
-        wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 
 }
index 5f70b6ab9468472d313e30cbb696660881ac5037..48ab3bf4fdf5662af85b81312e4e6c373d12515f 100644 (file)
@@ -31,32 +31,30 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class ShiftRows {
 
     public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook();   //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet("Sheet1");
+        try (Workbook wb = new XSSFWorkbook()) {   //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet("Sheet1");
 
-        Row row1 = sheet.createRow(1);
-        row1.createCell(0).setCellValue(1);
+            Row row1 = sheet.createRow(1);
+            row1.createCell(0).setCellValue(1);
 
-        Row row2 = sheet.createRow(4);
-        row2.createCell(1).setCellValue(2);
+            Row row2 = sheet.createRow(4);
+            row2.createCell(1).setCellValue(2);
 
-        Row row3 = sheet.createRow(5);
-        row3.createCell(2).setCellValue(3);
+            Row row3 = sheet.createRow(5);
+            row3.createCell(2).setCellValue(3);
 
-        Row row4 = sheet.createRow(6);
-        row4.createCell(3).setCellValue(4);
+            Row row4 = sheet.createRow(6);
+            row4.createCell(3).setCellValue(4);
 
-        Row row5 = sheet.createRow(9);
-        row5.createCell(4).setCellValue(5);
+            Row row5 = sheet.createRow(9);
+            row5.createCell(4).setCellValue(5);
 
-        // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
-        sheet.shiftRows(5, 10, -4);
+            // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
+            sheet.shiftRows(5, 10, -4);
 
-        FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
-
-
 }
index 4ea6ea37002a936a304eaabdb742b8f95727146a..dfee2473d91c05c2b4087942f28003e018661f18 100644 (file)
@@ -29,24 +29,24 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  */
 public class SplitAndFreezePanes {
     public static void main(String[]args) throws IOException {
-        Workbook wb = new XSSFWorkbook();
-        Sheet sheet1 = wb.createSheet("new sheet");
-        Sheet sheet2 = wb.createSheet("second sheet");
-        Sheet sheet3 = wb.createSheet("third sheet");
-        Sheet sheet4 = wb.createSheet("fourth sheet");
-
-        // Freeze just one row
-        sheet1.createFreezePane(0, 1, 0, 1);
-        // Freeze just one column
-        sheet2.createFreezePane(1, 0, 1, 0);
-        // Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
-        sheet3.createFreezePane(2, 2);
-        // Create a split with the lower left side being the active quadrant
-        sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
-
-        FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+        try (Workbook wb = new XSSFWorkbook()) {
+            Sheet sheet1 = wb.createSheet("new sheet");
+            Sheet sheet2 = wb.createSheet("second sheet");
+            Sheet sheet3 = wb.createSheet("third sheet");
+            Sheet sheet4 = wb.createSheet("fourth sheet");
+
+            // Freeze just one row
+            sheet1.createFreezePane(0, 1, 0, 1);
+            // Freeze just one column
+            sheet2.createFreezePane(1, 0, 1, 0);
+            // Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
+            sheet3.createFreezePane(2, 2);
+            // Create a split with the lower left side being the active quadrant
+            sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
+
+            try (FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 5911caa6cab7952624f55aff4f5ce5f4a674e309..48bd123814ffd71c2fba1487bcc8d0d2d15ee2f1 100644 (file)
@@ -29,37 +29,34 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class WorkbookProperties {
 
     public static void main(String[]args) throws IOException {
+        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
+            workbook.createSheet("Workbook Properties");
 
-        XSSFWorkbook workbook = new XSSFWorkbook();
-        workbook.createSheet("Workbook Properties");
+            POIXMLProperties props = workbook.getProperties();
 
-        POIXMLProperties props = workbook.getProperties();
-
-        /**
+        /*
          * Extended properties are a predefined set of metadata properties
          * that are specifically applicable to Office Open XML documents.
          * Extended properties consist of 24 simple properties and 3 complex properties stored in the
          *  part targeted by the relationship of type
          */
-        POIXMLProperties.ExtendedProperties ext =  props.getExtendedProperties();
-        ext.getUnderlyingProperties().setCompany("Apache Software Foundation");
-        ext.getUnderlyingProperties().setTemplate("XSSF");
+            POIXMLProperties.ExtendedProperties ext = props.getExtendedProperties();
+            ext.getUnderlyingProperties().setCompany("Apache Software Foundation");
+            ext.getUnderlyingProperties().setTemplate("XSSF");
 
-        /**
+        /*
          * Custom properties enable users to define custom metadata properties.
          */
-        
-        POIXMLProperties.CustomProperties cust =  props.getCustomProperties();
-        cust.addProperty("Author", "John Smith");
-        cust.addProperty("Year", 2009);
-        cust.addProperty("Price", 45.50);
-        cust.addProperty("Available", true);
-
-        FileOutputStream out = new FileOutputStream("workbook.xlsx");
-        workbook.write(out);
-        out.close();
-        workbook.close();
-    }
 
+            POIXMLProperties.CustomProperties cust = props.getCustomProperties();
+            cust.addProperty("Author", "John Smith");
+            cust.addProperty("Year", 2009);
+            cust.addProperty("Price", 45.50);
+            cust.addProperty("Available", true);
 
+            try (FileOutputStream out = new FileOutputStream("workbook.xlsx")) {
+                workbook.write(out);
+            }
+        }
+    }
 }
\ No newline at end of file
index 32b233ce7fe25421ae68c43a3d55dd0427f33ece..bdf856fa99b803cd7b47ce36dca644467bd554eb 100644 (file)
@@ -34,32 +34,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  */
 public class WorkingWithBorders {
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook();  //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet("borders");
+        try (Workbook wb = new XSSFWorkbook()) {  //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet("borders");
 
-        // Create a row and put some cells in it. Rows are 0 based.
-        Row row = sheet.createRow((short) 1);
+            // Create a row and put some cells in it. Rows are 0 based.
+            Row row = sheet.createRow((short) 1);
 
-        // Create a cell and put a value in it.
-        Cell cell = row.createCell((short) 1);
-        cell.setCellValue(4);
+            // Create a cell and put a value in it.
+            Cell cell = row.createCell((short) 1);
+            cell.setCellValue(4);
 
-        // Style the cell with borders all around.
-        CellStyle style = wb.createCellStyle();
-        style.setBorderBottom(BorderStyle.THIN);
-        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
-        style.setBorderLeft(BorderStyle.THIN);
-        style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
-        style.setBorderRight(BorderStyle.THIN);
-        style.setRightBorderColor(IndexedColors.BLUE.getIndex());
-        style.setBorderTop(BorderStyle.MEDIUM_DASHED);
-        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
-        cell.setCellStyle(style);
+            // Style the cell with borders all around.
+            CellStyle style = wb.createCellStyle();
+            style.setBorderBottom(BorderStyle.THIN);
+            style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
+            style.setBorderLeft(BorderStyle.THIN);
+            style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
+            style.setBorderRight(BorderStyle.THIN);
+            style.setRightBorderColor(IndexedColors.BLUE.getIndex());
+            style.setBorderTop(BorderStyle.MEDIUM_DASHED);
+            style.setTopBorderColor(IndexedColors.BLACK.getIndex());
+            cell.setCellStyle(style);
 
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 9930674845584b5a05f0bd30cda12a0adc93d73e..b2fa5993b159054a78fd6c612a048482787b4aca 100644 (file)
@@ -33,75 +33,75 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  */
 public class WorkingWithFonts {
     public static void main(String[] args) throws IOException {
-        Workbook wb = new XSSFWorkbook();  //or new HSSFWorkbook();
-        Sheet sheet = wb.createSheet("Fonts");
-
-        Font font0 = wb.createFont();
-        font0.setColor(IndexedColors.BROWN.getIndex());
-        CellStyle style0 = wb.createCellStyle();
-        style0.setFont(font0);
-
-        Font font1 = wb.createFont();
-        font1.setFontHeightInPoints((short)14);
-        font1.setFontName("Courier New");
-        font1.setColor(IndexedColors.RED.getIndex());
-        CellStyle style1 = wb.createCellStyle();
-        style1.setFont(font1);
-
-        Font font2 = wb.createFont();
-        font2.setFontHeightInPoints((short)16);
-        font2.setFontName("Arial");
-        font2.setColor(IndexedColors.GREEN.getIndex());
-        CellStyle style2 = wb.createCellStyle();
-        style2.setFont(font2);
-
-        Font font3 = wb.createFont();
-        font3.setFontHeightInPoints((short)18);
-        font3.setFontName("Times New Roman");
-        font3.setColor(IndexedColors.LAVENDER.getIndex());
-        CellStyle style3 = wb.createCellStyle();
-        style3.setFont(font3);
-
-        Font font4 = wb.createFont();
-        font4.setFontHeightInPoints((short)18);
-        font4.setFontName("Wingdings");
-        font4.setColor(IndexedColors.GOLD.getIndex());
-        CellStyle style4 = wb.createCellStyle();
-        style4.setFont(font4);
-
-        Font font5 = wb.createFont();
-        font5.setFontName("Symbol");
-        CellStyle style5 = wb.createCellStyle();
-        style5.setFont(font5);
-
-        Cell cell0 = sheet.createRow(0).createCell(1);
-        cell0.setCellValue("Default");
-        cell0.setCellStyle(style0);
-
-        Cell cell1 = sheet.createRow(1).createCell(1);
-        cell1.setCellValue("Courier");
-        cell1.setCellStyle(style1);
-
-        Cell cell2 = sheet.createRow(2).createCell(1);
-        cell2.setCellValue("Arial");
-        cell2.setCellStyle(style2);
-
-        Cell cell3 = sheet.createRow(3).createCell(1);
-        cell3.setCellValue("Times New Roman");
-        cell3.setCellStyle(style3);
-
-        Cell cell4 = sheet.createRow(4).createCell(1);
-        cell4.setCellValue("Wingdings");
-        cell4.setCellStyle(style4);
-
-        Cell cell5 = sheet.createRow(5).createCell(1);
-        cell5.setCellValue("Symbol");
-        cell5.setCellStyle(style5);
-
-        // Write the output to a file
-        FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        wb.close();
+        try (Workbook wb = new XSSFWorkbook()) {  //or new HSSFWorkbook();
+            Sheet sheet = wb.createSheet("Fonts");
+
+            Font font0 = wb.createFont();
+            font0.setColor(IndexedColors.BROWN.getIndex());
+            CellStyle style0 = wb.createCellStyle();
+            style0.setFont(font0);
+
+            Font font1 = wb.createFont();
+            font1.setFontHeightInPoints((short) 14);
+            font1.setFontName("Courier New");
+            font1.setColor(IndexedColors.RED.getIndex());
+            CellStyle style1 = wb.createCellStyle();
+            style1.setFont(font1);
+
+            Font font2 = wb.createFont();
+            font2.setFontHeightInPoints((short) 16);
+            font2.setFontName("Arial");
+            font2.setColor(IndexedColors.GREEN.getIndex());
+            CellStyle style2 = wb.createCellStyle();
+            style2.setFont(font2);
+
+            Font font3 = wb.createFont();
+            font3.setFontHeightInPoints((short) 18);
+            font3.setFontName("Times New Roman");
+            font3.setColor(IndexedColors.LAVENDER.getIndex());
+            CellStyle style3 = wb.createCellStyle();
+            style3.setFont(font3);
+
+            Font font4 = wb.createFont();
+            font4.setFontHeightInPoints((short) 18);
+            font4.setFontName("Wingdings");
+            font4.setColor(IndexedColors.GOLD.getIndex());
+            CellStyle style4 = wb.createCellStyle();
+            style4.setFont(font4);
+
+            Font font5 = wb.createFont();
+            font5.setFontName("Symbol");
+            CellStyle style5 = wb.createCellStyle();
+            style5.setFont(font5);
+
+            Cell cell0 = sheet.createRow(0).createCell(1);
+            cell0.setCellValue("Default");
+            cell0.setCellStyle(style0);
+
+            Cell cell1 = sheet.createRow(1).createCell(1);
+            cell1.setCellValue("Courier");
+            cell1.setCellStyle(style1);
+
+            Cell cell2 = sheet.createRow(2).createCell(1);
+            cell2.setCellValue("Arial");
+            cell2.setCellStyle(style2);
+
+            Cell cell3 = sheet.createRow(3).createCell(1);
+            cell3.setCellValue("Times New Roman");
+            cell3.setCellStyle(style3);
+
+            Cell cell4 = sheet.createRow(4).createCell(1);
+            cell4.setCellValue("Wingdings");
+            cell4.setCellStyle(style4);
+
+            Cell cell5 = sheet.createRow(5).createCell(1);
+            cell5.setCellValue("Symbol");
+            cell5.setCellStyle(style5);
+
+            // Write the output to a file
+            try (FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 25f994f953c0ae0d9bf799785b4f90675efcfe12..7da2d53a37d46ae7c3d4a6bfe7b284a2718c9122 100644 (file)
@@ -30,9 +30,9 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class WorkingWithPageSetup {
 
     public static void main(String[]args) throws Exception {
-        Workbook wb = new XSSFWorkbook();  //or new HSSFWorkbook();
+        try (Workbook wb = new XSSFWorkbook()) {  //or new HSSFWorkbook();
 
-        /**
+        /*
          * It's possible to set up repeating rows and columns in your printouts by using the setRepeatingRowsAndColumns() function in the Workbook object.
          *
          * This function Contains 5 parameters:
@@ -42,42 +42,41 @@ public class WorkingWithPageSetup {
          * The fourth and fifth parameters specify the range for the rows to repeat.
          * To stop the columns from repeating pass in -1 as the start and end rows.
          */
-        Sheet sheet1 = wb.createSheet("new sheet");
-        Sheet sheet2 = wb.createSheet("second sheet");
+            Sheet sheet1 = wb.createSheet("new sheet");
+            Sheet sheet2 = wb.createSheet("second sheet");
 
-        // Set the columns to repeat from column 0 to 2 on the first sheet
-        Row row1 = sheet1.createRow(0);
-        row1.createCell(0).setCellValue(1);
-        row1.createCell(1).setCellValue(2);
-        row1.createCell(2).setCellValue(3);
-        Row row2 = sheet1.createRow(1);
-        row2.createCell(1).setCellValue(4);
-        row2.createCell(2).setCellValue(5);
+            // Set the columns to repeat from column 0 to 2 on the first sheet
+            Row row1 = sheet1.createRow(0);
+            row1.createCell(0).setCellValue(1);
+            row1.createCell(1).setCellValue(2);
+            row1.createCell(2).setCellValue(3);
+            Row row2 = sheet1.createRow(1);
+            row2.createCell(1).setCellValue(4);
+            row2.createCell(2).setCellValue(5);
 
 
-        Row row3 = sheet2.createRow(1);
-        row3.createCell(0).setCellValue(2.1);
-        row3.createCell(4).setCellValue(2.2);
-        row3.createCell(5).setCellValue(2.3);
-        Row row4 = sheet2.createRow(2);
-        row4.createCell(4).setCellValue(2.4);
-        row4.createCell(5).setCellValue(2.5);
+            Row row3 = sheet2.createRow(1);
+            row3.createCell(0).setCellValue(2.1);
+            row3.createCell(4).setCellValue(2.2);
+            row3.createCell(5).setCellValue(2.3);
+            Row row4 = sheet2.createRow(2);
+            row4.createCell(4).setCellValue(2.4);
+            row4.createCell(5).setCellValue(2.5);
 
-        // Set the columns to repeat from column 0 to 2 on the first sheet
-        sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
-        // Set the the repeating rows and columns on the second sheet.
-        CellRangeAddress cra = CellRangeAddress.valueOf("E2:F3");
-        sheet2.setRepeatingColumns(cra);
-        sheet2.setRepeatingRows(cra);
+            // Set the columns to repeat from column 0 to 2 on the first sheet
+            sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
+            // Set the the repeating rows and columns on the second sheet.
+            CellRangeAddress cra = CellRangeAddress.valueOf("E2:F3");
+            sheet2.setRepeatingColumns(cra);
+            sheet2.setRepeatingRows(cra);
 
-        //set the print area for the first sheet
-        wb.setPrintArea(0, 1, 2, 0, 3);
+            //set the print area for the first sheet
+            wb.setPrintArea(0, 1, 2, 0, 3);
 
 
-        FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx");
-        wb.write(fileOut);
-        fileOut.close();
-        
-        wb.close();
+            try (FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx")) {
+                wb.write(fileOut);
+            }
+        }
     }
 }
index 34735b7c87545f2142767d64d9ab25c634cdb00e..f0d9ebde3765deb2d9dc721056a39c038beed780 100644 (file)
@@ -39,45 +39,38 @@ public class WorkingWithPictures {
     public static void main(String[] args) throws IOException {
 
         //create a new workbook
-        Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
-        try {
+        try (Workbook wb = new XSSFWorkbook()) {
             CreationHelper helper = wb.getCreationHelper();
-    
+
             //add a picture in this workbook.
             InputStream is = new FileInputStream(args[0]);
             byte[] bytes = IOUtils.toByteArray(is);
             is.close();
             int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
-    
+
             //create sheet
             Sheet sheet = wb.createSheet();
-    
+
             //create drawing
             Drawing<?> drawing = sheet.createDrawingPatriarch();
-    
+
             //add a picture shape
             ClientAnchor anchor = helper.createClientAnchor();
             anchor.setCol1(1);
             anchor.setRow1(1);
             Picture pict = drawing.createPicture(anchor, pictureIdx);
-    
+
             //auto-size picture
             pict.resize(2);
-    
+
             //save workbook
             String file = "picture.xls";
-            if(wb instanceof XSSFWorkbook)
-             {
+            if (wb instanceof XSSFWorkbook) {
                 file += "x"; // NOSONAR
             }
-            OutputStream fileOut = new FileOutputStream(file);
-            try {
+            try (OutputStream fileOut = new FileOutputStream(file)) {
                 wb.write(fileOut);
-            } finally {
-                fileOut.close();
             }
-        } finally {
-            wb.close();
         }
     }
 }
index f982ea52836583a78f59881b75a0621050a09074..4965c7922e67a2d13fada36d06b1eb64782d8ef2 100644 (file)
@@ -28,41 +28,34 @@ import java.io.OutputStream;
 public class WorkingWithRichText {
 
     public static void main(String[] args) throws Exception {
-
-        XSSFWorkbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
-        try {
+        try (XSSFWorkbook wb = new XSSFWorkbook()) {
             XSSFSheet sheet = wb.createSheet();
             XSSFRow row = sheet.createRow(2);
-    
+
             XSSFCell cell = row.createCell(1);
             XSSFRichTextString rt = new XSSFRichTextString("The quick brown fox");
-    
+
             XSSFFont font1 = wb.createFont();
             font1.setBold(true);
             font1.setColor(new XSSFColor(new java.awt.Color(255, 0, 0)));
             rt.applyFont(0, 10, font1);
-    
+
             XSSFFont font2 = wb.createFont();
             font2.setItalic(true);
             font2.setUnderline(XSSFFont.U_DOUBLE);
             font2.setColor(new XSSFColor(new java.awt.Color(0, 255, 0)));
             rt.applyFont(10, 19, font2);
-    
+
             XSSFFont font3 = wb.createFont();
             font3.setColor(new XSSFColor(new java.awt.Color(0, 0, 255)));
             rt.append(" Jumped over the lazy dog", font3);
-    
+
             cell.setCellValue(rt);
 
             // Write the output to a file
-            OutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx");
-            try {
+            try (OutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx")) {
                 wb.write(fileOut);
-            } finally {
-                fileOut.close();
             }
-        } finally {
-            wb.close();
         }
     }
 }
index d40c4ed0cb11b8b116fec210fcea68ea36cc0563..6cd7cfa9e600aeef1eed86a15d93f46c50b6c4d9 100644 (file)
@@ -31,26 +31,26 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
 public class BetterHeaderFooterExample {
 
     public static void main(String[] args) throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-
-        XWPFParagraph p = doc.createParagraph();
-
-        XWPFRun r = p.createRun();
-        r.setText("Some Text");
-        r.setBold(true);
-        r = p.createRun();
-        r.setText("Goodbye");
-
-        // create header/footer functions insert an empty paragraph
-        XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT);
-        head.createParagraph().createRun().setText("header");
-        
-        XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT);
-        foot.createParagraph().createRun().setText("footer");
-        
-        OutputStream os = new FileOutputStream(new File("header2.docx"));
-        doc.write(os);
-        os.close();
-        doc.close();
+        try (XWPFDocument doc = new XWPFDocument()) {
+
+            XWPFParagraph p = doc.createParagraph();
+
+            XWPFRun r = p.createRun();
+            r.setText("Some Text");
+            r.setBold(true);
+            r = p.createRun();
+            r.setText("Goodbye");
+
+            // create header/footer functions insert an empty paragraph
+            XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT);
+            head.createParagraph().createRun().setText("header");
+
+            XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT);
+            foot.createParagraph().createRun().setText("footer");
+
+            try (OutputStream os = new FileOutputStream(new File("header2.docx"))) {
+                doc.write(os);
+            }
+        }
     }
 }
index a2b9103a47b6117c941c9554f15517179e468132..3278f2cb5f1cea130e311b28ecdada1f435f6cc1 100644 (file)
@@ -41,65 +41,65 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblLayoutType;
 public class HeaderFooterTable {
 
     public static void main(String[] args) throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        
-        // Create a header with a 1 row, 3 column table
-        // changes made for issue 57366 allow a new header or footer
-        // to be created empty. This is a change. You will have to add
-        // either a paragraph or a table to the header or footer for
-        // the document to be considered valid.
-        XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
-        XWPFTable tbl = hdr.createTable(1, 3);
-        
-        // Set the padding around text in the cells to 1/10th of an inch
-        int pad = (int) (.1 * 1440);
-        tbl.setCellMargins(pad, pad, pad, pad);
-
-        // Set table width to 6.5 inches in 1440ths of a point
-        tbl.setWidth((int)(6.5 * 1440));
-        // Can not yet set table or cell width properly, tables default to
-        // autofit layout, and this requires fixed layout
-        CTTbl ctTbl = tbl.getCTTbl();
-        CTTblPr ctTblPr = ctTbl.addNewTblPr();
-        CTTblLayoutType layoutType = ctTblPr.addNewTblLayout();
-        layoutType.setType(STTblLayoutType.FIXED);
-
-        // Now set up a grid for the table, cells will fit into the grid
-        // Each cell width is 3120 in 1440ths of an inch, or 1/3rd of 6.5"
-        BigInteger w = new BigInteger("3120");
-        CTTblGrid grid = ctTbl.addNewTblGrid();
-        for (int i = 0; i < 3; i++) {
-            CTTblGridCol gridCol = grid.addNewGridCol();
-            gridCol.setW(w);
+        try (XWPFDocument doc = new XWPFDocument()) {
+
+            // Create a header with a 1 row, 3 column table
+            // changes made for issue 57366 allow a new header or footer
+            // to be created empty. This is a change. You will have to add
+            // either a paragraph or a table to the header or footer for
+            // the document to be considered valid.
+            XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
+            XWPFTable tbl = hdr.createTable(1, 3);
+
+            // Set the padding around text in the cells to 1/10th of an inch
+            int pad = (int) (.1 * 1440);
+            tbl.setCellMargins(pad, pad, pad, pad);
+
+            // Set table width to 6.5 inches in 1440ths of a point
+            tbl.setWidth((int) (6.5 * 1440));
+            // Can not yet set table or cell width properly, tables default to
+            // autofit layout, and this requires fixed layout
+            CTTbl ctTbl = tbl.getCTTbl();
+            CTTblPr ctTblPr = ctTbl.addNewTblPr();
+            CTTblLayoutType layoutType = ctTblPr.addNewTblLayout();
+            layoutType.setType(STTblLayoutType.FIXED);
+
+            // Now set up a grid for the table, cells will fit into the grid
+            // Each cell width is 3120 in 1440ths of an inch, or 1/3rd of 6.5"
+            BigInteger w = new BigInteger("3120");
+            CTTblGrid grid = ctTbl.addNewTblGrid();
+            for (int i = 0; i < 3; i++) {
+                CTTblGridCol gridCol = grid.addNewGridCol();
+                gridCol.setW(w);
+            }
+
+            // Add paragraphs to the cells
+            XWPFTableRow row = tbl.getRow(0);
+            XWPFTableCell cell = row.getCell(0);
+            XWPFParagraph p = cell.getParagraphArray(0);
+            XWPFRun r = p.createRun();
+            r.setText("header left cell");
+
+            cell = row.getCell(1);
+            p = cell.getParagraphArray(0);
+            r = p.createRun();
+            r.setText("header center cell");
+
+            cell = row.getCell(2);
+            p = cell.getParagraphArray(0);
+            r = p.createRun();
+            r.setText("header right cell");
+
+            // Create a footer with a Paragraph
+            XWPFFooter ftr = doc.createFooter(HeaderFooterType.DEFAULT);
+            p = ftr.createParagraph();
+
+            r = p.createRun();
+            r.setText("footer text");
+
+            try (OutputStream os = new FileOutputStream(new File("headertable.docx"))) {
+                doc.write(os);
+            }
         }
-        
-        // Add paragraphs to the cells
-        XWPFTableRow row = tbl.getRow(0);
-        XWPFTableCell cell = row.getCell(0);
-        XWPFParagraph p = cell.getParagraphArray(0);
-        XWPFRun r = p.createRun();
-        r.setText("header left cell");
-
-        cell = row.getCell(1);
-        p = cell.getParagraphArray(0);
-        r = p.createRun();
-        r.setText("header center cell");
-
-        cell = row.getCell(2);
-        p = cell.getParagraphArray(0);
-        r = p.createRun();
-        r.setText("header right cell");
-
-        // Create a footer with a Paragraph
-        XWPFFooter ftr = doc.createFooter(HeaderFooterType.DEFAULT);
-        p = ftr.createParagraph();
-
-        r = p.createRun();
-        r.setText("footer text");
-
-        OutputStream os = new FileOutputStream(new File("headertable.docx"));
-        doc.write(os);
-        doc.close();
        }
-
 }
index 28433c4ed06968bcd8ceaa6f7499a47818106b00..22ed4e6bf64589c74aca9c778fe4b3142bebce04 100644 (file)
@@ -36,95 +36,95 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
 public class SimpleDocument {
 
     public static void main(String[] args) throws Exception {
-        XWPFDocument doc = new XWPFDocument();
-
-        XWPFParagraph p1 = doc.createParagraph();
-        p1.setAlignment(ParagraphAlignment.CENTER);
-        p1.setBorderBottom(Borders.DOUBLE);
-        p1.setBorderTop(Borders.DOUBLE);
-
-        p1.setBorderRight(Borders.DOUBLE);
-        p1.setBorderLeft(Borders.DOUBLE);
-        p1.setBorderBetween(Borders.SINGLE);
-
-        p1.setVerticalAlignment(TextAlignment.TOP);
-
-        XWPFRun r1 = p1.createRun();
-        r1.setBold(true);
-        r1.setText("The quick brown fox");
-        r1.setBold(true);
-        r1.setFontFamily("Courier");
-        r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
-        r1.setTextPosition(100);
-
-        XWPFParagraph p2 = doc.createParagraph();
-        p2.setAlignment(ParagraphAlignment.RIGHT);
-
-        //BORDERS
-        p2.setBorderBottom(Borders.DOUBLE);
-        p2.setBorderTop(Borders.DOUBLE);
-        p2.setBorderRight(Borders.DOUBLE);
-        p2.setBorderLeft(Borders.DOUBLE);
-        p2.setBorderBetween(Borders.SINGLE);
-
-        XWPFRun r2 = p2.createRun();
-        r2.setText("jumped over the lazy dog");
-        r2.setStrikeThrough(true);
-        r2.setFontSize(20);
-
-        XWPFRun r3 = p2.createRun();
-        r3.setText("and went away");
-        r3.setStrikeThrough(true);
-        r3.setFontSize(20);
-        r3.setSubscript(VerticalAlign.SUPERSCRIPT);
-
-
-        XWPFParagraph p3 = doc.createParagraph();
-        p3.setWordWrapped(true);
-        p3.setPageBreak(true);
-                
-        //p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
-        p3.setAlignment(ParagraphAlignment.BOTH);
-        p3.setSpacingBetween(15, LineSpacingRule.EXACT);
-
-        p3.setIndentationFirstLine(600);
-        
-
-        XWPFRun r4 = p3.createRun();
-        r4.setTextPosition(20);
-        r4.setText("To be, or not to be: that is the question: "
-                + "Whether 'tis nobler in the mind to suffer "
-                + "The slings and arrows of outrageous fortune, "
-                + "Or to take arms against a sea of troubles, "
-                + "And by opposing end them? To die: to sleep; ");
-        r4.addBreak(BreakType.PAGE);
-        r4.setText("No more; and by a sleep to say we end "
-                + "The heart-ache and the thousand natural shocks "
-                + "That flesh is heir to, 'tis a consummation "
-                + "Devoutly to be wish'd. To die, to sleep; "
-                + "To sleep: perchance to dream: ay, there's the rub; "
-                + ".......");
-        r4.setItalic(true);
+        try (XWPFDocument doc = new XWPFDocument()) {
+
+            XWPFParagraph p1 = doc.createParagraph();
+            p1.setAlignment(ParagraphAlignment.CENTER);
+            p1.setBorderBottom(Borders.DOUBLE);
+            p1.setBorderTop(Borders.DOUBLE);
+
+            p1.setBorderRight(Borders.DOUBLE);
+            p1.setBorderLeft(Borders.DOUBLE);
+            p1.setBorderBetween(Borders.SINGLE);
+
+            p1.setVerticalAlignment(TextAlignment.TOP);
+
+            XWPFRun r1 = p1.createRun();
+            r1.setBold(true);
+            r1.setText("The quick brown fox");
+            r1.setBold(true);
+            r1.setFontFamily("Courier");
+            r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
+            r1.setTextPosition(100);
+
+            XWPFParagraph p2 = doc.createParagraph();
+            p2.setAlignment(ParagraphAlignment.RIGHT);
+
+            //BORDERS
+            p2.setBorderBottom(Borders.DOUBLE);
+            p2.setBorderTop(Borders.DOUBLE);
+            p2.setBorderRight(Borders.DOUBLE);
+            p2.setBorderLeft(Borders.DOUBLE);
+            p2.setBorderBetween(Borders.SINGLE);
+
+            XWPFRun r2 = p2.createRun();
+            r2.setText("jumped over the lazy dog");
+            r2.setStrikeThrough(true);
+            r2.setFontSize(20);
+
+            XWPFRun r3 = p2.createRun();
+            r3.setText("and went away");
+            r3.setStrikeThrough(true);
+            r3.setFontSize(20);
+            r3.setSubscript(VerticalAlign.SUPERSCRIPT);
+
+
+            XWPFParagraph p3 = doc.createParagraph();
+            p3.setWordWrapped(true);
+            p3.setPageBreak(true);
+
+            //p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
+            p3.setAlignment(ParagraphAlignment.BOTH);
+            p3.setSpacingBetween(15, LineSpacingRule.EXACT);
+
+            p3.setIndentationFirstLine(600);
+
+
+            XWPFRun r4 = p3.createRun();
+            r4.setTextPosition(20);
+            r4.setText("To be, or not to be: that is the question: "
+                    + "Whether 'tis nobler in the mind to suffer "
+                    + "The slings and arrows of outrageous fortune, "
+                    + "Or to take arms against a sea of troubles, "
+                    + "And by opposing end them? To die: to sleep; ");
+            r4.addBreak(BreakType.PAGE);
+            r4.setText("No more; and by a sleep to say we end "
+                    + "The heart-ache and the thousand natural shocks "
+                    + "That flesh is heir to, 'tis a consummation "
+                    + "Devoutly to be wish'd. To die, to sleep; "
+                    + "To sleep: perchance to dream: ay, there's the rub; "
+                    + ".......");
+            r4.setItalic(true);
 //This would imply that this break shall be treated as a simple line break, and break the line after that word:
 
-        XWPFRun r5 = p3.createRun();
-        r5.setTextPosition(-10);
-        r5.setText("For in that sleep of death what dreams may come");
-        r5.addCarriageReturn();
-        r5.setText("When we have shuffled off this mortal coil,"
-                + "Must give us pause: there's the respect"
-                + "That makes calamity of so long life;");
-        r5.addBreak();
-        r5.setText("For who would bear the whips and scorns of time,"
-                + "The oppressor's wrong, the proud man's contumely,");
-        
-        r5.addBreak(BreakClear.ALL);
-        r5.setText("The pangs of despised love, the law's delay,"
-                + "The insolence of office and the spurns" + ".......");
-
-        FileOutputStream out = new FileOutputStream("simple.docx");
-        doc.write(out);
-        out.close();
-        doc.close();
+            XWPFRun r5 = p3.createRun();
+            r5.setTextPosition(-10);
+            r5.setText("For in that sleep of death what dreams may come");
+            r5.addCarriageReturn();
+            r5.setText("When we have shuffled off this mortal coil,"
+                    + "Must give us pause: there's the respect"
+                    + "That makes calamity of so long life;");
+            r5.addBreak();
+            r5.setText("For who would bear the whips and scorns of time,"
+                    + "The oppressor's wrong, the proud man's contumely,");
+
+            r5.addBreak(BreakClear.ALL);
+            r5.setText("The pangs of despised love, the law's delay,"
+                    + "The insolence of office and the spurns" + ".......");
+
+            try (FileOutputStream out = new FileOutputStream("simple.docx")) {
+                doc.write(out);
+            }
+        }
     }
 }
index a798ebd431490104968931886b5b88fa78ee1df5..7927e911c72b0fa0ddb40ea4900eb4a4edf45463 100644 (file)
@@ -35,42 +35,36 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
  */
 public class SimpleDocumentWithHeader {
 
-       private static XWPFParagraph[] pars;
+       public static void main(String[] args) throws IOException {
+               try (XWPFDocument doc = new XWPFDocument()) {
 
-       public static void main(String[] args) {
-               XWPFDocument doc = new XWPFDocument();
+                       XWPFParagraph p = doc.createParagraph();
 
-               XWPFParagraph p = doc.createParagraph();
+                       XWPFRun r = p.createRun();
+                       r.setText("Some Text");
+                       r.setBold(true);
+                       r = p.createRun();
+                       r.setText("Goodbye");
 
-               XWPFRun r = p.createRun();
-               r.setText("Some Text");
-               r.setBold(true);
-               r = p.createRun();
-               r.setText("Goodbye");
+                       CTP ctP = CTP.Factory.newInstance();
+                       CTText t = ctP.addNewR().addNewT();
+                       t.setStringValue("header");
+                       XWPFParagraph[] pars = new XWPFParagraph[1];
+                       p = new XWPFParagraph(ctP, doc);
+                       pars[0] = p;
 
-               CTP ctP = CTP.Factory.newInstance();
-               CTText t = ctP.addNewR().addNewT();
-               t.setStringValue("header");
-               pars = new XWPFParagraph[1];
-               p = new XWPFParagraph(ctP, doc);
-               pars[0] = p;
+                       XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
+                       hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
 
-               XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
-               hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
-               
-               ctP = CTP.Factory.newInstance();
-               t = ctP.addNewR().addNewT();
-               t.setStringValue("My Footer");
-               pars[0] = new XWPFParagraph(ctP, doc);
-               hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
-               
-               try {
-                       OutputStream os = new FileOutputStream(new File("header.docx"));
-                       doc.write(os);
-               } catch (IOException e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
+                       ctP = CTP.Factory.newInstance();
+                       t = ctP.addNewR().addNewT();
+                       t.setStringValue("My Footer");
+                       pars[0] = new XWPFParagraph(ctP, doc);
+                       hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
+
+                       try (OutputStream os = new FileOutputStream(new File("header.docx"))) {
+                               doc.write(os);
+                       }
                }
-               
        }
 }
\ No newline at end of file
index 638cf91b12300ca48d834b0302c9797fb7aa9620..f00af9cde581dee04e5bcdce73fc3790de115de7 100644 (file)
@@ -35,41 +35,41 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
 public class SimpleImages {
 
     public static void main(String[] args) throws IOException, InvalidFormatException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        XWPFRun r = p.createRun();
+            XWPFRun r = p.createRun();
 
-        for(String imgFile : args) {
-            int format;
+            for (String imgFile : args) {
+                int format;
 
-            if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
-            else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
-            else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
-            else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
-            else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
-            else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
-            else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
-            else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
-            else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
-            else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
-            else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
-            else {
-                System.err.println("Unsupported picture: " + imgFile +
-                        ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
-                continue;
+                if (imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
+                else if (imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
+                else if (imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
+                else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
+                else if (imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
+                else if (imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
+                else if (imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
+                else if (imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
+                else if (imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
+                else if (imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
+                else if (imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
+                else {
+                    System.err.println("Unsupported picture: " + imgFile +
+                            ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
+                    continue;
+                }
+
+                r.setText(imgFile);
+                r.addBreak();
+                r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
+                r.addBreak(BreakType.PAGE);
             }
 
-            r.setText(imgFile);
-            r.addBreak();
-            r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
-            r.addBreak(BreakType.PAGE);
+            try (FileOutputStream out = new FileOutputStream("images.docx")) {
+                doc.write(out);
+            }
         }
-
-        FileOutputStream out = new FileOutputStream("images.docx");
-        doc.write(out);
-        out.close();
-        doc.close();
     }
 
 
index a3857ff2e7134169ec30ecc26d7e9bb0815ab11f..b09e00bd482c685cf18bccfb736eec6720bd4334 100644 (file)
@@ -69,9 +69,7 @@ public class SimpleTable {
     }
 
     public static void createSimpleTable() throws Exception {
-        XWPFDocument doc = new XWPFDocument();
-
-        try {
+        try (XWPFDocument doc = new XWPFDocument()) {
             XWPFTable table = doc.createTable(3, 3);
 
             table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");
@@ -93,14 +91,9 @@ public class SimpleTable {
 
             table.getRow(2).getCell(2).setText("only text");
 
-            OutputStream out = new FileOutputStream("simpleTable.docx");
-            try {
+            try (OutputStream out = new FileOutputStream("simpleTable.docx")) {
                 doc.write(out);
-            } finally {
-                out.close();
             }
-        } finally {
-            doc.close();
         }
     }
 
@@ -115,14 +108,11 @@ public class SimpleTable {
      * I make no claims that this is the "right" way to do it, but it worked
      * for me. Given the scarcity of XWPF examples, I thought this may prove
      * instructive and give you ideas for your own solutions.
-
-     * @throws Exception
      */
     public static void createStyledTable() throws Exception {
        // Create a new document from scratch
-        XWPFDocument doc = new XWPFDocument();
 
-        try {
+        try (XWPFDocument doc = new XWPFDocument()) {
             // -- OR --
             // open an existing empty document with styles already defined
             //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
@@ -201,14 +191,9 @@ public class SimpleTable {
             } // for row
 
             // write the file
-            OutputStream out = new FileOutputStream("styledTable.docx");
-            try {
+            try (OutputStream out = new FileOutputStream("styledTable.docx")) {
                 doc.write(out);
-            } finally {
-                out.close();
             }
-        } finally {
-            doc.close();
         }
     }
 }