package org.apache.poi.hslf.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
/**
* How to create a single-level bulleted list
* and change some of the bullet attributes
- *
- * @author Yegor Kozlov
*/
public final class BulletsDemo {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
HSLFSlideShow ppt = new HSLFSlideShow();
FileOutputStream out = new FileOutputStream("bullets.ppt");
ppt.write(out);
out.close();
+
+ ppt.close();
}
}
ppt.write(out);
out.close();
+ ppt.close();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.*;
-import org.apache.poi.hssf.util.HSSFColor;
-
import java.io.FileOutputStream;
import java.io.IOException;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.usermodel.BorderStyle;
+
/**
* Demonstrates how to create borders around cells.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class Borders {
public static void main(String[] args) throws IOException {
// Style the cell with borders all around.
HSSFCellStyle style = wb.createCellStyle();
- style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
+ style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
- style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
+ style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(HSSFColor.GREEN.index);
- style.setBorderRight(HSSFCellStyle.BORDER_THIN);
+ style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(HSSFColor.BLUE.index);
- style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED);
+ style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(HSSFColor.ORANGE.index);
cell.setCellStyle(style);
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+
+ wb.close();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.*;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
+import org.apache.poi.hssf.usermodel.HSSFComment;
+import org.apache.poi.hssf.usermodel.HSSFFont;
+import org.apache.poi.hssf.usermodel.HSSFPatriarch;
+import org.apache.poi.hssf.usermodel.HSSFRichTextString;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
-import java.io.*;
-
/**
* Demonstrates how to work with excel cell comments.
*
* Excel comment is a kind of a text shape,
* so inserting a comment is very similar to placing a text box in a worksheet
* </p>
- *
- * @author Yegor Kozlov
*/
public class CellComments {
HSSFFont font = wb.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short)10);
- font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
+ font.setBold(true);
font.setColor(HSSFColor.RED.index);
string.applyFont(font);
FileOutputStream out = new FileOutputStream("poi_comment.xls");
wb.write(out);
out.close();
+
+ wb.close();
}
}
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+
+ wb.close();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.*;
-
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFDataFormat;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+
/**
* An example on how to cells with dates. The important thing to note
* about dates is that they are really normal numeric cells that are
* formatted specially.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class CreateDateCells {
public static void main(String[] args) throws IOException {
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+
+ wb.close();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.*;
-import org.apache.poi.hssf.util.HSSFColor;
-
import java.io.FileOutputStream;
import java.io.IOException;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.usermodel.FillPatternType;
+
/**
* Shows how to use various fills.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class FrillsAndFills {
public static void main(String[] args) throws IOException {
// Aqua background
HSSFCellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(HSSFColor.AQUA.index);
- style.setFillPattern(HSSFCellStyle.BIG_SPOTS);
+ 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(HSSFColor.ORANGE.index);
- style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell = row.createCell(2);
cell.setCellValue("X");
cell.setCellStyle(style);
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+
+ wb.close();
}
}
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
+import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.util.CellRangeAddress;
/**
cs.setFont(f);
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
cs2.setBorderBottom(BorderStyle.THIN);
- cs2.setFillPattern((short) 1); // fill w fg
+ cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cs2.setFillForegroundColor((short) 0xA);
cs2.setFont(f2);
wb.setSheetName(0, "HSSF Test");
wb.write(out);
} finally {
out.close();
+ wb.close();
}
-
- wb.close();
}
/**
/**
* Test if hyperlink formula, with url that got more than 127 characters, works
- *
- * @author Bernard Chesnoy
*/
public class HyperlinkFormula {
public static void main(String[] args) throws IOException {
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.usermodel.Font;
/**
* Demonstrates how to create hyperlinks.
//by default hyperlinks are blue and underlined
HSSFCellStyle hlink_style = wb.createCellStyle();
HSSFFont hlink_font = wb.createFont();
- hlink_font.setUnderline(HSSFFont.U_SINGLE);
+ hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(HSSFColor.BLUE.index);
hlink_style.setFont(hlink_font);
FileOutputStream out = new FileOutputStream("hssf-links.xls");
wb.write(out);
out.close();
+ wb.close();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.*;
-import org.apache.poi.ss.util.CellRangeAddress;
-
-import java.io.IOException;
import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.util.CellRangeAddress;
/**
* An example of how to merge regions of cells.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class MergedCells {
public static void main(String[] args) throws IOException {
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.*;
-import org.apache.poi.ss.usermodel.CellType;
-
import java.io.FileOutputStream;
import java.io.IOException;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFFont;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.CellType;
+
/**
* Demonstrates how to use newlines in cells.
- *
- * @author Glen Stampoultzis (glens at apache.org)
- * @author Fauzia Lala <fauzia.lala at wcom.com>
*/
public class NewLinesInCells {
public static void main( String[] args ) throws IOException {
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-
import java.io.FileOutputStream;
import java.io.IOException;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+
/**
* This example creates a new blank workbook. This workbook will contain a single blank sheet.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
-public class NewWorkbook
-{
- public static void main(String[] args)
- throws IOException
- {
+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();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-
-import java.io.IOException;
import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.Sheet;
-/**
- * @author Glen Stampoultzis (glens at apache.org)
- */
-public class SplitAndFreezePanes
-{
- public static void main(String[] args)
- throws IOException
- {
+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");
// 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, HSSFSheet.PANE_LOWER_LEFT );
+ sheet4.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.hssf.usermodel.examples;
-import org.apache.poi.hssf.usermodel.*;
-
import java.io.FileOutputStream;
import java.io.IOException;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFFont;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+
/**
* Demonstrates how to create and use fonts.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class WorkingWithFonts {
public static void main(String[] args) throws IOException {
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.ss.examples;\r
\r
import java.io.File;\r
-import java.io.FileNotFoundException;\r
import java.io.FileOutputStream;\r
import java.io.IOException;\r
import java.net.URL;\r
import java.util.Locale;\r
\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
import org.apache.poi.hssf.usermodel.HSSFSheet;\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
import org.apache.poi.ss.usermodel.ClientAnchor;\r
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;\r
import org.apache.poi.ss.usermodel.Drawing;\r
*\r
* @param args the command line arguments\r
*/\r
- public static void main(String[] args) {\r
+ public static void main(String[] args) throws IOException {\r
String imageFile = null;\r
String outputFile = null;\r
FileOutputStream fos = null;\r
Workbook workbook = null;\r
Sheet sheet = null;\r
- try {\r
- if(args.length < 2){\r
- System.err.println("Usage: AddDimensionedImage imageFile outputFile");\r
- return;\r
- }\r
- workbook = new HSSFWorkbook(); // OR XSSFWorkbook\r
- sheet = workbook.createSheet("Picture Test");\r
- imageFile = args[0];\r
- outputFile = args[1];\r
- new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),\r
- new File(imageFile).toURI().toURL(), 100, 40,\r
- AddDimensionedImage.EXPAND_ROW_AND_COLUMN);\r
- fos = new FileOutputStream(outputFile);\r
- workbook.write(fos);\r
- }\r
- catch(FileNotFoundException fnfEx) {\r
- System.out.println("Caught an: " + fnfEx.getClass().getName());\r
- System.out.println("Message: " + fnfEx.getMessage());\r
- System.out.println("Stacktrace follows...........");\r
- fnfEx.printStackTrace(System.out);\r
- }\r
- catch(IOException ioEx) {\r
- System.out.println("Caught an: " + ioEx.getClass().getName());\r
- System.out.println("Message: " + ioEx.getMessage());\r
- System.out.println("Stacktrace follows...........");\r
- ioEx.printStackTrace(System.out);\r
- }\r
- finally {\r
- if(fos != null) {\r
- try {\r
- fos.close();\r
- fos = null;\r
- }\r
- catch(IOException ioEx) {\r
- // I G N O R E\r
- }\r
- }\r
- }\r
+\r
+ if(args.length < 2){\r
+ System.err.println("Usage: AddDimensionedImage imageFile outputFile");\r
+ return;\r
+ }\r
+ workbook = new HSSFWorkbook(); // OR XSSFWorkbook\r
+ sheet = workbook.createSheet("Picture Test");\r
+ imageFile = args[0];\r
+ outputFile = args[1];\r
+ new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),\r
+ new File(imageFile).toURI().toURL(), 100, 40,\r
+ AddDimensionedImage.EXPAND_ROW_AND_COLUMN);\r
+ fos = new FileOutputStream(outputFile);\r
+ workbook.write(fos);\r
+ fos.close();\r
+ workbook.close();\r
}\r
\r
/**\r
\r
package org.apache.poi.ss.examples;\r
\r
-import org.apache.poi.hssf.usermodel.*;\r
-import org.apache.poi.ss.usermodel.*;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.ss.usermodel.BuiltinFormats;\r
+import org.apache.poi.ss.usermodel.CellStyle;\r
+import org.apache.poi.ss.usermodel.ColorScaleFormatting;\r
+import org.apache.poi.ss.usermodel.ComparisonOperator;\r
+import org.apache.poi.ss.usermodel.ConditionalFormattingRule;\r
import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType;\r
+import org.apache.poi.ss.usermodel.DataBarFormatting;\r
+import org.apache.poi.ss.usermodel.ExtendedColor;\r
+import org.apache.poi.ss.usermodel.FontFormatting;\r
+import org.apache.poi.ss.usermodel.IconMultiStateFormatting;\r
import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet;\r
+import org.apache.poi.ss.usermodel.IndexedColors;\r
+import org.apache.poi.ss.usermodel.PatternFormatting;\r
+import org.apache.poi.ss.usermodel.Row;\r
+import org.apache.poi.ss.usermodel.Sheet;\r
+import org.apache.poi.ss.usermodel.SheetConditionalFormatting;\r
+import org.apache.poi.ss.usermodel.Workbook;\r
import org.apache.poi.ss.util.CellRangeAddress;\r
import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
/**\r
* Excel Conditional Formatting -- Examples\r
*\r
public static void main(String[] args) throws IOException {\r
Workbook wb;\r
\r
- if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook();\r
- else wb = new XSSFWorkbook();\r
+ if(args.length > 0 && args[0].equals("-xls")) {\r
+ wb = new HSSFWorkbook();\r
+ } else {\r
+ wb = new XSSFWorkbook();\r
+ }\r
\r
sameCell(wb.createSheet("Same Cell"));\r
multiCell(wb.createSheet("MultiCell"));\r
\r
// Write the output to a file\r
String file = "cf-poi.xls";\r
- if(wb instanceof XSSFWorkbook) file += "x";\r
+ if(wb instanceof XSSFWorkbook) {\r
+ file += "x";\r
+ }\r
FileOutputStream out = new FileOutputStream(file);\r
wb.write(out);\r
out.close();\r
System.out.println("Generated: " + file);\r
+ wb.close();\r
}\r
\r
/**\r
Row r = sheet.createRow(i);\r
r.createCell(0).setCellValue("This is row " + rn + " (" + i + ")");\r
String str = "";\r
- if (rn%2 == 0) str = str + "even ";\r
- if (rn%3 == 0) str = str + "x3 ";\r
- if (rn%5 == 0) str = str + "x5 ";\r
- if (rn%10 == 0) str = str + "x10 ";\r
- if (str.length() == 0) str = "nothing special...";\r
+ if (rn%2 == 0) {\r
+ str = str + "even ";\r
+ }\r
+ if (rn%3 == 0) {\r
+ str = str + "x3 ";\r
+ }\r
+ if (rn%5 == 0) {\r
+ str = str + "x5 ";\r
+ }\r
+ if (rn%10 == 0) {\r
+ str = str + "x10 ";\r
+ }\r
+ if (str.length() == 0) {\r
+ str = "nothing special...";\r
+ }\r
r.createCell(1).setCellValue("It is " + str);\r
}\r
sheet.autoSizeColumn(0);\r
sheet.createRow(2).createCell(0).setCellFormula("A2+1");\r
sheet.createRow(3).createCell(0).setCellFormula("A3+1");\r
\r
- for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style);\r
+ for(int rownum = 1; rownum <= 3; rownum++) {\r
+ sheet.getRow(rownum).getCell(0).setCellStyle(style);\r
+ }\r
\r
SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
\r
==================================================================== */\r
\r
package org.apache.poi.ss.examples;\r
-import java.io.*;\r
-import org.apache.poi.xssf.usermodel.*;\r
-import org.apache.poi.hssf.usermodel.*;\r
-import org.apache.poi.ss.usermodel.*;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.ss.usermodel.Cell;\r
+import org.apache.poi.ss.usermodel.DataValidation;\r
+import org.apache.poi.ss.usermodel.DataValidationConstraint;\r
+import org.apache.poi.ss.usermodel.DataValidationHelper;\r
+import org.apache.poi.ss.usermodel.Name;\r
+import org.apache.poi.ss.usermodel.Row;\r
+import org.apache.poi.ss.usermodel.Sheet;\r
+import org.apache.poi.ss.usermodel.Workbook;\r
import org.apache.poi.ss.util.CellRangeAddressList;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
\r
/**\r
* Demonstrates one technique that may be used to create linked or dependent\r
*/\r
public class LinkedDropDownLists {\r
\r
- LinkedDropDownLists(String workbookName) {\r
- File file = null;\r
- FileOutputStream fos = null;\r
- Workbook workbook = null;\r
- Sheet sheet = null;\r
- DataValidationHelper dvHelper = null;\r
- DataValidationConstraint dvConstraint = null;\r
- DataValidation validation = null;\r
- CellRangeAddressList addressList = null;\r
- try {\r
-\r
- // Using the ss.usermodel allows this class to support both binary\r
- // and xml based workbooks. The choice of which one to create is\r
- // made by checking the file extension.\r
- if (workbookName.endsWith(".xlsx")) {\r
- workbook = new XSSFWorkbook();\r
- } else {\r
- workbook = new HSSFWorkbook();\r
- }\r
- \r
- // Build the sheet that will hold the data for the validations. This\r
- // must be done first as it will create names that are referenced \r
- // later.\r
- sheet = workbook.createSheet("Linked Validations");\r
- LinkedDropDownLists.buildDataSheet(sheet);\r
-\r
- // Build the first data validation to occupy cell A1. Note\r
- // that it retrieves it's data from the named area or region called\r
- // CHOICES. Further information about this can be found in the\r
- // static buildDataSheet() method below.\r
- addressList = new CellRangeAddressList(0, 0, 0, 0);\r
- dvHelper = sheet.getDataValidationHelper();\r
- dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");\r
- validation = dvHelper.createValidation(dvConstraint, addressList);\r
- sheet.addValidationData(validation);\r
- \r
- // Now, build the linked or dependent drop down list that will\r
- // occupy cell B1. The key to the whole process is the use of the\r
- // INDIRECT() function. In the buildDataSheet(0 method, a series of\r
- // named regions are created and the names of three of them mirror\r
- // the options available to the user in the first drop down list\r
- // (in cell A1). Using the INDIRECT() function makes it possible\r
- // to convert the selection the user makes in that first drop down\r
- // into the addresses of a named region of cells and then to use\r
- // those cells to populate the second drop down list.\r
- addressList = new CellRangeAddressList(0, 0, 1, 1);\r
- dvConstraint = dvHelper.createFormulaListConstraint(\r
- "INDIRECT(UPPER($A$1))");\r
- validation = dvHelper.createValidation(dvConstraint, addressList);\r
- sheet.addValidationData(validation);\r
- \r
- file = new File(workbookName);\r
- fos = new FileOutputStream(file);\r
- workbook.write(fos);\r
- } catch (IOException ioEx) {\r
- System.out.println("Caught a: " + ioEx.getClass().getName());\r
- System.out.println("Message: " + ioEx.getMessage());\r
- System.out.println("Stacktrace follws:.....");\r
- ioEx.printStackTrace(System.out);\r
- } finally {\r
- try {\r
- if (fos != null) {\r
- fos.close();\r
- fos = null;\r
- }\r
- } catch (IOException ioEx) {\r
- System.out.println("Caught a: " + ioEx.getClass().getName());\r
- System.out.println("Message: " + ioEx.getMessage());\r
- System.out.println("Stacktrace follws:.....");\r
- ioEx.printStackTrace(System.out);\r
- }\r
+ LinkedDropDownLists(String workbookName) throws IOException {\r
+ // Using the ss.usermodel allows this class to support both binary\r
+ // and xml based workbooks. The choice of which one to create is\r
+ // made by checking the file extension.\r
+ Workbook workbook;\r
+ if (workbookName.endsWith(".xlsx")) {\r
+ workbook = new XSSFWorkbook();\r
+ } else {\r
+ workbook = new HSSFWorkbook();\r
}\r
+ \r
+ // Build the sheet that will hold the data for the validations. This\r
+ // must be done first as it will create names that are referenced \r
+ // later.\r
+ Sheet sheet = workbook.createSheet("Linked Validations");\r
+ LinkedDropDownLists.buildDataSheet(sheet);\r
+\r
+ // Build the first data validation to occupy cell A1. Note\r
+ // that it retrieves it's data from the named area or region called\r
+ // CHOICES. Further information about this can be found in the\r
+ // static buildDataSheet() method below.\r
+ CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);\r
+ DataValidationHelper dvHelper = sheet.getDataValidationHelper();\r
+ DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");\r
+ DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);\r
+ sheet.addValidationData(validation);\r
+ \r
+ // Now, build the linked or dependent drop down list that will\r
+ // occupy cell B1. The key to the whole process is the use of the\r
+ // INDIRECT() function. In the buildDataSheet(0 method, a series of\r
+ // named regions are created and the names of three of them mirror\r
+ // the options available to the user in the first drop down list\r
+ // (in cell A1). Using the INDIRECT() function makes it possible\r
+ // to convert the selection the user makes in that first drop down\r
+ // into the addresses of a named region of cells and then to use\r
+ // those cells to populate the second drop down list.\r
+ addressList = new CellRangeAddressList(0, 0, 1, 1);\r
+ dvConstraint = dvHelper.createFormulaListConstraint(\r
+ "INDIRECT(UPPER($A$1))");\r
+ validation = dvHelper.createValidation(dvConstraint, addressList);\r
+ sheet.addValidationData(validation);\r
+ \r
+ FileOutputStream fos = new FileOutputStream(workbookName);\r
+ workbook.write(fos);\r
+ fos.close();\r
+ workbook.close();\r
}\r
\r
/**\r
package org.apache.poi.ss.examples;
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
+import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hssf.usermodel.HSSFObjectData;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
-import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
-import org.apache.poi.xslf.usermodel.XSLFSlideShow;
+import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import org.apache.xmlbeans.XmlException;
/**
* Loads embedded resources from Workbooks. Code taken from the website:
* https://poi.apache.org/spreadsheet/quick-guide.html#Embedded
*/
public class LoadEmbedded {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException, EncryptedDocumentException, OpenXML4JException, XmlException {
Workbook wb = WorkbookFactory.create(new File(args[0]));
loadEmbedded(wb);
}
- public static void loadEmbedded(Workbook wb) throws Exception {
+ public static void loadEmbedded(Workbook wb) throws IOException, InvalidFormatException, OpenXML4JException, XmlException {
if (wb instanceof HSSFWorkbook) {
loadEmbedded((HSSFWorkbook)wb);
}
}
}
- public static void loadEmbedded(HSSFWorkbook workbook) throws Exception {
+ public static void loadEmbedded(HSSFWorkbook workbook) throws IOException {
for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
//the OLE2 Class Name of the object
String oleName = obj.getOLE2ClassName();
if (oleName.equals("Worksheet")) {
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, false);
- //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets());
+ embeddedWorkbook.close();
} else if (oleName.equals("Document")) {
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
HWPFDocument embeddedWordDocument = new HWPFDocument(dn);
- //System.out.println(entry.getName() + ": " + embeddedWordDocument.getRange().text());
+ embeddedWordDocument.close();
} else if (oleName.equals("Presentation")) {
DirectoryNode dn = (DirectoryNode) obj.getDirectory();
- SlideShow<?,?> embeddedPowerPointDocument = new HSLFSlideShow(dn);
- //System.out.println(entry.getName() + ": " + embeddedPowerPointDocument.getSlides().length);
+ SlideShow<?,?> embeddedSlieShow = new HSLFSlideShow(dn);
+ embeddedSlieShow.close();
} else {
if(obj.hasDirectoryEntry()){
// The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
}
}
- public static void loadEmbedded(XSSFWorkbook workbook) throws Exception {
+ public static void loadEmbedded(XSSFWorkbook workbook) throws IOException, InvalidFormatException, OpenXML4JException, XmlException {
for (PackagePart pPart : workbook.getAllEmbedds()) {
String contentType = pPart.getContentType();
- // Excel Workbook - either binary or OpenXML
if (contentType.equals("application/vnd.ms-excel")) {
+ // Excel Workbook - either binary or OpenXML
HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());
- }
- // Excel Workbook - OpenXML file format
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
- OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
- XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(docPackage);
- }
- // Word Document - binary (OLE2CDF) file format
- else if (contentType.equals("application/msword")) {
+ embeddedWorkbook.close();
+ } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
+ // Excel Workbook - OpenXML file format
+ XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());
+ embeddedWorkbook.close();
+ } else if (contentType.equals("application/msword")) {
+ // Word Document - binary (OLE2CDF) file format
HWPFDocument document = new HWPFDocument(pPart.getInputStream());
- }
- // Word Document - OpenXML file format
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
- OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
- XWPFDocument document = new XWPFDocument(docPackage);
- }
- // PowerPoint Document - binary file format
- else if (contentType.equals("application/vnd.ms-powerpoint")) {
+ document.close();
+ } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
+ // Word Document - OpenXML file format
+ XWPFDocument document = new XWPFDocument(pPart.getInputStream());
+ document.close();
+ } else if (contentType.equals("application/vnd.ms-powerpoint")) {
+ // PowerPoint Document - binary file format
HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream());
- }
- // PowerPoint Document - OpenXML file format
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
- OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
- XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);
- }
- // Any other type of embedded object.
- else {
+ slideShow.close();
+ } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
+ // PowerPoint Document - OpenXML file format
+ XMLSlideShow slideShow = new XMLSlideShow(pPart.getInputStream());
+ slideShow.close();
+ } else {
+ // Any other type of embedded object.
System.out.println("Unknown Embedded Document: " + contentType);
InputStream inputStream = pPart.getInputStream();
+ inputStream.close();
}
}
}
==================================================================== */\r
package org.apache.poi.xssf.usermodel.examples;\r
\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+import java.io.InputStream;\r
+\r
+import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.hwpf.HWPFDocument;\r
import org.apache.poi.openxml4j.opc.OPCPackage;\r
import org.apache.poi.openxml4j.opc.PackagePart;\r
import org.apache.poi.xslf.usermodel.XSLFSlideShow;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
-import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;\r
-import org.apache.poi.hwpf.HWPFDocument;\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
-\r
-import java.io.InputStream;\r
\r
/**\r
* Demonstrates how you can extract embedded data from a .xlsx file\r
*/\r
public class EmbeddedObjects {\r
public static void main(String[] args) throws Exception {\r
- OPCPackage pkg = OPCPackage.open(args[0]);\r
- XSSFWorkbook workbook = new XSSFWorkbook(pkg);\r
+ XSSFWorkbook workbook = new XSSFWorkbook(args[0]);\r
for (PackagePart pPart : workbook.getAllEmbedds()) {\r
String contentType = pPart.getContentType();\r
- // Excel Workbook - either binary or OpenXML\r
if (contentType.equals("application/vnd.ms-excel")) {\r
+ // Excel Workbook - either binary or OpenXML\r
HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());\r
- }\r
- // Excel Workbook - OpenXML file format\r
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {\r
+ embeddedWorkbook.close();\r
+ } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {\r
+ // Excel Workbook - OpenXML file format\r
XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());\r
- }\r
- // Word Document - binary (OLE2CDF) file format\r
- else if (contentType.equals("application/msword")) {\r
+ embeddedWorkbook.close();\r
+ } else if (contentType.equals("application/msword")) {\r
+ // Word Document - binary (OLE2CDF) file format\r
HWPFDocument document = new HWPFDocument(pPart.getInputStream());\r
- }\r
- // Word Document - OpenXML file format\r
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {\r
+ document.close();\r
+ } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {\r
+ // Word Document - OpenXML file format\r
XWPFDocument document = new XWPFDocument(pPart.getInputStream());\r
- }\r
- // PowerPoint Document - binary file format\r
- else if (contentType.equals("application/vnd.ms-powerpoint")) {\r
+ document.close();\r
+ } else if (contentType.equals("application/vnd.ms-powerpoint")) {\r
+ // PowerPoint Document - binary file format\r
HSLFSlideShowImpl slideShow = new HSLFSlideShowImpl(pPart.getInputStream());\r
- }\r
- // PowerPoint Document - OpenXML file format\r
- else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {\r
+ slideShow.close();\r
+ } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {\r
+ // PowerPoint Document - OpenXML file format\r
OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());\r
XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);\r
- }\r
- // Any other type of embedded object.\r
- else {\r
+ slideShow.close();\r
+ } else {\r
+ // Any other type of embedded object.\r
System.out.println("Unknown Embedded Document: " + contentType);\r
InputStream inputStream = pPart.getInputStream();\r
+ inputStream.close();\r
}\r
}\r
- pkg.close();\r
+ workbook.close();\r
}\r
}
\ No newline at end of file
out.writeShort(encryptionType);
byte data[] = new byte[1024];
- LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(data, 0);
+ LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(data, 0); // NOSONAR
switch (encryptionInfo.getEncryptionMode()) {
case xor:
public int serialize(int offset, byte[] data) {
int recSize = getRecordSize();
int dataSize = recSize - 4;
- LittleEndianByteArrayOutputStream out = new LittleEndianByteArrayOutputStream(data, offset, recSize);
+ LittleEndianByteArrayOutputStream out = new LittleEndianByteArrayOutputStream(data, offset, recSize); // NOSONAR
out.writeShort(sid);
out.writeShort(dataSize);
private void convertLabelRecords(List<Record> records, int offset)
{
- if (log.check( POILogger.DEBUG ))
- log.log(POILogger.DEBUG, "convertLabelRecords called");
+ if (log.check( POILogger.DEBUG )) {
+ log.log(POILogger.DEBUG, "convertLabelRecords called");
+ }
for (int k = offset; k < records.size(); k++)
{
Record rec = records.get(k);
records.add(k, newrec);
}
}
- if (log.check( POILogger.DEBUG ))
- log.log(POILogger.DEBUG, "convertLabelRecords exit");
+ if (log.check( POILogger.DEBUG )) {
+ log.log(POILogger.DEBUG, "convertLabelRecords exit");
+ }
}
/**
throw new IllegalArgumentException("sheetName must not be null");
}
- if (workbook.doesContainsSheetName( sheetname, _sheets.size() ))
+ if (workbook.doesContainsSheetName( sheetname, _sheets.size() )) {
throw new IllegalArgumentException("The workbook already contains a sheet named '" + sheetname + "'");
+ }
HSSFSheet sheet = new HSSFSheet(this);
short numberOfFonts = getNumberOfFonts();
for (short i=0; i<=numberOfFonts; i++) {
// Remember - there is no 4!
- if(i == 4) continue;
+ if(i == 4) {
+ continue;
+ }
HSSFFont hssfFont = getFontAt(i);
if (hssfFont.getBoldweight() == boldWeight
short numberOfFonts = getNumberOfFonts();
for (short i=0; i<=numberOfFonts; i++) {
// Remember - there is no 4!
- if(i == 4) continue;
+ if(i == 4) {
+ continue;
+ }
HSSFFont hssfFont = getFontAt(i);
if (hssfFont.getBold() == bold
*/
@Override
public HSSFFont getFontAt(short idx) {
- if(fonts == null) fonts = new HashMap<Short, HSSFFont>();
+ if(fonts == null) {
+ fonts = new HashMap<Short, HSSFFont>();
+ }
// So we don't confuse users, give them back
// the same object every time, but create
return;
}
- LittleEndianByteArrayInputStream plain = new LittleEndianByteArrayInputStream(buf, 0);
- LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0);
+ LittleEndianByteArrayInputStream plain = new LittleEndianByteArrayInputStream(buf, 0); // NOSONAR
+ LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0); // NOSONAR
Encryptor enc = fpr.getEncryptionInfo().getEncryptor();
enc.setChunkSize(Biff8DecryptingStream.RC4_REKEYING_INTERVAL);
byte tmp[] = new byte[1024];
*/
@Override
public HSSFDataFormat createDataFormat() {
- if (formatter == null)
+ if (formatter == null) {
formatter = new HSSFDataFormat(workbook);
+ }
return formatter;
}
List<EscherRecord> escherRecords = r.getEscherRecords();
PrintWriter w = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()));
for (EscherRecord escherRecord : escherRecords) {
- if (fat)
+ if (fat) {
System.out.println(escherRecord.toString());
- else
+ } else {
escherRecord.display(w, 0);
+ }
}
w.flush();
}
/**
* @deprecated POI 3.16 beta 1. use {@link POIDocument#getDirectory()} instead
*/
+ @Deprecated
@Removal(version="3.18")
public DirectoryNode getRootDirectory(){
return getDirectory();
public static void viewFile(final String filename, boolean withSizes) throws IOException {
NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(filename));
displayDirectory(fs.getRoot(), "", withSizes);
+ fs.close();
}
public static void viewFileOld(final String filename, boolean withSizes) throws IOException {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filename));
displayDirectory(fs.getRoot(), "", withSizes);
+ fs.close();
}
public static void displayDirectory(DirectoryNode dir, String indent, boolean withSizes) {
throw new IllegalArgumentException("path must not be a directory");
}
- OPCPackage pack = new ZipPackage(path, access);
+ OPCPackage pack = new ZipPackage(path, access); // NOSONAR
boolean success = false;
if (pack.partList == null && access != PackageAccess.WRITE) {
try {
}
// Check if part already exist
- if (this.getPart(thumbnailPartName) != null)
+ if (this.getPart(thumbnailPartName) != null) {
throw new InvalidOperationException(
"You already add a thumbnail named '" + filename + "'");
+ }
// Add the thumbnail part to this package.
PackagePart thumbnailPart = this.createPart(thumbnailPartName,
fos = new FileOutputStream(targetFile);
this.save(fos);
} finally {
- if (fos != null) fos.close();
+ if (fos != null) {
+ fos.close();
+ }
}
}
package org.apache.poi.hslf.dev;
+import java.io.IOException;
import java.util.List;
-import org.apache.poi.hslf.model.textproperties.*;
-import org.apache.poi.hslf.record.*;
+import org.apache.poi.hslf.model.textproperties.BitMaskTextProp;
+import org.apache.poi.hslf.model.textproperties.TextProp;
+import org.apache.poi.hslf.model.textproperties.TextPropCollection;
+import org.apache.poi.hslf.record.Record;
+import org.apache.poi.hslf.record.SlideListWithText;
+import org.apache.poi.hslf.record.StyleTextPropAtom;
+import org.apache.poi.hslf.record.TextBytesAtom;
+import org.apache.poi.hslf.record.TextCharsAtom;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
/**
* Having found them, it shows the contents
*/
public final class TextStyleListing {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
if(args.length < 1) {
System.err.println("Need to give a filename");
System.exit(1);
}
}
}
+
+ ss.close();
}
public static void showStyleTextPropAtom(StyleTextPropAtom stpa) {
package org.apache.poi.hslf.dev;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.util.Map;
import org.apache.poi.hslf.record.CurrentUserAtom;
public final class UserEditAndPersistListing {
private static byte[] fileContents;
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
if(args.length < 1) {
System.err.println("Need to give a filename");
System.exit(1);
System.out.println("");
// Find any persist ones first
- Record[] records = ss.getRecords();
int pos = 0;
- for(int i=0; i<records.length; i++) {
- Record r = records[i];
-
+ for(Record r : ss.getRecords()) {
if(r.getRecordType() == 6001l) {
// PersistPtrFullBlock
System.out.println("Found PersistPtrFullBlock at " + pos + " (" + Integer.toHexString(pos) + ")");
PersistPtrHolder pph = (PersistPtrHolder)r;
// Check the sheet offsets
- int[] sheetIDs = pph.getKnownSlideIDs();
Map<Integer,Integer> sheetOffsets = pph.getSlideLocationsLookup();
- for(int j=0; j<sheetIDs.length; j++) {
- Integer id = sheetIDs[j];
+ for(int id : pph.getKnownSlideIDs()) {
Integer offset = sheetOffsets.get(id);
System.out.println(" Knows about sheet " + id);
pos = 0;
// Now look for UserEditAtoms
- for(int i=0; i<records.length; i++) {
- Record r = records[i];
-
+ for(Record r : ss.getRecords()) {
if(r instanceof UserEditAtom) {
UserEditAtom uea = (UserEditAtom)r;
System.out.println("Found UserEditAtom at " + pos + " (" + Integer.toHexString(pos) + ")");
CurrentUserAtom cua = ss.getCurrentUserAtom();
System.out.println("Checking Current User Atom");
System.out.println(" Thinks the CurrentEditOffset is " + cua.getCurrentEditOffset());
-
+
System.out.println("");
+
+ ss.close();
}
import java.io.FileOutputStream;
import java.io.IOException;
-import java.util.List;
import org.apache.poi.hslf.usermodel.HSLFPictureData;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
/**
* Utility to extract pictures from a PowerPoint file.
- *
- * @author Yegor Kozlov
*/
public final class ImageExtractor {
public static void main(String args[]) throws IOException {
HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl(args[0]));
//extract all pictures contained in the presentation
- List<HSLFPictureData> pdata = ppt.getPictureData();
- for (int i = 0; i < pdata.size(); i++) {
- HSLFPictureData pict = pdata.get(i);
-
+ int i = 0;
+ for (HSLFPictureData pict : ppt.getPictureData()) {
// picture data
byte[] data = pict.getData();
PictureType type = pict.getType();
- FileOutputStream out = new FileOutputStream("pict_" + i + type.extension);
+ FileOutputStream out = new FileOutputStream("pict_" + i++ + type.extension);
out.write(data);
out.close();
}
+
+ ppt.close();
}
}
/**
* Return the value we were given at creation, be it 6001 or 6002
*/
+ @Override
public long getRecordType() { return _type; }
/**
TreeMap<Integer,Integer> orderedSlideLocations = new TreeMap<Integer,Integer>(_slideLocations);
@SuppressWarnings("resource")
- BufAccessBAOS bos = new BufAccessBAOS();
+ BufAccessBAOS bos = new BufAccessBAOS(); // NOSONAR
byte intbuf[] = new byte[4];
int lastPersistEntry = -1;
int lastSlideId = -1;
* Write the contents of the record back, so it can be written
* to disk
*/
- public void writeOut(OutputStream out) throws IOException {
+ @Override
+ public void writeOut(OutputStream out) throws IOException {
normalizePersistDirectory();
out.write(_header);
out.write(_ptrData);
* Gets the record type.
* @return the record type.
*/
+ @Override
public long getRecordType() { return _type; }
/**
* @param out the output stream to write to.
* @throws java.io.IOException if an error occurs.
*/
+ @Override
public void writeOut(OutputStream out) throws IOException {
out.write(_header);
out.write(_data);
*/
public int getCharactersCovered(){
int covered = 0;
- for (TextSpecInfoRun r : getTextSpecInfoRuns()) covered += r.getLength();
+ for (TextSpecInfoRun r : getTextSpecInfoRuns()) {
+ covered += r.getLength();
+ }
return covered;
}
public TextSpecInfoRun[] getTextSpecInfoRuns(){
- LittleEndianByteArrayInputStream bis = new LittleEndianByteArrayInputStream(_data);
+ LittleEndianByteArrayInputStream bis = new LittleEndianByteArrayInputStream(_data); // NOSONAR
List<TextSpecInfoRun> lst = new ArrayList<TextSpecInfoRun>();
while (bis.available() > 0) {
lst.add(new TextSpecInfoRun(bis));
decryptInit();
dec.setChunkSize(-1);
- LittleEndianByteArrayInputStream lei = new LittleEndianByteArrayInputStream(docstream, offset);
+ LittleEndianByteArrayInputStream lei = new LittleEndianByteArrayInputStream(docstream, offset); // NOSONAR
ChunkedCipherInputStream ccis = null;
try {
ccis = dec.getDataStream(lei, docstream.length-offset, 0);
encryptInit();
- LittleEndianByteArrayOutputStream los = new LittleEndianByteArrayOutputStream(pictstream, offset);
+ LittleEndianByteArrayOutputStream los = new LittleEndianByteArrayOutputStream(pictstream, offset); // NOSONAR
ChunkedCipherOutputStream ccos = null;
try {
}
}
+ @Override
public void close() throws IOException {
if (cyos != null) {
cyos.close();
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
+import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.poi.util.Removal;
*
* @deprecated POI 3.16 beta 1. use {@link POIDocument#getDirectory()} instead
*/
+ @Deprecated
@Removal(version="3.18")
protected DirectoryNode getPOIFSDirectory() {
return getDirectory();
private static DirectoryNode handleDualStorage(DirectoryNode dir) throws IOException {
// when there's a dual storage entry, use it, as the outer document can't be read quite probably ...
String dualName = "PP97_DUALSTORAGE";
- if (!dir.hasEntry(dualName)) return dir;
+ if (!dir.hasEntry(dualName)) {
+ return dir;
+ }
dir = (DirectoryNode) dir.getEntry(dualName);
return dir;
}
* Builds the list of records, based on the contents
* of the PowerPoint stream
*/
- private void buildRecords() {
+ private void buildRecords() throws IOException {
// The format of records in a powerpoint file are:
// <little endian 2 byte "info">
// <little endian 2 byte "type">
_records = read(_docstream, (int) currentUser.getCurrentEditOffset());
}
- private Record[] read(byte[] docstream, int usrOffset) {
+ private Record[] read(byte[] docstream, int usrOffset) throws IOException {
//sort found records by offset.
//(it is not necessary but SlideShow.findMostRecentCoreRecords() expects them sorted)
NavigableMap<Integer, Record> records = new TreeMap<Integer, Record>(); // offset -> record
}
}
+ decryptData.close();
return records.values().toArray(new Record[records.size()]);
}
_pictures = new ArrayList<HSLFPictureData>();
// if the presentation doesn't contain pictures - will use a null set instead
- if (!getDirectory().hasEntry("Pictures")) return;
-
- HSLFSlideShowEncrypted decryptData = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom());
+ if (!getDirectory().hasEntry("Pictures")) {
+ return;
+ }
DocumentEntry entry = (DocumentEntry) getDirectory().getEntry("Pictures");
DocumentInputStream is = getDirectory().createDocumentInputStream(entry);
byte[] pictstream = IOUtils.toByteArray(is, entry.getSize());
is.close();
- int pos = 0;
- // An empty picture record (length 0) will take up 8 bytes
- while (pos <= (pictstream.length - 8)) {
- int offset = pos;
-
- decryptData.decryptPicture(pictstream, offset);
-
- // Image signature
- int signature = LittleEndian.getUShort(pictstream, pos);
- pos += LittleEndian.SHORT_SIZE;
- // Image type + 0xF018
- int type = LittleEndian.getUShort(pictstream, pos);
- pos += LittleEndian.SHORT_SIZE;
- // Image size (excluding the 8 byte header)
- int imgsize = LittleEndian.getInt(pictstream, pos);
- pos += LittleEndian.INT_SIZE;
-
- // When parsing the BStoreDelay stream, [MS-ODRAW] says that we
- // should terminate if the type isn't 0xf007 or 0xf018->0xf117
- if (!((type == 0xf007) || (type >= 0xf018 && type <= 0xf117)))
- break;
-
- // The image size must be 0 or greater
- // (0 is allowed, but odd, since we do wind on by the header each
- // time, so we won't get stuck)
- if (imgsize < 0) {
- throw new CorruptPowerPointFileException("The file contains a picture, at position " + _pictures.size() + ", which has a negatively sized data length, so we can't trust any of the picture data");
- }
-
- // If they type (including the bonus 0xF018) is 0, skip it
- PictureType pt = PictureType.forNativeID(type - 0xF018);
- if (pt == null) {
- logger.log(POILogger.ERROR, "Problem reading picture: Invalid image type 0, on picture with length " + imgsize + ".\nYou document will probably become corrupted if you save it!");
- logger.log(POILogger.ERROR, "" + pos);
- } else {
- //The pictstream can be truncated halfway through a picture.
- //This is not a problem if the pictstream contains extra pictures
- //that are not used in any slide -- BUG-60305
- if (pos+imgsize > pictstream.length) {
- logger.log(POILogger.WARN, "\"Pictures\" stream may have ended early. In some circumstances, this is not a problem; " +
- "in others, this could indicate a corrupt file");
+ HSLFSlideShowEncrypted decryptData = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom());
+ try {
+
+ int pos = 0;
+ // An empty picture record (length 0) will take up 8 bytes
+ while (pos <= (pictstream.length - 8)) {
+ int offset = pos;
+
+ decryptData.decryptPicture(pictstream, offset);
+
+ // Image signature
+ int signature = LittleEndian.getUShort(pictstream, pos);
+ pos += LittleEndianConsts.SHORT_SIZE;
+ // Image type + 0xF018
+ int type = LittleEndian.getUShort(pictstream, pos);
+ pos += LittleEndianConsts.SHORT_SIZE;
+ // Image size (excluding the 8 byte header)
+ int imgsize = LittleEndian.getInt(pictstream, pos);
+ pos += LittleEndianConsts.INT_SIZE;
+
+ // When parsing the BStoreDelay stream, [MS-ODRAW] says that we
+ // should terminate if the type isn't 0xf007 or 0xf018->0xf117
+ if (!((type == 0xf007) || (type >= 0xf018 && type <= 0xf117))) {
break;
}
- // Build the PictureData object from the data
- try {
- HSLFPictureData pict = HSLFPictureData.create(pt);
- pict.setSignature(signature);
-
- // Copy the data, ready to pass to PictureData
- byte[] imgdata = new byte[imgsize];
- System.arraycopy(pictstream, pos, imgdata, 0, imgdata.length);
- pict.setRawData(imgdata);
-
- pict.setOffset(offset);
- pict.setIndex(_pictures.size());
- _pictures.add(pict);
- } catch (IllegalArgumentException e) {
- logger.log(POILogger.ERROR, "Problem reading picture: " + e + "\nYou document will probably become corrupted if you save it!");
+
+ // The image size must be 0 or greater
+ // (0 is allowed, but odd, since we do wind on by the header each
+ // time, so we won't get stuck)
+ if (imgsize < 0) {
+ throw new CorruptPowerPointFileException("The file contains a picture, at position " + _pictures.size() + ", which has a negatively sized data length, so we can't trust any of the picture data");
+ }
+
+ // If they type (including the bonus 0xF018) is 0, skip it
+ PictureType pt = PictureType.forNativeID(type - 0xF018);
+ if (pt == null) {
+ logger.log(POILogger.ERROR, "Problem reading picture: Invalid image type 0, on picture with length " + imgsize + ".\nYou document will probably become corrupted if you save it!");
+ logger.log(POILogger.ERROR, "" + pos);
+ } else {
+ //The pictstream can be truncated halfway through a picture.
+ //This is not a problem if the pictstream contains extra pictures
+ //that are not used in any slide -- BUG-60305
+ if (pos+imgsize > pictstream.length) {
+ logger.log(POILogger.WARN, "\"Pictures\" stream may have ended early. In some circumstances, this is not a problem; " +
+ "in others, this could indicate a corrupt file");
+ break;
+ }
+ // Build the PictureData object from the data
+ try {
+ HSLFPictureData pict = HSLFPictureData.create(pt);
+ pict.setSignature(signature);
+
+ // Copy the data, ready to pass to PictureData
+ byte[] imgdata = new byte[imgsize];
+ System.arraycopy(pictstream, pos, imgdata, 0, imgdata.length);
+ pict.setRawData(imgdata);
+
+ pict.setOffset(offset);
+ pict.setIndex(_pictures.size());
+ _pictures.add(pict);
+ } catch (IllegalArgumentException e) {
+ logger.log(POILogger.ERROR, "Problem reading picture: " + e + "\nYou document will probably become corrupted if you save it!");
+ }
}
+
+ pos += imgsize;
}
-
- pos += imgsize;
+ } finally {
+ decryptData.close();
}
}
// Tell them of the positions of the other records though
PositionDependentRecord pdr = (PositionDependentRecord) record;
Integer persistId = persistIds.get(pdr.getLastOnDiskOffset());
- if (persistId == null) persistId = 0;
+ if (persistId == null) {
+ persistId = 0;
+ }
// For now, we're only handling PositionDependentRecord's that
// happen at the top level.
pict.close();
}
+ encryptedSS.close();
+
// If requested, copy over any other streams we spot, eg Macros
if (copyAllOtherNodes) {
EntryUtils.copyNodes(getDirectory().getFileSystem(), outFS, writtenEntries);
* @param setName The property to read
* @return The value of the given property or null if it wasn't found.
*/
+ @Override
protected PropertySet getPropertySet(String setName) {
DocumentEncryptionAtom dea = getDocumentEncryptionAtom();
return (dea == null)
* @throws IOException if an error when writing to the
* {@link POIFSFileSystem} occurs
*/
+ @Override
protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException {
super.writeProperties(outFS, writtenEntries);
DocumentEncryptionAtom dea = getDocumentEncryptionAtom();
private static class CountingOS extends OutputStream {
int count = 0;
+ @Override
public void write(int b) throws IOException {
count++;
}
+ @Override
public void write(byte[] b) throws IOException {
count += b.length;
}
+ @Override
public void write(byte[] b, int off, int len) throws IOException {
count += len;
}