public static void save(final InputStream inputStream, final String filename, final String pwd)
throws InvalidFormatException, IOException, GeneralSecurityException {
+ POIFSFileSystem fs = null;
+ FileOutputStream fos = null;
+ OPCPackage opc = null;
try {
- POIFSFileSystem fs = new POIFSFileSystem();
+ fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = Encryptor.getInstance(info);
enc.confirmPassword(pwd);
- OPCPackage opc = OPCPackage.open(inputStream);
- try {
- FileOutputStream fos = new FileOutputStream(filename);
- try {
- opc.save(enc.getDataStream(fs));
- fs.writeFilesystem(fos);
- } finally {
- IOUtils.closeQuietly(fos);
- }
- } finally {
- IOUtils.closeQuietly(opc);
- }
+ opc = OPCPackage.open(inputStream);
+ fos = new FileOutputStream(filename);
+ opc.save(enc.getDataStream(fs));
+ fs.writeFilesystem(fos);
} finally {
+ IOUtils.closeQuietly(fos);
+ IOUtils.closeQuietly(opc);
+ IOUtils.closeQuietly(fs);
IOUtils.closeQuietly(inputStream);
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.util.Date;
-import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.CreationHelper;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.RichTextString;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
public class CreateCell {
- public static void main(String[]args) throws Exception {
+ 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");
FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
==================================================================== */
package org.apache.poi.xssf.usermodel.examples;
-import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
+
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
*/
public class CreateTable {
- public static void main(String[] args) throws FileNotFoundException,
- IOException {
+ public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
-import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
* Fills and Colors
*/
public class FillsAndColors {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
// Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
- style.setFillPattern(CellStyle.BIG_SPOTS);
+ 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(CellStyle.SOLID_FOREGROUND);
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell = row.createCell(2);
cell.setCellValue(new XSSFRichTextString("X"));
cell.setCellStyle(style);
FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
wb.write(fileOut);
fileOut.close();
-
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Sheet;
public class FitSheetToOnePage {
-
- public static void main(String[]args) throws Exception {
+ 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();
FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx");
wb.write(fileOut);
fileOut.close();
-
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
import org.apache.poi.ss.usermodel.Footer;
import org.apache.poi.ss.usermodel.Header;
public class HeadersAndFooters {
- public static void main(String[]args) throws Exception {
+ 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);
FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx");
wb.write(fileOut);
fileOut.close();
-
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.usermodel.Sheet;
+import java.io.FileInputStream;
+import java.io.IOException;
+
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
-
-import java.io.FileInputStream;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Iterate over rows and cells
*/
public class IterateCells {
- public static void main(String[] args) throws Exception {
+ 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);
}
}
}
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;\r
\r
import java.io.FileOutputStream;\r
+import java.io.IOException;\r
\r
import org.apache.poi.ss.usermodel.Cell;\r
import org.apache.poi.ss.usermodel.Chart;\r
*/\r
public class LineChart {\r
\r
- public static void main(String[] args) throws Exception {\r
+ public static void main(String[] args) throws IOException {\r
Workbook wb = new XSSFWorkbook();\r
Sheet sheet = wb.createSheet("linechart");\r
final int NUM_OF_ROWS = 3;\r
}\r
}\r
\r
- Drawing drawing = sheet.createDrawingPatriarch();\r
+ Drawing<?> drawing = sheet.createDrawingPatriarch();\r
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);\r
\r
Chart chart = drawing.createChart(anchor);\r
FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx");\r
wb.write(fileOut);\r
fileOut.close();\r
+ wb.close();\r
}\r
}\r
package org.apache.poi.xssf.usermodel.examples;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.Row;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
-
-import java.io.FileOutputStream;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* An example of how to merge regions of cells.
*/
public class MergingCells {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
*/
public class NewLinesInCells {
- public static void main(String[]args) throws Exception {
+ public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet();
FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.io.OutputStream;
import org.apache.poi.ss.usermodel.Sheet;
public class Outlining {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
Outlining o=new Outlining();
o.groupRowColumn();
o.collapseExpandRowColumn();
}
- private void groupRowColumn() throws Exception {
+ private void groupRowColumn() throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
wb.write(fileOut);
} finally {
fileOut.close();
+ wb.close();
}
}
- private void collapseExpandRowColumn() throws Exception {
+ private void collapseExpandRowColumn() throws IOException {
Workbook wb2 = new XSSFWorkbook();
Sheet sheet2 = wb2.createSheet("new sheet");
sheet2.groupRow( 5, 14 );
wb2.write(fileOut);
} finally {
fileOut.close();
+ wb2.close();
}
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
-import org.apache.poi.ss.usermodel.*;
-import org.apache.poi.ss.util.*;
-import org.apache.poi.ss.usermodel.charts.*;
+import java.io.IOException;
+
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Chart;
+import org.apache.poi.ss.usermodel.ClientAnchor;
+import org.apache.poi.ss.usermodel.Drawing;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.ss.usermodel.charts.AxisCrosses;
+import org.apache.poi.ss.usermodel.charts.AxisPosition;
+import org.apache.poi.ss.usermodel.charts.ChartDataSource;
+import org.apache.poi.ss.usermodel.charts.ChartLegend;
+import org.apache.poi.ss.usermodel.charts.DataSources;
+import org.apache.poi.ss.usermodel.charts.LegendPosition;
+import org.apache.poi.ss.usermodel.charts.ScatterChartData;
+import org.apache.poi.ss.usermodel.charts.ValueAxis;
+import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Illustrates how to create a simple scatter chart.
- *
- * @author Roman Kashitsyn
*/
public class ScatterChart {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet 1");
final int NUM_OF_ROWS = 3;
}
}
- Drawing drawing = sheet.createDrawingPatriarch();
+ Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor);
FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
*/
public class ShiftRows {
- public static void main(String[]args) throws Exception {
+ public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx");
wb.write(fileOut);
fileOut.close();
-
+ wb.close();
}
package org.apache.poi.xssf.usermodel.examples;
-import org.apache.poi.ss.usermodel.Workbook;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import java.io.FileOutputStream;
-
/**
- * How to set spklit and freeze panes
+ * How to set split and freeze panes
*/
public class SplitAndFreezePanes {
- public static void main(String[]args) throws Exception {
+ public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream;
+import java.io.IOException;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.POIXMLProperties;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
- * How to set extended and custom properties
- *
- * @author Yegor Kozlov
+ * How to set extended and custom properties
*/
public class WorkbookProperties {
- public static void main(String[]args) throws Exception {
+ public static void main(String[]args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.createSheet("Workbook Properties");
FileOutputStream out = new FileOutputStream("workbook.xlsx");
workbook.write(out);
out.close();
-
+ workbook.close();
}
package org.apache.poi.xssf.usermodel.examples;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.apache.poi.ss.usermodel.IndexedColors;
-import org.apache.poi.ss.usermodel.*;
-
import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.poi.ss.usermodel.BorderStyle;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.IndexedColors;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Working with borders
*/
public class WorkingWithBorders {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("borders");
// Style the cell with borders all around.
CellStyle style = wb.createCellStyle();
- style.setBorderBottom(CellStyle.BORDER_THIN);
+ style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
- style.setBorderLeft(CellStyle.BORDER_THIN);
+ style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
- style.setBorderRight(CellStyle.BORDER_THIN);
+ style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
- style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
+ style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(style);
FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
package org.apache.poi.xssf.usermodel.examples;
-import org.apache.poi.ss.usermodel.*;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.apache.poi.ss.usermodel.IndexedColors;
-
import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.IndexedColors;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Working with Fonts
*/
public class WorkingWithFonts {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("Fonts");
FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx");
wb.write(fileOut);
fileOut.close();
+ wb.close();
}
}
public class BetterHeaderFooterExample {
- public static void main(String[] args) {
+ public static void main(String[] args) throws IOException {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();
XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT);
foot.createParagraph().createRun().setText("footer");
- try {
- OutputStream os = new FileOutputStream(new File("header2.docx"));
- doc.write(os);
- doc.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ OutputStream os = new FileOutputStream(new File("header2.docx"));
+ doc.write(os);
+ os.close();
+ doc.close();
}
}
\r
import java.io.File;\r
import java.io.FileInputStream;\r
-import java.io.FileOutputStream;\r
import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
import java.util.List;\r
-import java.util.Iterator;\r
\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
+import org.apache.poi.openxml4j.opc.PackagePart;\r
+import org.apache.poi.ss.usermodel.Cell;\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.usermodel.WorkbookFactory;\r
+import org.apache.poi.util.IOUtils;\r
import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
-import org.apache.poi.ss.usermodel.Workbook;\r
-import org.apache.poi.ss.usermodel.Sheet;\r
-import org.apache.poi.ss.usermodel.Row;\r
-import org.apache.poi.ss.usermodel.Cell;\r
\r
/**\r
* Tests whether it is possible to successfully update an Excel workbook that is\r
* embedded into a WordprocessingML document. Note that the test has currently\r
* only been conducted with a binary Excel workbook and NOT yet with a\r
- * SpreadsheetML workbook embedded into the document.\r
- *\r
- * <p>\r
- * This code was successfully tested with the following file from the POI test collection:\r
- * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx\r
- * </p>\r
- *\r
- * @author Mark B\r
+ * SpreadsheetML workbook embedded into the document.<p>\r
+ * \r
+ * This code was successfully tested with the following file from the POI test collection:\r
+ * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx\r
*/\r
public class UpdateEmbeddedDoc {\r
\r
this.docFile = new File(filename);\r
FileInputStream fis = null;\r
if (!this.docFile.exists()) {\r
- throw new FileNotFoundException("The Word dcoument " +\r
- filename +\r
- " does not exist.");\r
+ throw new FileNotFoundException("The Word dcoument " + filename + " does not exist.");\r
}\r
try {\r
-\r
// Open the Word document file and instantiate the XWPFDocument\r
// class.\r
fis = new FileInputStream(this.docFile);\r
this.doc = new XWPFDocument(fis);\r
} finally {\r
- if (fis != null) {\r
- try {\r
- fis.close();\r
- fis = null;\r
- } catch (IOException ioEx) {\r
- System.out.println("IOException caught trying to close " +\r
- "FileInputStream in the constructor of " +\r
- "UpdateEmbeddedDoc.");\r
- }\r
- }\r
+ IOUtils.closeQuietly(fis);\r
}\r
}\r
\r
* file system.\r
*/\r
public void updateEmbeddedDoc() throws OpenXML4JException, IOException {\r
- Workbook workbook = null;\r
- Sheet sheet = null;\r
- Row row = null;\r
- Cell cell = null;\r
- PackagePart pPart = null;\r
- Iterator<PackagePart> pIter = null;\r
List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();\r
- if (embeddedDocs != null && !embeddedDocs.isEmpty()) {\r
- pIter = embeddedDocs.iterator();\r
- while (pIter.hasNext()) {\r
- pPart = pIter.next();\r
- if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||\r
- pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {\r
-\r
- // Get an InputStream from the pacage part and pass that\r
- // to the create method of the WorkbookFactory class. Update\r
- // the resulting Workbook and then stream that out again\r
- // using an OutputStream obtained from the same PackagePart.\r
- workbook = WorkbookFactory.create(pPart.getInputStream());\r
- sheet = workbook.getSheetAt(SHEET_NUM);\r
- row = sheet.getRow(ROW_NUM);\r
- cell = row.getCell(CELL_NUM);\r
+ for (PackagePart pPart : embeddedDocs) {\r
+ String ext = pPart.getPartName().getExtension();\r
+ if (BINARY_EXTENSION.equals(ext) || OPENXML_EXTENSION.equals(ext)) {\r
+ // Get an InputStream from the package part and pass that\r
+ // to the create method of the WorkbookFactory class. Update\r
+ // the resulting Workbook and then stream that out again\r
+ // using an OutputStream obtained from the same PackagePart.\r
+ InputStream is = pPart.getInputStream();\r
+ Workbook workbook = null;\r
+ OutputStream os = null;\r
+ try {\r
+ workbook = WorkbookFactory.create(is);\r
+ Sheet sheet = workbook.getSheetAt(SHEET_NUM);\r
+ Row row = sheet.getRow(ROW_NUM);\r
+ Cell cell = row.getCell(CELL_NUM);\r
cell.setCellValue(NEW_VALUE);\r
- workbook.write(pPart.getOutputStream());\r
+ os = pPart.getOutputStream();\r
+ workbook.write(os);\r
+ } finally {\r
+ IOUtils.closeQuietly(os);\r
+ IOUtils.closeQuietly(workbook);\r
+ IOUtils.closeQuietly(is);\r
}\r
}\r
+ }\r
\r
+ if (!embeddedDocs.isEmpty()) {\r
// Finally, write the newly modified Word document out to file.\r
- this.doc.write(new FileOutputStream(this.docFile));\r
+ FileOutputStream fos = new FileOutputStream(this.docFile);\r
+ this.doc.write(fos);\r
+ fos.close();\r
}\r
}\r
\r
* file system.\r
*/\r
public void checkUpdatedDoc() throws OpenXML4JException, IOException {\r
- Workbook workbook = null;\r
- Sheet sheet = null;\r
- Row row = null;\r
- Cell cell = null;\r
- PackagePart pPart = null;\r
- Iterator<PackagePart> pIter = null;\r
- List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();\r
- if (embeddedDocs != null && !embeddedDocs.isEmpty()) {\r
- pIter = embeddedDocs.iterator();\r
- while (pIter.hasNext()) {\r
- pPart = pIter.next();\r
- if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||\r
- pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {\r
- workbook = WorkbookFactory.create(pPart.getInputStream());\r
- sheet = workbook.getSheetAt(SHEET_NUM);\r
- row = sheet.getRow(ROW_NUM);\r
- cell = row.getCell(CELL_NUM);\r
+ for (PackagePart pPart : this.doc.getAllEmbedds()) {\r
+ String ext = pPart.getPartName().getExtension();\r
+ if (BINARY_EXTENSION.equals(ext) || OPENXML_EXTENSION.equals(ext)) {\r
+ InputStream is = pPart.getInputStream();\r
+ Workbook workbook = null;\r
+ try {\r
+ workbook = WorkbookFactory.create(is);\r
+ Sheet sheet = workbook.getSheetAt(SHEET_NUM);\r
+ Row row = sheet.getRow(ROW_NUM);\r
+ Cell cell = row.getCell(CELL_NUM);\r
assertEquals(cell.getNumericCellValue(), NEW_VALUE, 0.0001);\r
+ } finally {\r
+ IOUtils.closeQuietly(workbook);\r
+ IOUtils.closeQuietly(is);\r
}\r
}\r
}\r
* Code to test updating of the embedded Excel workbook.\r
*\r
* @param args\r
+ * @throws OpenXML4JException \r
*/\r
- public static void main(String[] args) {\r
- try {\r
- UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]);\r
- ued.updateEmbeddedDoc();\r
- ued.checkUpdatedDoc();\r
- } catch (Exception ex) {\r
- System.out.println(ex.getClass().getName());\r
- System.out.println(ex.getMessage());\r
- ex.printStackTrace(System.out);\r
- }\r
+ public static void main(String[] args) throws IOException, OpenXML4JException {\r
+ UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]);\r
+ ued.updateEmbeddedDoc();\r
+ ued.checkUpdatedDoc();\r
}\r
}\r
final int size = LittleEndianConsts.INT_SIZE;
checkPosition(size);
int le = LittleEndian.getInt(buf, pos);
- if (super.skip(size) < size) {
- throw new RuntimeException("Buffer overrun");
- }
+ long skipped = super.skip(size);
+ assert skipped == size : "Buffer overrun";
return le;
}
final int size = LittleEndianConsts.LONG_SIZE;
checkPosition(size);
long le = LittleEndian.getLong(buf, pos);
- if (super.skip(size) < size) {
- throw new RuntimeException("Buffer overrun");
- }
+ long skipped = super.skip(size);
+ assert skipped == size : "Buffer overrun";
return le;
}
final int size = LittleEndianConsts.SHORT_SIZE;
checkPosition(size);
int le = LittleEndian.getUShort(buf, pos);
- if (super.skip(size) < size) {
- throw new RuntimeException("Buffer overrun");
- }
+ long skipped = super.skip(size);
+ assert skipped == size : "Buffer overrun";
return le;
}
}
} catch(OfficeXmlFileException e) {
// opening as .xls failed => try opening as .xlsx
- OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE);
+ OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE); // NOSONAR
try {
return new XSSFWorkbook(pkg);
} catch (Exception ioe) {
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Internal;
import org.apache.poi.util.NotImplemented;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
+import org.apache.poi.util.Removal;
import org.apache.poi.util.TempFile;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFSheet;
public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles, boolean useSharedStringsTable){
setRandomAccessWindowSize(rowAccessWindowSize);
setCompressTempFiles(compressTmpFiles);
- if (workbook == null)
- {
+ if (workbook == null) {
_wb=new XSSFWorkbook();
_sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null;
- }
- else
- {
+ } else {
_wb=workbook;
_sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null;
- final int numberOfSheets = _wb.getNumberOfSheets();
- for ( int i = 0; i < numberOfSheets; i++ )
- {
- XSSFSheet sheet = _wb.getSheetAt( i );
- createAndRegisterSXSSFSheet( sheet );
+ for ( Sheet sheet : _wb ) {
+ createAndRegisterSXSSFSheet( (XSSFSheet)sheet );
}
}
}
{
for(XSSFSheet sheet : _sxFromXHash.values())
{
- if(sheetRef.equals(sheet.getPackagePart().getPartName().getName().substring(1))) return sheet;
+ if(sheetRef.equals(sheet.getPackagePart().getPartName().getName().substring(1))) {
+ return sheet;
+ }
}
return null;
}
- protected void injectData(ZipEntrySource zipEntrySource, OutputStream out) throws IOException
- {
- try
- {
+ protected void injectData(ZipEntrySource zipEntrySource, OutputStream out) throws IOException {
+ try {
ZipOutputStream zos = new ZipOutputStream(out);
- try
- {
+ try {
Enumeration<? extends ZipEntry> en = zipEntrySource.getEntries();
- while (en.hasMoreElements())
- {
+ while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
zos.putNextEntry(new ZipEntry(ze.getName()));
InputStream is = zipEntrySource.getInputStream(ze);
XSSFSheet xSheet=getSheetFromZipEntryName(ze.getName());
- if(xSheet!=null)
- {
+ if(xSheet!=null) {
SXSSFSheet sxSheet=getSXSSFSheet(xSheet);
InputStream xis = sxSheet.getWorksheetXMLInputStream();
- try
- {
+ try {
copyStreamAndInjectWorksheet(is,zos,xis);
- }
- finally
- {
+ } finally {
xis.close();
}
- }
- else
- {
- copyStream(is, zos);
+ } else {
+ IOUtils.copy(is, zos);
}
is.close();
}
- }
- finally
- {
+ } finally {
zos.close();
}
- }
- finally
- {
+ } finally {
zipEntrySource.close();
}
}
- private static void copyStream(InputStream in, OutputStream out) throws IOException {
- byte[] chunk = new byte[1024];
- int count;
- while ((count = in.read(chunk)) >=0 ) {
- out.write(chunk,0,count);
- }
- }
+
private static void copyStreamAndInjectWorksheet(InputStream in, OutputStream out, InputStream worksheetData) throws IOException {
InputStreamReader inReader=new InputStreamReader(in,"UTF-8"); //TODO: Is it always UTF-8 or do we need to read the xml encoding declaration in the file? If not, we should perhaps use a SAX reader instead.
OutputStreamWriter outWriter=new OutputStreamWriter(out,"UTF-8");
int pos=0;
String s="<sheetData";
int n=s.length();
-//Copy from "in" to "out" up to the string "<sheetData/>" or "</sheetData>" (excluding).
+ //Copy from "in" to "out" up to the string "<sheetData/>" or "</sheetData>" (excluding).
while(((c=inReader.read())!=-1))
{
if(c==s.charAt(pos))
}
else
{
- if(pos>0) outWriter.write(s,0,pos);
+ if(pos>0) {
+ outWriter.write(s,0,pos);
+ }
if(c==s.charAt(0))
{
pos=1;
outWriter.write("<sheetData>\n");
outWriter.flush();
}
-//Copy the worksheet data to "out".
- copyStream(worksheetData,out);
+ //Copy the worksheet data to "out".
+ IOUtils.copy(worksheetData,out);
outWriter.write("</sheetData>");
outWriter.flush();
-//Copy the rest of "in" to "out".
- while(((c=inReader.read())!=-1))
+ //Copy the rest of "in" to "out".
+ while(((c=inReader.read())!=-1)) {
outWriter.write(c);
+ }
outWriter.flush();
}
* @return the font with the matched attributes or <code>null</code>
* @deprecated POI 3.15 beta 2. Use {@link #findFont(boolean, short, short, String, boolean, boolean, short, byte)} instead.
*/
+ @Deprecated
@Override
+ @Removal(version="3.17")
public Font findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline)
{
return _wb.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline);
}
/**
- * Write out this workbook to an Outputstream.
+ * Write out this workbook to an OutputStream.
*
* @param stream - the java OutputStream you wish to write to
* @exception IOException if anything can't be written.
//Save the template
File tmplFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx");
- try
- {
+ boolean deleted;
+ try {
FileOutputStream os = new FileOutputStream(tmplFile);
- try
- {
+ try {
_wb.write(os);
- }
- finally
- {
+ } finally {
os.close();
}
//Substitute the template entries with the generated sheet data files
final ZipEntrySource source = new ZipFileZipEntrySource(new ZipFile(tmplFile));
injectData(source, stream);
+ } finally {
+ deleted = tmplFile.delete();
}
- finally
- {
- if(!tmplFile.delete()) {
- throw new IOException("Could not delete temporary file after processing: " + tmplFile);
- }
+ if(!deleted) {
+ throw new IOException("Could not delete temporary file after processing: " + tmplFile);
}
}
*/
@Override
@Deprecated
+ @Removal(version="3.18")
public Name getNameAt(int nameIndex)
{
return _wb.getNameAt(nameIndex);
*/
@Override
@Deprecated
+ @Removal(version="3.18")
public int getNameIndex(String name)
{
return _wb.getNameIndex(name);
*/
@Override
@Deprecated
+ @Removal(version="3.18")
public void removeName(int index)
{
_wb.removeName(index);
*/
@Override
@Deprecated
+ @Removal(version="3.18")
public void removeName(String name)
{
_wb.removeName(name);
import org.apache.poi.util.Beta;
import org.apache.poi.util.Internal;
import org.apache.poi.util.LocaleUtil;
+import org.apache.poi.util.Removal;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
// Copy CellStyle
if (policy.isCopyCellStyle()) {
- if (srcCell != null) {
- setCellStyle(srcCell.getCellStyle());
- }
- else {
- // clear cell style
- setCellStyle(null);
- }
+ setCellStyle(srcCell == null ? null : srcCell.getCellStyle());
}
+ final Hyperlink srcHyperlink = (srcCell == null) ? null : srcCell.getHyperlink();
+
if (policy.isMergeHyperlink()) {
// if srcCell doesn't have a hyperlink and destCell has a hyperlink, don't clear destCell's hyperlink
- final Hyperlink srcHyperlink = srcCell.getHyperlink();
if (srcHyperlink != null) {
setHyperlink(new XSSFHyperlink(srcHyperlink));
}
- }
- else if (policy.isCopyHyperlink()) {
+ } else if (policy.isCopyHyperlink()) {
// overwrite the hyperlink at dest cell with srcCell's hyperlink
// if srcCell doesn't have a hyperlink, clear the hyperlink (if one exists) at destCell
- final Hyperlink srcHyperlink = srcCell.getHyperlink();
- if (srcHyperlink == null) {
- setHyperlink(null);
- }
- else {
- setHyperlink(new XSSFHyperlink(srcHyperlink));
- }
+ setHyperlink(srcHyperlink == null ? null : new XSSFHyperlink(srcHyperlink));
}
}
case NUMERIC:
if(_cell.isSetV()) {
String v = _cell.getV();
- if (v.isEmpty()) return 0.0;
+ if (v.isEmpty()) {
+ return 0.0;
+ }
try {
return Double.parseDouble(v);
} catch(NumberFormatException e) {
*/
protected String getCellFormula(XSSFEvaluationWorkbook fpb) {
CellType cellType = getCellTypeEnum();
- if(cellType != CellType.FORMULA) throw typeMismatch(CellType.FORMULA, cellType, false);
+ if(cellType != CellType.FORMULA) {
+ throw typeMismatch(CellType.FORMULA, cellType, false);
+ }
CTCellFormula f = _cell.getF();
if (isPartOfArrayFormulaGroup() && f == null) {
XSSFSheet sheet = getSheet();
CTCellFormula f = sheet.getSharedFormula(si);
- if(f == null) throw new IllegalStateException(
- "Master cell of a shared formula with sid="+si+" was not found");
+ if(f == null) {
+ throw new IllegalStateException(
+ "Master cell of a shared formula with sid="+si+" was not found");
+ }
String sharedFormula = f.getStringValue();
//Range of cells which the shared formula applies to
XSSFWorkbook wb = _row.getSheet().getWorkbook();
if (formula == null) {
wb.onDeleteFormula(this);
- if(_cell.isSetF()) _cell.unsetF();
+ if(_cell.isSetF()) {
+ _cell.unsetF();
+ }
return;
}
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue(formula);
_cell.setF(f);
- if(_cell.isSetV()) _cell.unsetV();
+ if(_cell.isSetV()) {
+ _cell.unsetV();
+ }
}
/**
@Override
public void setCellStyle(CellStyle style) {
if(style == null) {
- if(_cell.isSetS()) _cell.unsetS();
+ if(_cell.isSetS()) {
+ _cell.unsetS();
+ }
} else {
XSSFCellStyle xStyle = (XSSFCellStyle)style;
xStyle.verifyBelongsToStylesSource(_stylesSource);
* @return the cell type
* @deprecated 3.15. Will return a {@link CellType} enum in the future.
*/
+ @Deprecated
@Override
+ @Removal(version="3.17")
public int getCellType() {
return getCellTypeEnum().getCode();
}
*/
@Override
public CellType getCellTypeEnum() {
- if (isFormulaCell()) return CellType.FORMULA;
+ if (isFormulaCell()) {
+ return CellType.FORMULA;
+ }
return getBaseCellType(true);
}
* on the cached value of the formula
* @deprecated 3.15. Will return a {@link CellType} enum in the future.
*/
+ @Deprecated
@Override
+ @Removal(version="3.17")
public int getCachedFormulaResultType() {
return getCachedFormulaResultTypeEnum().getCode();
}
*/
public String getErrorCellString() throws IllegalStateException {
CellType cellType = getBaseCellType(true);
- if(cellType != CellType.ERROR) throw typeMismatch(CellType.ERROR, cellType, false);
+ if(cellType != CellType.ERROR) {
+ throw typeMismatch(CellType.ERROR, cellType, false);
+ }
return _cell.getV();
}
private void setBlank(){
CTCell blank = CTCell.Factory.newInstance();
blank.setR(_cell.getR());
- if(_cell.isSetS()) blank.setS(_cell.getS());
+ if(_cell.isSetS()) {
+ blank.setS(_cell.getS());
+ }
_cell.set(blank);
}
* @see CellType#ERROR
* @deprecated POI 3.15 beta 3. Use {@link #setCellType(CellType)} instead.
*/
+ @Deprecated
@Override
+ @Removal(version="3.17")
public void setCellType(int cellType) {
setCellType(CellType.forInt(cellType));
}
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue("0");
_cell.setF(f);
- if(_cell.isSetT()) _cell.unsetT();
+ if(_cell.isSetT()) {
+ _cell.unsetT();
+ }
}
break;
case BLANK:
options.setLoadReplaceDocumentElement(null);
ctPivotCacheDefinition = CTPivotCacheDefinition.Factory.parse(is, options);
} catch (XmlException e) {
- throw new IOException(e.getLocalizedMessage());
+ throw new IOException(e.getLocalizedMessage(), e);
}
}
final String ref = wsSource.getRef();
final String name = wsSource.getName();
- if (ref == null && name == null) throw new IllegalArgumentException("Pivot cache must reference an area, named range, or table.");
+ if (ref == null && name == null) {
+ throw new IllegalArgumentException("Pivot cache must reference an area, named range, or table.");
+ }
// this is the XML format, so tell the reference that.
- if (ref != null) return new AreaReference(ref, SpreadsheetVersion.EXCEL2007);
+ if (ref != null) {
+ return new AreaReference(ref, SpreadsheetVersion.EXCEL2007);
+ }
+
+ assert (name != null);
+
+ // named range or table?
+ final Name range = wb.getName(name);
+ if (range != null) {
+ return new AreaReference(range.getRefersToFormula(), SpreadsheetVersion.EXCEL2007);
+ }
- if (name != null) {
- // named range or table?
- final Name range = wb.getName(name);
- if (range != null) return new AreaReference(range.getRefersToFormula(), SpreadsheetVersion.EXCEL2007);
- // not a named range, check for a table.
- // do this second, as tables are sheet-specific, but named ranges are not, and may not have a sheet name given.
- final XSSFSheet sheet = (XSSFSheet) wb.getSheet(wsSource.getSheet());
- for (XSSFTable table : sheet.getTables()) {
- if (table.getName().equals(name)) { //case-sensitive?
- return new AreaReference(table.getStartCellReference(), table.getEndCellReference());
- }
+ // not a named range, check for a table.
+ // do this second, as tables are sheet-specific, but named ranges are not, and may not have a sheet name given.
+ final XSSFSheet sheet = (XSSFSheet) wb.getSheet(wsSource.getSheet());
+ for (XSSFTable table : sheet.getTables()) {
+ // TODO: case-sensitive?
+ if (name.equals(table.getName())) {
+ return new AreaReference(table.getStartCellReference(), table.getEndCellReference());
}
}
private void initHyperlinks() {
hyperlinks = new ArrayList<XSSFHyperlink>();
- if(!worksheet.isSetHyperlinks()) return;
+ if(!worksheet.isSetHyperlinks()) {
+ return;
+ }
try {
PackageRelationshipCollection hyperRels =
// for each cell in sheet, if cell belongs to an array formula, check if merged region intersects array formula cells
for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
XSSFRow row = getRow(rowIn);
- if (row == null) continue;
+ if (row == null) {
+ continue;
+ }
for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
XSSFCell cell = row.getCell(colIn);
- if (cell == null) continue;
+ if (cell == null) {
+ continue;
+ }
if (cell.isPartOfArrayFormulaGroup()) {
CellRangeAddress arrayRange = cell.getArrayFormulaRange();
// If both colSplit and rowSplit are zero then the existing freeze pane is removed
if(colSplit == 0 && rowSplit == 0){
- if(ctView.isSetPane()) ctView.unsetPane();
+ if(ctView.isSetPane()) {
+ ctView.unsetPane();
+ }
ctView.setSelectionArray(null);
return;
}
if (colSplit > 0) {
pane.setXSplit(colSplit);
} else {
- if(pane.isSetXSplit()) pane.unsetXSplit();
+ if(pane.isSetXSplit()) {
+ pane.unsetXSplit();
+ }
}
if (rowSplit > 0) {
pane.setYSplit(rowSplit);
} else {
- if(pane.isSetYSplit()) pane.unsetYSplit();
+ if(pane.isSetYSplit()) {
+ pane.unsetYSplit();
+ }
}
pane.setState(STPaneState.FROZEN);
* @return the cell comment, if one exists. Otherwise return null.
* @deprecated as of 2015-11-23 (circa POI 3.14beta1). Use {@link #getCellComment(CellAddress)} instead.
*/
+ @Deprecated
@Override
+ @Removal(version="3.16")
public XSSFComment getCellComment(int row, int column) {
return getCellComment(new CellAddress(row, column));
}
CellAddress ref = new CellAddress(row, column);
CTComment ctComment = sheetComments.getCTComment(ref);
- if(ctComment == null) return null;
+ if(ctComment == null) {
+ return null;
+ }
XSSFVMLDrawing vml = getVMLDrawing(false);
return new XSSFComment(sheetComments, ctComment,
*/
@Override
public double getMargin(short margin) {
- if (!worksheet.isSetPageMargins()) return 0;
+ if (!worksheet.isSetPageMargins()) {
+ return 0;
+ }
CTPageMargins pageMargins = worksheet.getPageMargins();
switch (margin) {
@Override
public CellRangeAddress getMergedRegion(int index) {
CTMergeCells ctMergeCells = worksheet.getMergeCells();
- if(ctMergeCells == null) throw new IllegalStateException("This worksheet does not contain merged regions");
+ if(ctMergeCells == null) {
+ throw new IllegalStateException("This worksheet does not contain merged regions");
+ }
CTMergeCell ctMergeCell = ctMergeCells.getMergeCellArray(index);
String ref = ctMergeCell.getRef();
public List<CellRangeAddress> getMergedRegions() {
List<CellRangeAddress> addresses = new ArrayList<CellRangeAddress>();
CTMergeCells ctMergeCells = worksheet.getMergeCells();
- if(ctMergeCells == null) return addresses;
+ if(ctMergeCells == null) {
+ return addresses;
+ }
for(CTMergeCell ctMergeCell : ctMergeCells.getMergeCellArray()) {
String ref = ctMergeCell.getRef();
public PaneInformation getPaneInformation() {
CTPane pane = getDefaultSheetView().getPane();
// no pane configured
- if(pane == null) return null;
+ if(pane == null) {
+ return null;
+ }
CellReference cellRef = pane.isSetTopLeftCell() ? new CellReference(pane.getTopLeftCell()) : null;
return new PaneInformation((short)pane.getXSplit(), (short)pane.getYSplit(),
*/
@Override
public void removeMergedRegion(int index) {
- if (!worksheet.isSetMergeCells()) return;
+ if (!worksheet.isSetMergeCells()) {
+ return;
+ }
CTMergeCells ctMergeCells = worksheet.getMergeCells();
int size = ctMergeCells.sizeOfMergeCellArray();
*/
@Override
public void removeMergedRegions(Collection<Integer> indices) {
- if (!worksheet.isSetMergeCells()) return;
+ if (!worksheet.isSetMergeCells()) {
+ return;
+ }
CTMergeCells ctMergeCells = worksheet.getMergeCells();
List<CTMergeCell> newMergeCells = new ArrayList<CTMergeCell>(ctMergeCells.sizeOfMergeCellArray());
*/
@Override
public void setColumnWidth(int columnIndex, int width) {
- if(width > 255*256) throw new IllegalArgumentException("The maximum column width for an individual cell is 255 characters.");
+ if(width > 255*256) {
+ throw new IllegalArgumentException("The maximum column width for an individual cell is 255 characters.");
+ }
columnHelper.setColWidth(columnIndex, (double)width/256);
columnHelper.setCustomWidth(columnIndex, true);
short level = getRow(rowIndex).getCTRow().getOutlineLevel();
int currentRow = rowIndex;
while (getRow(currentRow) != null) {
- if (getRow(currentRow).getCTRow().getOutlineLevel() < level)
+ if (getRow(currentRow).getCTRow().getOutlineLevel() < level) {
return currentRow + 1;
+ }
currentRow--;
}
return currentRow;
* @param rowNumber the zero based row index to expand
*/
private void expandRow(int rowNumber) {
- if (rowNumber == -1)
+ if (rowNumber == -1) {
return;
+ }
XSSFRow row = getRow(rowNumber);
// If it is already expanded do nothing.
if (!row.getCTRow().isSetHidden()) {
* @param denominator The denominator for the zoom magnification.
* @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #setZoom(int)} instead.
*/
+ @Deprecated
@Removal(version="3.16")
@Override
public void setZoom(int numerator, int denominator) {
// we need to sort it in a way so the shifting does not mess up the structures,
// i.e. when shifting down, start from down and go up, when shifting up, vice-versa
SortedMap<XSSFComment, Integer> commentsToShift = new TreeMap<XSSFComment, Integer>(new Comparator<XSSFComment>() {
+ @Override
public int compare(XSSFComment o1, XSSFComment o2) {
int row1 = o1.getRow();
int row2 = o2.getRow();
}
}
- if(rownum < startRow || rownum > endRow) continue;
+ if(rownum < startRow || rownum > endRow) {
+ continue;
+ }
if (!copyRowHeight) {
row.setHeight((short)-1);
* @param cellRef the location of the active cell, e.g. <code>A1</code>..
* @deprecated 3.14beta2 (circa 2015-12-05). Use {@link #setActiveCell(CellAddress)} instead.
*/
+ @Deprecated
+ @Removal(version="3.16")
public void setActiveCell(String cellRef) {
CTSelection ctsel = getSheetTypeSelection();
ctsel.setActiveCell(cellRef);
*/
private CTSheetView getDefaultSheetView() {
CTSheetViews views = getSheetTypeSheetViews();
- int sz = views == null ? 0 : views.sizeOfSheetViewArray();
- if (sz == 0) {
+ if (views == null) {
return null;
}
- return views.getSheetViewArray(sz - 1);
+ int sz = views.sizeOfSheetViewArray();
+ return (sz == 0) ? null : views.getSheetViewArray(sz - 1);
}
/**
return dataValidationHelper;
}
+ @Override
public List<XSSFDataValidation> getDataValidations() {
List<XSSFDataValidation> xssfValidations = new ArrayList<XSSFDataValidation>();
CTDataValidations dataValidations = this.worksheet.getDataValidations();
@Override
public XSSFAutoFilter setAutoFilter(CellRangeAddress range) {
CTAutoFilter af = worksheet.getAutoFilter();
- if(af == null) af = worksheet.addNewAutoFilter();
+ if(af == null) {
+ af = worksheet.addNewAutoFilter();
+ }
CellRangeAddress norm = new CellRangeAddress(range.getFirstRow(), range.getLastRow(),
range.getFirstColumn(), range.getLastColumn());
*/
public XSSFColor getTabColor() {
CTSheetPr pr = worksheet.getSheetPr();
- if(pr == null) pr = worksheet.addNewSheetPr();
+ if(pr == null) {
+ pr = worksheet.addNewSheetPr();
+ }
if (!pr.isSetTabColor()) {
return null;
}
* @param colorIndex the indexed color to set, must be a constant from {@link org.apache.poi.ss.usermodel.IndexedColors}
* @deprecated 3.15-beta2. Removed in 3.17. Use {@link #setTabColor(XSSFColor)}.
*/
+ @Deprecated
+ @Removal(version="3.17")
public void setTabColor(int colorIndex) {
IndexedColors indexedColor = IndexedColors.fromInt(colorIndex);
XSSFColor color = new XSSFColor(indexedColor);
*/
public void setTabColor(XSSFColor color) {
CTSheetPr pr = worksheet.getSheetPr();
- if(pr == null) pr = worksheet.addNewSheetPr();
+ if(pr == null) {
+ pr = worksheet.addNewSheetPr();
+ }
pr.setTabColor(color.getCTColor());
}
}
return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() {
+ @Override
public void configureReference(CTWorksheetSource wsSource) {
final String[] firstCell = source.getFirstCell().getCellRefParts();
final String firstRow = firstCell[1];
}
return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() {
+ @Override
public void configureReference(CTWorksheetSource wsSource) {
wsSource.setName(source.getNameName());
}
@Beta
public XSSFPivotTable createPivotTable(final Table source, CellReference position) {
return createPivotTable(position, getWorkbook().getSheet(source.getSheetName()), new PivotTableReferenceConfigurator() {
- public void configureReference(CTWorksheetSource wsSource) {
+ @Override
+ public void configureReference(CTWorksheetSource wsSource) {
wsSource.setName(source.getName());
}
});
return tables;
}
+ @Override
public int getColumnOutlineLevel(int columnIndex) {
CTCol col = columnHelper.getColumn(columnIndex, false);
if (col == null) {
Map<String, ExternalLinksTable> elIdMap = new HashMap<String, ExternalLinksTable>();
for(RelationPart rp : getRelationParts()){
POIXMLDocumentPart p = rp.getDocumentPart();
- if(p instanceof SharedStringsTable) sharedStringSource = (SharedStringsTable)p;
- else if(p instanceof StylesTable) stylesSource = (StylesTable)p;
- else if(p instanceof ThemesTable) theme = (ThemesTable)p;
- else if(p instanceof CalculationChain) calcChain = (CalculationChain)p;
- else if(p instanceof MapInfo) mapInfo = (MapInfo)p;
- else if (p instanceof XSSFSheet) {
+ if(p instanceof SharedStringsTable) {
+ sharedStringSource = (SharedStringsTable)p;
+ } else if(p instanceof StylesTable) {
+ stylesSource = (StylesTable)p;
+ } else if(p instanceof ThemesTable) {
+ theme = (ThemesTable)p;
+ } else if(p instanceof CalculationChain) {
+ calcChain = (CalculationChain)p;
+ } else if(p instanceof MapInfo) {
+ mapInfo = (MapInfo)p;
+ } else if (p instanceof XSSFSheet) {
shIdMap.put(rp.getRelationship().getId(), (XSSFSheet)p);
- }
- else if (p instanceof ExternalLinksTable) {
+ } else if (p instanceof ExternalLinksTable) {
elIdMap.put(rp.getRelationship().getId(), (ExternalLinksTable)p);
}
}
*/
@Override
public XSSFDataFormat createDataFormat() {
- if (formatter == null)
+ if (formatter == null) {
formatter = new XSSFDataFormat(stylesSource);
+ }
return formatter;
}
validateSheetName(sheetname);
// YK: Mimic Excel and silently truncate sheet names longer than 31 characters
- if(sheetname.length() > 31) sheetname = sheetname.substring(0, 31);
+ if(sheetname.length() > 31) {
+ sheetname = sheetname.substring(0, 31);
+ }
WorkbookUtil.validateSheetName(sheetname);
CTSheet sheet = addSheet(sheetname);
wrapper.sheet = sheet;
sheet.setId(rp.getRelationship().getId());
sheet.setSheetId(sheetNumber);
- if (sheets.isEmpty()) wrapper.setSelected(true);
+ if (sheets.isEmpty()) {
+ wrapper.setSelected(true);
+ }
sheets.add(wrapper);
return wrapper;
}
@Override
public String getPrintArea(int sheetIndex) {
XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
- if (name == null) return null;
+ if (name == null) {
+ return null;
+ }
//adding one here because 0 indicates a global named region; doesnt make sense for print areas
return name.getRefersToFormula();
public int getSheetIndex(Sheet sheet) {
int idx = 0;
for(XSSFSheet sh : sheets){
- if(sh == sheet) return idx;
+ if(sh == sheet) {
+ return idx;
+ }
idx++;
}
return -1;
List<XSSFName> toRemove = new ArrayList<XSSFName>();
for (XSSFName nm : namedRanges) {
CTDefinedName ct = nm.getCTName();
- if(!ct.isSetLocalSheetId()) continue;
+ if(!ct.isSetLocalSheetId()) {
+ continue;
+ }
if (ct.getLocalSheetId() == index) {
toRemove.add(nm);
} else if (ct.getLocalSheetId() > index){
*/
@Override
public void setSheetName(int sheetIndex, String sheetname) {
+ if (sheetname == null) {
+ throw new IllegalArgumentException( "sheetName must not be null" );
+ }
+
validateSheetIndex(sheetIndex);
String oldSheetName = getSheetName(sheetIndex);
// YK: Mimic Excel and silently truncate sheet names longer than 31 characters
- if(sheetname != null && sheetname.length() > 31) sheetname = sheetname.substring(0, 31);
+ if(sheetname.length() > 31) {
+ sheetname = sheetname.substring(0, 31);
+ }
WorkbookUtil.validateSheetName(sheetname);
- // findbugs fix - validateSheetName has already checked for null value
- assert(sheetname != null);
// Do nothing if no change
- if (sheetname.equals(oldSheetName)) return;
+ if (sheetname.equals(oldSheetName)) {
+ return;
+ }
// Check it isn't already taken
- if (containsSheet(sheetname, sheetIndex ))
+ if (containsSheet(sheetname, sheetIndex )) {
throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
+ }
// Update references to the name
XSSFFormulaUtils utils = new XSSFFormulaUtils(this);
* Returns the Theme of current workbook.
*/
public ThemesTable getTheme() {
- if (stylesSource == null) return null;
+ if (stylesSource == null) {
+ return null;
+ }
return stylesSource.getTheme();
}
*/
@Override
public XSSFCreationHelper getCreationHelper() {
- if(_creationHelper == null) _creationHelper = new XSSFCreationHelper(this);
+ if(_creationHelper == null) {
+ _creationHelper = new XSSFCreationHelper(this);
+ }
return _creationHelper;
}
ctName = ctName.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN);
}
- if (excludeSheetIdx != i && name.equalsIgnoreCase(ctName))
+ if (excludeSheetIdx != i && name.equalsIgnoreCase(ctName)) {
return true;
+ }
}
return false;
}
* otherwise the given algorithm is used for calculating the hash password (Excel 2013)
*/
public void setWorkbookPassword(String password, HashAlgorithm hashAlgo) {
- if (password == null && !workbookProtectionPresent()) return;
+ if (password == null && !workbookProtectionPresent()) {
+ return;
+ }
setPassword(safeGetWorkbookProtection(), password, hashAlgo, "workbook");
}
* @return true, if the hashes match (... though original password may differ ...)
*/
public boolean validateWorkbookPassword(String password) {
- if (!workbookProtectionPresent()) return (password == null);
+ if (!workbookProtectionPresent()) {
+ return (password == null);
+ }
return validatePassword(safeGetWorkbookProtection(), password, "workbook");
}
* otherwise the given algorithm is used for calculating the hash password (Excel 2013)
*/
public void setRevisionsPassword(String password, HashAlgorithm hashAlgo) {
- if (password == null && !workbookProtectionPresent()) return;
+ if (password == null && !workbookProtectionPresent()) {
+ return;
+ }
setPassword(safeGetWorkbookProtection(), password, hashAlgo, "revisions");
}
* @return true if the hashes match (... though original password may differ ...)
*/
public boolean validateRevisionsPassword(String password) {
- if (!workbookProtectionPresent()) return (password == null);
+ if (!workbookProtectionPresent()) {
+ return (password == null);
+ }
return validatePassword(safeGetWorkbookProtection(), password, "revisions");
}
public static final int OVERLAPS_2_WRAPS = 3;
public static long[] getOverlappingRange(long[] range1, long[] range2) {
- int overlappingType = getOverlappingType(range1, range2);
- if (overlappingType == OVERLAPS_1_MINOR) {
- return new long[]{range2[0], range1[1]};
+ switch(getOverlappingType(range1, range2)) {
+ case OVERLAPS_1_MINOR:
+ return new long[]{range2[0], range1[1]};
+ case OVERLAPS_2_MINOR:
+ return new long[]{range1[0], range2[1]};
+ case OVERLAPS_2_WRAPS:
+ return range1;
+ case OVERLAPS_1_WRAPS:
+ return range2;
+ default:
+ case NO_OVERLAPS:
+ return new long[]{-1, -1};
}
- else if (overlappingType == OVERLAPS_2_MINOR) {
- return new long[]{range1[0], range2[1]};
- }
- else if (overlappingType == OVERLAPS_2_WRAPS) {
- return range1;
- }
- else if (overlappingType == OVERLAPS_1_WRAPS) {
- return range2;
- }
- return new long[]{-1, -1};
}
public static int getOverlappingType(long[] range1, long[] range2) {
long max1 = range1[1];
long min2 = range2[0];
long max2 = range2[1];
- if (min1 >= min2 && max1 <= max2) {
- return OVERLAPS_2_WRAPS;
- }
- else if (min2 >= min1 && max2 <= max1) {
- return OVERLAPS_1_WRAPS;
- }
- else if ((min2 >= min1 && min2 <= max1) && max2 >= max1) {
- return OVERLAPS_1_MINOR;
- }
- else if ((min1 >= min2 && min1 <= max2) && max1 >= max2) {
- return OVERLAPS_2_MINOR;
+ if (min1 >= min2) {
+ if (max1 <= max2) {
+ return OVERLAPS_2_WRAPS;
+ } else if (min1 <= max2) {
+ return OVERLAPS_2_MINOR;
+ }
+ } else {
+ if (max1 >= max2) {
+ return OVERLAPS_1_WRAPS;
+ } else if (max1 >= min2) {
+ return OVERLAPS_1_MINOR;
+ }
}
return NO_OVERLAPS;
import org.apache.poi.wp.usermodel.Paragraph;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPBdr;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTProofErr;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRunTrackChange;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSmartTagRun;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTextAlignment;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTextAlignment;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
/**
* <p>A Paragraph within a Document, Table, Header etc.</p>
for (XWPFParagraph p : footnote.getParagraphs()) {
if (!first) {
footnoteText.append("\n");
- first = false;
}
+ first = false;
footnoteText.append(p.getText());
}
return !paragraph.getDomNode().hasChildNodes();
}
+ @Override
public XWPFDocument getDocument() {
return document;
}
public String getStyleID() {
if (paragraph.getPPr() != null) {
if (paragraph.getPPr().getPStyle() != null) {
- if (paragraph.getPPr().getPStyle().getVal() != null)
+ if (paragraph.getPPr().getPStyle().getVal() != null) {
return paragraph.getPPr().getPStyle().getVal();
+ }
}
}
return null;
public BigInteger getNumID() {
if (paragraph.getPPr() != null) {
if (paragraph.getPPr().getNumPr() != null) {
- if (paragraph.getPPr().getNumPr().getNumId() != null)
+ if (paragraph.getPPr().getNumPr().getNumId() != null) {
return paragraph.getPPr().getNumPr().getNumId().getVal();
+ }
}
}
return null;
* @param numPos
*/
public void setNumID(BigInteger numPos) {
- if (paragraph.getPPr() == null)
+ if (paragraph.getPPr() == null) {
paragraph.addNewPPr();
- if (paragraph.getPPr().getNumPr() == null)
+ }
+ if (paragraph.getPPr().getNumPr() == null) {
paragraph.getPPr().addNewNumPr();
+ }
if (paragraph.getPPr().getNumPr().getNumId() == null) {
paragraph.getPPr().getNumPr().addNewNumId();
}
public BigInteger getNumIlvl() {
if (paragraph.getPPr() != null) {
if (paragraph.getPPr().getNumPr() != null) {
- if (paragraph.getPPr().getNumPr().getIlvl() != null)
+ if (paragraph.getPPr().getNumPr().getIlvl() != null) {
return paragraph.getPPr().getNumPr().getIlvl().getVal();
+ }
}
}
return null;
}
}
if (level != null && level.getNumFmt() != null
- && level.getNumFmt().getVal() != null)
+ && level.getNumFmt().getVal() != null) {
return level.getNumFmt().getVal().toString();
+ }
}
}
return null;
if (num != null) {
BigInteger ilvl = getNumIlvl();
CTNum ctNum = num.getCTNum();
- if (ctNum == null)
+ if (ctNum == null) {
return null;
+ }
CTDecimalNumber ctDecimalNumber = ctNum.getAbstractNumId();
- if (ctDecimalNumber == null)
+ if (ctDecimalNumber == null) {
return null;
+ }
BigInteger abstractNumId = ctDecimalNumber.getVal();
- if (abstractNumId == null)
+ if (abstractNumId == null) {
return null;
+ }
XWPFAbstractNum xwpfAbstractNum = numbering.getAbstractNum(abstractNumId);
- if (xwpfAbstractNum == null)
+ if (xwpfAbstractNum == null) {
return null;
+ }
CTAbstractNum anum = xwpfAbstractNum.getCTAbstractNum();
- if (anum == null)
+ if (anum == null) {
return null;
+ }
CTLvl level = null;
for (int i = 0; i < anum.sizeOfLvlArray(); i++) {
}
}
if (level != null && level.getLvlText() != null
- && level.getLvlText().getVal() != null)
+ && level.getLvlText().getVal() != null) {
return level.getLvlText().getVal().toString();
+ }
}
}
return null;
/**
* @return The raw alignment value, {@link #getAlignment()} is suggested
*/
+ @Override
public int getFontAlignment() {
return getAlignment().getValue();
}
+ @Override
public void setFontAlignment(int align) {
ParagraphAlignment pAlign = ParagraphAlignment.valueOf(align);
setAlignment(pAlign);
}
CTBorder pr = (ct.isSetTop()) ? ct.getTop() : ct.addNewTop();
- if (border.getValue() == Borders.NONE.getValue())
+ if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetTop();
- else
+ } else {
pr.setVal(STBorder.Enum.forInt(border.getValue()));
+ }
}
/**
public void setBorderBottom(Borders border) {
CTPBdr ct = getCTPBrd(true);
CTBorder pr = ct.isSetBottom() ? ct.getBottom() : ct.addNewBottom();
- if (border.getValue() == Borders.NONE.getValue())
+ if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetBottom();
- else
+ } else {
pr.setVal(STBorder.Enum.forInt(border.getValue()));
+ }
}
/**
public void setBorderLeft(Borders border) {
CTPBdr ct = getCTPBrd(true);
CTBorder pr = ct.isSetLeft() ? ct.getLeft() : ct.addNewLeft();
- if (border.getValue() == Borders.NONE.getValue())
+ if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetLeft();
- else
+ } else {
pr.setVal(STBorder.Enum.forInt(border.getValue()));
+ }
}
/**
public void setBorderRight(Borders border) {
CTPBdr ct = getCTPBrd(true);
CTBorder pr = ct.isSetRight() ? ct.getRight() : ct.addNewRight();
- if (border.getValue() == Borders.NONE.getValue())
+ if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetRight();
- else
+ } else {
pr.setVal(STBorder.Enum.forInt(border.getValue()));
+ }
}
/**
public void setBorderBetween(Borders border) {
CTPBdr ct = getCTPBrd(true);
CTBorder pr = ct.isSetBetween() ? ct.getBetween() : ct.addNewBetween();
- if (border.getValue() == Borders.NONE.getValue())
+ if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetBetween();
- else
+ } else {
pr.setVal(STBorder.Enum.forInt(border.getValue()));
+ }
}
/**
CTPPr ppr = getCTPPr();
CTOnOff ctPageBreak = ppr.isSetPageBreakBefore() ? ppr
.getPageBreakBefore() : ppr.addNewPageBreakBefore();
- if (pageBreak)
+ if (pageBreak) {
ctPageBreak.setVal(STOnOff.TRUE);
- else
+ } else {
ctPageBreak.setVal(STOnOff.FALSE);
+ }
}
/**
indent.setFirstLine(bi);
}
+ @Override
public int getIndentFromLeft() {
return getIndentationLeft();
}
+ @Override
public void setIndentFromLeft(int dxaLeft) {
setIndentationLeft(dxaLeft);
}
+ @Override
public int getIndentFromRight() {
return getIndentationRight();
}
+ @Override
public void setIndentFromRight(int dxaRight) {
setIndentationRight(dxaRight);
}
+ @Override
public int getFirstLineIndent() {
return getIndentationFirstLine();
}
+ @Override
public void setFirstLineIndent(int first) {
setIndentationFirstLine(first);
}
*
* @return boolean
*/
+ @Override
public boolean isWordWrapped() {
CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr()
.getWordWrap() : null;
*
* @param wrap - boolean
*/
+ @Override
public void setWordWrapped(boolean wrap) {
CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr()
.getWordWrap() : getCTPPr().addNewWordWrap();
- if (wrap)
+ if (wrap) {
wordWrap.setVal(STOnOff.TRUE);
- else
+ } else {
wordWrap.unsetVal();
+ }
}
public boolean isWordWrap() {
private CTPBdr getCTPBrd(boolean create) {
CTPPr pr = getCTPPr();
CTPBdr ct = pr.isSetPBdr() ? pr.getPBdr() : null;
- if (create && ct == null)
+ if (create && ct == null) {
ct = pr.addNewPBdr();
+ }
return ct;
}
private CTSpacing getCTSpacing(boolean create) {
CTPPr pr = getCTPPr();
CTSpacing ct = pr.getSpacing() == null ? null : pr.getSpacing();
- if (create && ct == null)
+ if (create && ct == null) {
ct = pr.addNewSpacing();
+ }
return ct;
}
private CTInd getCTInd(boolean create) {
CTPPr pr = getCTPPr();
CTInd ct = pr.getInd() == null ? null : pr.getInd();
- if (create && ct == null)
+ if (create && ct == null) {
ct = pr.addNewInd();
+ }
return ct;
}
for (int j = startText; j <= endText; j++) {
String tmpText = tArray[j].getStringValue();
int startChar = 0, endChar = tmpText.length() - 1;
- if ((j == textBegin) && (i == runBegin))
+ if ((j == textBegin) && (i == runBegin)) {
startChar = charBegin;
+ }
if ((j == textEnd) && (i == runEnd)) {
endChar = charEnd;
}
*
* @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType()
*/
+ @Override
public BodyElementType getElementType() {
return BodyElementType.PARAGRAPH;
}
+ @Override
public IBody getBody() {
return part;
}
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/
+ @Override
public POIXMLDocumentPart getPart() {
if (part != null) {
return part.getPart();
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
+ @Override
public BodyType getPartType() {
return part.getPartType();
}
} catch (IOException e) {
throw new POIXMLException(e);
} finally {
- try {
- if (is != null) is.close();
- } catch (IOException e) {
- throw new POIXMLException(e);
- }
+ IOUtils.closeQuietly(is);
}
this.checksum = IOUtils.calculateChecksum(data);
}
import java.io.IOException;\r
import java.io.InputStream;\r
import java.io.OutputStream;\r
-import java.net.*;\r
+import java.net.ConnectException;\r
+import java.net.HttpURLConnection;\r
+import java.net.MalformedURLException;\r
+import java.net.SocketTimeoutException;\r
+import java.net.URL;\r
import java.security.Key;\r
import java.security.KeyPair;\r
import java.security.KeyStore;\r
throw e;\r
}\r
if((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) {\r
- Assume.assumeTrue("Only allowing ConnectException with 'timed out' as message here, but had: " + e,\r
+ Assume.assumeFalse("Only allowing ConnectException with 'timed out' as message here, but had: " + e,\r
e.getCause().getMessage().contains("timed out"));\r
} else if (e.getCause() instanceof IOException) {\r
- Assume.assumeTrue("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e,\r
+ Assume.assumeFalse("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e,\r
e.getCause().getMessage().contains("Error contacting TSP server"));\r
} else if (e.getCause() instanceof RuntimeException) {\r
- Assume.assumeTrue("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e,\r
+ Assume.assumeFalse("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e,\r
e.getCause().getMessage().contains("This site is cur"));\r
- } else {\r
- throw e;\r
}\r
+ throw e;\r
}\r
\r
// verify\r
boolean b = si.verifySignature();\r
assertTrue("Signature not correctly calculated for " + ha, b);\r
} finally {\r
- if (pkg != null) pkg.close();\r
+ if (pkg != null) {\r
+ pkg.close();\r
+ }\r
}\r
}\r
}\r