SonarQube fixes

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1777855 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2017-01-08 00:38:41 +00:00
parent 24c0b83841
commit bf311b8e6e
30 changed files with 562 additions and 434 deletions

View File

@ -84,24 +84,22 @@ public class SavePasswordProtectedXlsx {
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);
}
}

View File

@ -18,9 +18,17 @@
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;
/**
@ -29,7 +37,7 @@ 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");
@ -76,5 +84,6 @@ public class CreateCell {
FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -16,9 +16,9 @@
==================================================================== */
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;
@ -37,8 +37,7 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;
*/
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();
@ -88,5 +87,6 @@ public class CreateTable {
FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -17,9 +17,15 @@
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;
@ -27,7 +33,7 @@ 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");
@ -37,7 +43,7 @@ public class FillsAndColors {
// 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);
@ -45,7 +51,7 @@ public class FillsAndColors {
// 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);
@ -54,6 +60,6 @@ public class FillsAndColors {
FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -17,6 +17,7 @@
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;
@ -25,8 +26,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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();
@ -41,6 +41,6 @@ public class FitSheetToOnePage {
FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -17,6 +17,7 @@
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;
@ -28,7 +29,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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);
@ -79,6 +80,6 @@ public class HeadersAndFooters {
FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -17,20 +17,21 @@
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);
@ -42,5 +43,6 @@ public class IterateCells {
}
}
}
wb.close();
}
}

View File

@ -17,6 +17,7 @@
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.Chart;
@ -42,7 +43,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class LineChart {
public static void main(String[] args) throws Exception {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("linechart");
final int NUM_OF_ROWS = 3;
@ -59,7 +60,7 @@ public class LineChart {
}
}
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);
@ -87,5 +88,6 @@ public class LineChart {
FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -17,21 +17,22 @@
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 org.apache.poi.ss.usermodel.Cell;
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 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.XSSFRichTextString;
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");
@ -45,5 +46,6 @@ public class MergingCells {
FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -17,6 +17,7 @@
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;
@ -30,7 +31,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
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();
@ -52,6 +53,7 @@ public class NewLinesInCells {
FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -18,6 +18,7 @@
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;
@ -26,14 +27,14 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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");
@ -50,10 +51,11 @@ public class Outlining {
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 );
@ -76,6 +78,7 @@ public class Outlining {
wb2.write(fileOut);
} finally {
fileOut.close();
wb2.close();
}
}
}

View File

@ -20,19 +20,32 @@
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;
@ -49,7 +62,7 @@ public class ScatterChart {
}
}
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);
@ -76,5 +89,6 @@ public class ScatterChart {
FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -18,6 +18,7 @@
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;
@ -29,7 +30,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
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");
@ -54,7 +55,7 @@ public class ShiftRows {
FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}

View File

@ -17,17 +17,18 @@
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");
@ -46,5 +47,6 @@ public class SplitAndFreezePanes {
FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -18,18 +18,17 @@
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");
@ -59,7 +58,7 @@ public class WorkbookProperties {
FileOutputStream out = new FileOutputStream("workbook.xlsx");
workbook.write(out);
out.close();
workbook.close();
}

View File

@ -17,17 +17,23 @@
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");
@ -40,13 +46,13 @@ public class WorkingWithBorders {
// 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);
@ -54,5 +60,6 @@ public class WorkingWithBorders {
FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -17,17 +17,22 @@
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");
@ -97,5 +102,6 @@ public class WorkingWithFonts {
FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -30,7 +30,7 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
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();
@ -48,13 +48,9 @@ public class BetterHeaderFooterExample {
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();
}
}

View File

@ -23,33 +23,31 @@ import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Iterator;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.openxml4j.opc.PackagePart;
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.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
/**
* Tests whether it is possible to successfully update an Excel workbook that is
* embedded into a WordprocessingML document. Note that the test has currently
* only been conducted with a binary Excel workbook and NOT yet with a
* SpreadsheetML workbook embedded into the document.
*
* <p>
* This code was successfully tested with the following file from the POI test collection:
* http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx
* </p>
*
* @author Mark B
* SpreadsheetML workbook embedded into the document.<p>
*
* This code was successfully tested with the following file from the POI test collection:
* http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx
*/
public class UpdateEmbeddedDoc {
@ -79,27 +77,15 @@ public class UpdateEmbeddedDoc {
this.docFile = new File(filename);
FileInputStream fis = null;
if (!this.docFile.exists()) {
throw new FileNotFoundException("The Word dcoument " +
filename +
" does not exist.");
throw new FileNotFoundException("The Word dcoument " + filename + " does not exist.");
}
try {
// Open the Word document file and instantiate the XWPFDocument
// class.
fis = new FileInputStream(this.docFile);
this.doc = new XWPFDocument(fis);
} finally {
if (fis != null) {
try {
fis.close();
fis = null;
} catch (IOException ioEx) {
System.out.println("IOException caught trying to close " +
"FileInputStream in the constructor of " +
"UpdateEmbeddedDoc.");
}
}
IOUtils.closeQuietly(fis);
}
}
@ -121,35 +107,38 @@ public class UpdateEmbeddedDoc {
* file system.
*/
public void updateEmbeddedDoc() throws OpenXML4JException, IOException {
Workbook workbook = null;
Sheet sheet = null;
Row row = null;
Cell cell = null;
PackagePart pPart = null;
Iterator<PackagePart> pIter = null;
List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();
if (embeddedDocs != null && !embeddedDocs.isEmpty()) {
pIter = embeddedDocs.iterator();
while (pIter.hasNext()) {
pPart = pIter.next();
if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||
pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {
// Get an InputStream from the pacage part and pass that
// to the create method of the WorkbookFactory class. Update
// the resulting Workbook and then stream that out again
// using an OutputStream obtained from the same PackagePart.
workbook = WorkbookFactory.create(pPart.getInputStream());
sheet = workbook.getSheetAt(SHEET_NUM);
row = sheet.getRow(ROW_NUM);
cell = row.getCell(CELL_NUM);
for (PackagePart pPart : embeddedDocs) {
String ext = pPart.getPartName().getExtension();
if (BINARY_EXTENSION.equals(ext) || OPENXML_EXTENSION.equals(ext)) {
// Get an InputStream from the package part and pass that
// to the create method of the WorkbookFactory class. Update
// the resulting Workbook and then stream that out again
// using an OutputStream obtained from the same PackagePart.
InputStream is = pPart.getInputStream();
Workbook workbook = null;
OutputStream os = null;
try {
workbook = WorkbookFactory.create(is);
Sheet sheet = workbook.getSheetAt(SHEET_NUM);
Row row = sheet.getRow(ROW_NUM);
Cell cell = row.getCell(CELL_NUM);
cell.setCellValue(NEW_VALUE);
workbook.write(pPart.getOutputStream());
os = pPart.getOutputStream();
workbook.write(os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(workbook);
IOUtils.closeQuietly(is);
}
}
}
if (!embeddedDocs.isEmpty()) {
// Finally, write the newly modified Word document out to file.
this.doc.write(new FileOutputStream(this.docFile));
FileOutputStream fos = new FileOutputStream(this.docFile);
this.doc.write(fos);
fos.close();
}
}
@ -179,24 +168,20 @@ public class UpdateEmbeddedDoc {
* file system.
*/
public void checkUpdatedDoc() throws OpenXML4JException, IOException {
Workbook workbook = null;
Sheet sheet = null;
Row row = null;
Cell cell = null;
PackagePart pPart = null;
Iterator<PackagePart> pIter = null;
List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();
if (embeddedDocs != null && !embeddedDocs.isEmpty()) {
pIter = embeddedDocs.iterator();
while (pIter.hasNext()) {
pPart = pIter.next();
if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||
pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {
workbook = WorkbookFactory.create(pPart.getInputStream());
sheet = workbook.getSheetAt(SHEET_NUM);
row = sheet.getRow(ROW_NUM);
cell = row.getCell(CELL_NUM);
for (PackagePart pPart : this.doc.getAllEmbedds()) {
String ext = pPart.getPartName().getExtension();
if (BINARY_EXTENSION.equals(ext) || OPENXML_EXTENSION.equals(ext)) {
InputStream is = pPart.getInputStream();
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(is);
Sheet sheet = workbook.getSheetAt(SHEET_NUM);
Row row = sheet.getRow(ROW_NUM);
Cell cell = row.getCell(CELL_NUM);
assertEquals(cell.getNumericCellValue(), NEW_VALUE, 0.0001);
} finally {
IOUtils.closeQuietly(workbook);
IOUtils.closeQuietly(is);
}
}
}
@ -206,16 +191,11 @@ public class UpdateEmbeddedDoc {
* Code to test updating of the embedded Excel workbook.
*
* @param args
* @throws OpenXML4JException
*/
public static void main(String[] args) {
try {
UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]);
ued.updateEmbeddedDoc();
ued.checkUpdatedDoc();
} catch (Exception ex) {
System.out.println(ex.getClass().getName());
System.out.println(ex.getMessage());
ex.printStackTrace(System.out);
}
public static void main(String[] args) throws IOException, OpenXML4JException {
UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]);
ued.updateEmbeddedDoc();
ued.checkUpdatedDoc();
}
}

View File

@ -56,9 +56,8 @@ public final class LittleEndianByteArrayInputStream extends ByteArrayInputStream
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;
}
@ -67,9 +66,8 @@ public final class LittleEndianByteArrayInputStream extends ByteArrayInputStream
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;
}
@ -88,9 +86,8 @@ public final class LittleEndianByteArrayInputStream extends ByteArrayInputStream
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;
}

View File

@ -261,7 +261,7 @@ public class WorkbookFactory {
}
} 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) {

View File

@ -48,10 +48,12 @@ import org.apache.poi.ss.usermodel.PictureData;
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;
@ -233,20 +235,14 @@ public class SXSSFWorkbook implements Workbook {
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 );
}
}
}
@ -364,62 +360,44 @@ public class SXSSFWorkbook implements Workbook {
{
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");
@ -428,7 +406,7 @@ public class SXSSFWorkbook implements Workbook {
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))
@ -492,7 +470,9 @@ public class SXSSFWorkbook implements Workbook {
}
else
{
if(pos>0) outWriter.write(s,0,pos);
if(pos>0) {
outWriter.write(s,0,pos);
}
if(c==s.charAt(0))
{
pos=1;
@ -510,13 +490,14 @@ public class SXSSFWorkbook implements Workbook {
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();
}
@ -830,7 +811,9 @@ public class SXSSFWorkbook implements Workbook {
* @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);
@ -934,7 +917,7 @@ public class SXSSFWorkbook implements Workbook {
}
/**
* 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.
@ -946,27 +929,23 @@ public class SXSSFWorkbook implements Workbook {
//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);
}
}
@ -1046,6 +1025,7 @@ public class SXSSFWorkbook implements Workbook {
*/
@Override
@Deprecated
@Removal(version="3.18")
public Name getNameAt(int nameIndex)
{
return _wb.getNameAt(nameIndex);
@ -1076,6 +1056,7 @@ public class SXSSFWorkbook implements Workbook {
*/
@Override
@Deprecated
@Removal(version="3.18")
public int getNameIndex(String name)
{
return _wb.getNameIndex(name);
@ -1090,6 +1071,7 @@ public class SXSSFWorkbook implements Workbook {
*/
@Override
@Deprecated
@Removal(version="3.18")
public void removeName(int index)
{
_wb.removeName(index);
@ -1104,6 +1086,7 @@ public class SXSSFWorkbook implements Workbook {
*/
@Override
@Deprecated
@Removal(version="3.18")
public void removeName(String name)
{
_wb.removeName(name);

View File

@ -46,6 +46,7 @@ import org.apache.poi.ss.util.CellReference;
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;
@ -180,32 +181,20 @@ public final class XSSFCell implements Cell {
// 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));
}
}
@ -303,7 +292,9 @@ public final class XSSFCell implements Cell {
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) {
@ -487,7 +478,9 @@ public final class XSSFCell implements Cell {
*/
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) {
@ -510,8 +503,10 @@ public final class XSSFCell implements Cell {
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
@ -560,7 +555,9 @@ public final class XSSFCell implements Cell {
XSSFWorkbook wb = _row.getSheet().getWorkbook();
if (formula == null) {
wb.onDeleteFormula(this);
if(_cell.isSetF()) _cell.unsetF();
if(_cell.isSetF()) {
_cell.unsetF();
}
return;
}
@ -571,7 +568,9 @@ public final class XSSFCell implements Cell {
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue(formula);
_cell.setF(f);
if(_cell.isSetV()) _cell.unsetV();
if(_cell.isSetV()) {
_cell.unsetV();
}
}
/**
@ -644,7 +643,9 @@ public final class XSSFCell implements Cell {
@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);
@ -670,7 +671,9 @@ public final class XSSFCell implements Cell {
* @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();
}
@ -684,7 +687,9 @@ public final class XSSFCell implements Cell {
*/
@Override
public CellType getCellTypeEnum() {
if (isFormulaCell()) return CellType.FORMULA;
if (isFormulaCell()) {
return CellType.FORMULA;
}
return getBaseCellType(true);
}
@ -700,7 +705,9 @@ public final class XSSFCell implements Cell {
* 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();
}
@ -826,7 +833,9 @@ public final class XSSFCell implements Cell {
*/
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();
}
@ -897,7 +906,9 @@ public final class XSSFCell implements Cell {
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);
}
@ -925,7 +936,9 @@ public final class XSSFCell implements Cell {
* @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));
}
@ -964,7 +977,9 @@ public final class XSSFCell implements Cell {
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue("0");
_cell.setF(f);
if(_cell.isSetT()) _cell.unsetT();
if(_cell.isSetT()) {
_cell.unsetT();
}
}
break;
case BLANK:

View File

@ -78,7 +78,7 @@ public class XSSFPivotCacheDefinition extends POIXMLDocumentPart{
options.setLoadReplaceDocumentElement(null);
ctPivotCacheDefinition = CTPivotCacheDefinition.Factory.parse(is, options);
} catch (XmlException e) {
throw new IOException(e.getLocalizedMessage());
throw new IOException(e.getLocalizedMessage(), e);
}
}
@ -123,22 +123,30 @@ public class XSSFPivotCacheDefinition extends POIXMLDocumentPart{
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);
}
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());
}
assert (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()) {
// TODO: case-sensitive?
if (name.equals(table.getName())) {
return new AreaReference(table.getStartCellReference(), table.getEndCellReference());
}
}

View File

@ -236,7 +236,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
private void initHyperlinks() {
hyperlinks = new ArrayList<XSSFHyperlink>();
if(!worksheet.isSetHyperlinks()) return;
if(!worksheet.isSetHyperlinks()) {
return;
}
try {
PackageRelationshipCollection hyperRels =
@ -390,11 +392,15 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
// 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();
@ -646,7 +652,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
// 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;
}
@ -659,12 +667,16 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
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);
@ -756,7 +768,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @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));
}
@ -778,7 +792,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
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,
@ -1181,7 +1197,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
@Override
public double getMargin(short margin) {
if (!worksheet.isSetPageMargins()) return 0;
if (!worksheet.isSetPageMargins()) {
return 0;
}
CTPageMargins pageMargins = worksheet.getPageMargins();
switch (margin) {
@ -1252,7 +1270,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
@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();
@ -1269,7 +1289,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
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();
@ -1302,7 +1324,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
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(),
@ -1861,7 +1885,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
@Override
public void removeMergedRegion(int index) {
if (!worksheet.isSetMergeCells()) return;
if (!worksheet.isSetMergeCells()) {
return;
}
CTMergeCells ctMergeCells = worksheet.getMergeCells();
int size = ctMergeCells.sizeOfMergeCellArray();
@ -1884,7 +1910,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
@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());
@ -2466,7 +2494,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
@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);
@ -2611,8 +2641,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
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;
@ -2641,8 +2672,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @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()) {
@ -2756,6 +2788,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @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) {
@ -2989,6 +3022,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
// 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();
@ -3038,7 +3072,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
}
}
if(rownum < startRow || rownum > endRow) continue;
if(rownum < startRow || rownum > endRow) {
continue;
}
if (!copyRowHeight) {
row.setHeight((short)-1);
@ -3266,6 +3302,8 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @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);
@ -3313,11 +3351,11 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
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);
}
/**
@ -3835,6 +3873,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
return dataValidationHelper;
}
@Override
public List<XSSFDataValidation> getDataValidations() {
List<XSSFDataValidation> xssfValidations = new ArrayList<XSSFDataValidation>();
CTDataValidations dataValidations = this.worksheet.getDataValidations();
@ -3879,7 +3918,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
@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());
@ -3945,7 +3986,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
public XSSFColor getTabColor() {
CTSheetPr pr = worksheet.getSheetPr();
if(pr == null) pr = worksheet.addNewSheetPr();
if(pr == null) {
pr = worksheet.addNewSheetPr();
}
if (!pr.isSetTabColor()) {
return null;
}
@ -3958,6 +4001,8 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @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);
@ -3971,7 +4016,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
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());
}
@ -4197,6 +4244,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
}
return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() {
@Override
public void configureReference(CTWorksheetSource wsSource) {
final String[] firstCell = source.getFirstCell().getCellRefParts();
final String firstRow = firstCell[1];
@ -4269,6 +4317,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
}
return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() {
@Override
public void configureReference(CTWorksheetSource wsSource) {
wsSource.setName(source.getNameName());
}
@ -4297,7 +4346,8 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
@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());
}
});
@ -4317,6 +4367,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
return tables;
}
@Override
public int getColumnOutlineLevel(int columnIndex) {
CTCol col = columnHelper.getColumn(columnIndex, false);
if (col == null) {

View File

@ -352,15 +352,19 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
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);
}
}
@ -723,8 +727,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
*/
@Override
public XSSFDataFormat createDataFormat() {
if (formatter == null)
if (formatter == null) {
formatter = new XSSFDataFormat(stylesSource);
}
return formatter;
}
@ -827,7 +832,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
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);
@ -860,7 +867,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
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;
}
@ -1082,7 +1091,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
@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();
@ -1146,7 +1157,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
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;
@ -1439,7 +1452,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
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){
@ -1639,21 +1654,28 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
*/
@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);
@ -1822,7 +1844,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* Returns the Theme of current workbook.
*/
public ThemesTable getTheme() {
if (stylesSource == null) return null;
if (stylesSource == null) {
return null;
}
return stylesSource.getTheme();
}
@ -1832,7 +1856,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
*/
@Override
public XSSFCreationHelper getCreationHelper() {
if(_creationHelper == null) _creationHelper = new XSSFCreationHelper(this);
if(_creationHelper == null) {
_creationHelper = new XSSFCreationHelper(this);
}
return _creationHelper;
}
@ -1857,8 +1883,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
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;
}
@ -2149,7 +2176,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* 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");
}
@ -2159,7 +2188,9 @@ public class XSSFWorkbook extends POIXMLDocument implements 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");
}
@ -2171,7 +2202,9 @@ public class XSSFWorkbook extends POIXMLDocument implements 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");
}
@ -2181,7 +2214,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* @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");
}

View File

@ -26,20 +26,19 @@ public class NumericRanges {
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) {
@ -47,17 +46,18 @@ public class NumericRanges {
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;

View File

@ -26,37 +26,7 @@ import org.apache.poi.util.Internal;
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>
@ -114,8 +84,8 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
for (XWPFParagraph p : footnote.getParagraphs()) {
if (!first) {
footnoteText.append("\n");
first = false;
}
first = false;
footnoteText.append(p.getText());
}
@ -204,6 +174,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
return !paragraph.getDomNode().hasChildNodes();
}
@Override
public XWPFDocument getDocument() {
return document;
}
@ -240,8 +211,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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;
@ -257,8 +229,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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;
@ -270,10 +243,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* @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();
}
@ -289,8 +264,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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;
@ -319,8 +295,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
}
}
if (level != null && level.getNumFmt() != null
&& level.getNumFmt().getVal() != null)
&& level.getNumFmt().getVal() != null) {
return level.getNumFmt().getVal().toString();
}
}
}
return null;
@ -339,26 +316,31 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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++) {
@ -369,8 +351,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
}
}
if (level != null && level.getLvlText() != null
&& level.getLvlText().getVal() != null)
&& level.getLvlText().getVal() != null) {
return level.getLvlText().getVal().toString();
}
}
}
return null;
@ -486,10 +469,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
/**
* @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);
@ -600,10 +585,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
}
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()));
}
}
/**
@ -654,10 +640,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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()));
}
}
/**
@ -703,10 +690,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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()));
}
}
/**
@ -752,10 +740,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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()));
}
}
/**
@ -805,10 +794,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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()));
}
}
/**
@ -857,10 +847,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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);
}
}
/**
@ -1228,26 +1219,32 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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);
}
@ -1260,6 +1257,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
*
* @return boolean
*/
@Override
public boolean isWordWrapped() {
CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr()
.getWordWrap() : null;
@ -1279,13 +1277,15 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
*
* @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() {
@ -1325,8 +1325,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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;
}
@ -1337,8 +1338,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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;
}
@ -1349,8 +1351,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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;
}
@ -1536,8 +1539,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
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;
}
@ -1585,10 +1589,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
*
* @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType()
*/
@Override
public BodyElementType getElementType() {
return BodyElementType.PARAGRAPH;
}
@Override
public IBody getBody() {
return part;
}
@ -1598,6 +1604,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/
@Override
public POIXMLDocumentPart getPart() {
if (part != null) {
return part.getPart();
@ -1610,6 +1617,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
@Override
public BodyType getPartType() {
return part.getPartType();
}

View File

@ -156,11 +156,7 @@ public class XWPFPictureData extends POIXMLDocumentPart {
} 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);
}

View File

@ -36,7 +36,11 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
@ -389,17 +393,16 @@ public class TestSignatureInfo {
throw e;
}
if((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) {
Assume.assumeTrue("Only allowing ConnectException with 'timed out' as message here, but had: " + e,
Assume.assumeFalse("Only allowing ConnectException with 'timed out' as message here, but had: " + e,
e.getCause().getMessage().contains("timed out"));
} else if (e.getCause() instanceof IOException) {
Assume.assumeTrue("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e,
Assume.assumeFalse("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e,
e.getCause().getMessage().contains("Error contacting TSP server"));
} else if (e.getCause() instanceof RuntimeException) {
Assume.assumeTrue("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e,
Assume.assumeFalse("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e,
e.getCause().getMessage().contains("This site is cur"));
} else {
throw e;
}
throw e;
}
// verify
@ -557,7 +560,9 @@ public class TestSignatureInfo {
boolean b = si.verifySignature();
assertTrue("Signature not correctly calculated for " + ha, b);
} finally {
if (pkg != null) pkg.close();
if (pkg != null) {
pkg.close();
}
}
}
}