SonarQube fixes - close resources

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1796962 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2017-05-31 00:31:53 +00:00
parent 7e6007e0bd
commit 95164e4a50
21 changed files with 695 additions and 668 deletions

View File

@ -34,30 +34,31 @@ public final class BulletsDemo {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
HSLFSlideShow ppt = new HSLFSlideShow(); HSLFSlideShow ppt = new HSLFSlideShow();
try {
HSLFSlide slide = ppt.createSlide(); HSLFSlide slide = ppt.createSlide();
HSLFTextBox shape = new HSLFTextBox(); HSLFTextBox shape = new HSLFTextBox();
HSLFTextParagraph rt = shape.getTextParagraphs().get(0); HSLFTextParagraph rt = shape.getTextParagraphs().get(0);
rt.getTextRuns().get(0).setFontSize(42d); rt.getTextRuns().get(0).setFontSize(42d);
rt.setBullet(true); rt.setBullet(true);
rt.setIndent(0d); //bullet offset rt.setIndent(0d); //bullet offset
rt.setLeftMargin(50d); //text offset (should be greater than bullet offset) rt.setLeftMargin(50d); //text offset (should be greater than bullet offset)
rt.setBulletChar('\u263A'); //bullet character rt.setBulletChar('\u263A'); //bullet character
shape.setText( shape.setText(
"January\r" + "January\r" +
"February\r" + "February\r" +
"March\r" + "March\r" +
"April"); "April");
slide.addShape(shape); slide.addShape(shape);
shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide
slide.addShape(shape); slide.addShape(shape);
FileOutputStream out = new FileOutputStream("bullets.ppt"); FileOutputStream out = new FileOutputStream("bullets.ppt");
ppt.write(out); ppt.write(out);
out.close(); out.close();
} finally {
ppt.close(); ppt.close();
}
} }
} }

View File

@ -34,31 +34,33 @@ public abstract class CreateHyperlink {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
HSLFSlideShow ppt = new HSLFSlideShow(); HSLFSlideShow ppt = new HSLFSlideShow();
HSLFSlide slideA = ppt.createSlide(); try {
ppt.createSlide(); HSLFSlide slideA = ppt.createSlide();
HSLFSlide slideC = ppt.createSlide(); ppt.createSlide();
HSLFSlide slideC = ppt.createSlide();
// link to a URL
HSLFTextBox textBox1 = slideA.createTextBox(); // link to a URL
textBox1.setText("Apache POI"); HSLFTextBox textBox1 = slideA.createTextBox();
textBox1.setAnchor(new Rectangle(100, 100, 200, 50)); textBox1.setText("Apache POI");
textBox1.setAnchor(new Rectangle(100, 100, 200, 50));
HSLFHyperlink link1 = textBox1.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
link1.linkToUrl("http://www.apache.org"); HSLFHyperlink link1 = textBox1.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
link1.setLabel(textBox1.getText()); link1.linkToUrl("http://www.apache.org");
link1.setLabel(textBox1.getText());
// link to another slide
HSLFTextBox textBox2 = slideA.createTextBox(); // link to another slide
textBox2.setText("Go to slide #3"); HSLFTextBox textBox2 = slideA.createTextBox();
textBox2.setAnchor(new Rectangle(100, 300, 200, 50)); textBox2.setText("Go to slide #3");
textBox2.setAnchor(new Rectangle(100, 300, 200, 50));
HSLFHyperlink link2 = textBox2.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
link2.linkToSlide(slideC); HSLFHyperlink link2 = textBox2.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
link2.linkToSlide(slideC);
FileOutputStream out = new FileOutputStream("hyperlink.ppt");
ppt.write(out); FileOutputStream out = new FileOutputStream("hyperlink.ppt");
out.close(); ppt.write(out);
out.close();
ppt.close(); } finally {
ppt.close();
}
} }
} }

View File

@ -41,45 +41,47 @@ public final class Graphics2DDemo {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
HSLFSlideShow ppt = new HSLFSlideShow(); HSLFSlideShow ppt = new HSLFSlideShow();
//bar chart data. The first value is the bar color, the second is the width try {
Object[] def = new Object[]{ //bar chart data. The first value is the bar color, the second is the width
Color.yellow, 40, Object[] def = new Object[]{
Color.green, 60, Color.yellow, 40,
Color.gray, 30, Color.green, 60,
Color.red, 80, Color.gray, 30,
}; Color.red, 80,
};
HSLFSlide slide = ppt.createSlide();
HSLFSlide slide = ppt.createSlide();
HSLFGroupShape group = new HSLFGroupShape();
//define position of the drawing in the slide HSLFGroupShape group = new HSLFGroupShape();
Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); //define position of the drawing in the slide
group.setAnchor(bounds); Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300);
group.setInteriorAnchor(new java.awt.Rectangle(0, 0, 100, 100)); group.setAnchor(bounds);
slide.addShape(group); group.setInteriorAnchor(new java.awt.Rectangle(0, 0, 100, 100));
Graphics2D graphics = new PPGraphics2D(group); slide.addShape(group);
Graphics2D graphics = new PPGraphics2D(group);
//draw a simple bar graph
int x = 10, y = 10; //draw a simple bar graph
graphics.setFont(new Font("Arial", Font.BOLD, 10)); int x = 10, y = 10;
for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { graphics.setFont(new Font("Arial", Font.BOLD, 10));
for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {
graphics.setColor(Color.black);
int width = ((Integer)def[i+1]).intValue();
graphics.drawString("Q" + idx, x-5, y+10);
graphics.drawString(width + "%", x + width+3, y + 10);
graphics.setColor((Color)def[i]);
graphics.fill(new Rectangle(x, y, width, 10));
y += 15;
}
graphics.setColor(Color.black); graphics.setColor(Color.black);
int width = ((Integer)def[i+1]).intValue(); graphics.setFont(new Font("Arial", Font.BOLD, 14));
graphics.drawString("Q" + idx, x-5, y+10); graphics.draw(group.getInteriorAnchor());
graphics.drawString(width + "%", x + width+3, y + 10); graphics.drawString("Performance", x + 30, y + 10);
graphics.setColor((Color)def[i]);
graphics.fill(new Rectangle(x, y, width, 10)); FileOutputStream out = new FileOutputStream("hslf-graphics.ppt");
y += 15; ppt.write(out);
out.close();
} finally {
ppt.close();
} }
graphics.setColor(Color.black);
graphics.setFont(new Font("Arial", Font.BOLD, 14));
graphics.draw(group.getInteriorAnchor());
graphics.drawString("Performance", x + 30, y + 10);
FileOutputStream out = new FileOutputStream("hslf-graphics.ppt");
ppt.write(out);
out.close();
ppt.close();
} }
} }

View File

@ -29,22 +29,24 @@ public abstract class HeadersFootersDemo {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
HSLFSlideShow ppt = new HSLFSlideShow(); HSLFSlideShow ppt = new HSLFSlideShow();
HeadersFooters slideHeaders = ppt.getSlideHeadersFooters(); try {
slideHeaders.setFootersText("Created by POI-HSLF"); HeadersFooters slideHeaders = ppt.getSlideHeadersFooters();
slideHeaders.setSlideNumberVisible(true); slideHeaders.setFootersText("Created by POI-HSLF");
slideHeaders.setDateTimeText("custom date time"); slideHeaders.setSlideNumberVisible(true);
slideHeaders.setDateTimeText("custom date time");
HeadersFooters notesHeaders = ppt.getNotesHeadersFooters();
notesHeaders.setFootersText("My notes footers"); HeadersFooters notesHeaders = ppt.getNotesHeadersFooters();
notesHeaders.setHeaderText("My notes header"); notesHeaders.setFootersText("My notes footers");
notesHeaders.setHeaderText("My notes header");
ppt.createSlide();
ppt.createSlide();
FileOutputStream out = new FileOutputStream("headers_footers.ppt");
ppt.write(out); FileOutputStream out = new FileOutputStream("headers_footers.ppt");
out.close(); ppt.write(out);
out.close();
ppt.close(); } finally {
ppt.close();
}
} }
} }

View File

@ -31,27 +31,45 @@ import org.apache.poi.sl.usermodel.VerticalAlignment;
/** /**
* Demonstrates how to create tables * Demonstrates how to create tables
*
* @author Yegor Kozlov
*/ */
public final class TableDemo { public final class TableDemo {
//test data for the first table
static final String[][] txt1 = {
{"INPUT FILE", "NUMBER OF RECORDS"},
{"Item File", "11,559"},
{"Vendor File", "502"},
{"Purchase History File - # of PO\u2019s\r(12/01/04 - 05/31/06)", "12,852"},
{"Purchase History File - # of PO Lines\r(12/01/04 - 05/31/06)", "53,523" },
{"Total PO History Spend", "$10,172,038"}
};
//test data for the second taable
static final String[][] txt2 = {
{"Data Source"},
{"CAS Internal Metrics - Item Master Summary\r" +
"CAS Internal Metrics - Vendor Summary\r" +
"CAS Internal Metrics - PO History Summary"}
};
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
//test data for the first taable
String[][] txt1 = {
{"INPUT FILE", "NUMBER OF RECORDS"},
{"Item File", "11,559"},
{"Vendor File", "502"},
{"Purchase History File - # of PO\u2019s\r(12/01/04 - 05/31/06)", "12,852"},
{"Purchase History File - # of PO Lines\r(12/01/04 - 05/31/06)", "53,523" },
{"Total PO History Spend", "$10,172,038"}
};
HSLFSlideShow ppt = new HSLFSlideShow(); HSLFSlideShow ppt = new HSLFSlideShow();
HSLFSlide slide = ppt.createSlide(); try {
HSLFSlide slide = ppt.createSlide();
create1stTable(slide);
create2ndTable(slide);
FileOutputStream out = new FileOutputStream("hslf-table.ppt");
ppt.write(out);
out.close();
} finally {
ppt.close();
}
}
static void create1stTable(HSLFSlide slide) {
//six rows, two columns //six rows, two columns
HSLFTable table1 = slide.createTable(6, 2); HSLFTable table1 = slide.createTable(6, 2);
for (int i = 0; i < txt1.length; i++) { for (int i = 0; i < txt1.length; i++) {
@ -77,17 +95,11 @@ public final class TableDemo {
table1.setColumnWidth(0, 300); table1.setColumnWidth(0, 300);
table1.setColumnWidth(1, 150); table1.setColumnWidth(1, 150);
int pgWidth = ppt.getPageSize().width; int pgWidth = slide.getSlideShow().getPageSize().width;
table1.moveTo((pgWidth - table1.getAnchor().getWidth())/2., 100.); table1.moveTo((pgWidth - table1.getAnchor().getWidth())/2., 100.);
}
//test data for the second taable static void create2ndTable(HSLFSlide slide) {
String[][] txt2 = {
{"Data Source"},
{"CAS Internal Metrics - Item Master Summary\r" +
"CAS Internal Metrics - Vendor Summary\r" +
"CAS Internal Metrics - PO History Summary"}
};
//two rows, one column //two rows, one column
HSLFTable table2 = slide.createTable(2, 1); HSLFTable table2 = slide.createTable(2, 1);
for (int i = 0; i < txt2.length; i++) { for (int i = 0; i < txt2.length; i++) {
@ -120,11 +132,5 @@ public final class TableDemo {
dts2.setOutsideBorders(Color.black, 1.0); dts2.setOutsideBorders(Color.black, 1.0);
table2.moveTo(200, 400); table2.moveTo(200, 400);
FileOutputStream out = new FileOutputStream("hslf-table.ppt");
ppt.write(out);
out.close();
ppt.close();
} }
} }

View File

@ -731,13 +731,16 @@ public class AddDimensionedImage {
outputFile = args[1]; outputFile = args[1];
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
sheet = workbook.createSheet("Picture Test"); try {
new AddDimensionedImage().addImageToSheet("A1", sheet, sheet = workbook.createSheet("Picture Test");
imageFile, 125, 125, new AddDimensionedImage().addImageToSheet("A1", sheet,
AddDimensionedImage.EXPAND_ROW_AND_COLUMN); imageFile, 125, 125,
fos = new FileOutputStream(outputFile); AddDimensionedImage.EXPAND_ROW_AND_COLUMN);
workbook.write(fos); fos = new FileOutputStream(outputFile);
workbook.close(); workbook.write(fos);
} finally {
workbook.close();
}
} }
catch(FileNotFoundException fnfEx) { catch(FileNotFoundException fnfEx) {
System.out.println("Caught an: " + fnfEx.getClass().getName()); System.out.println("Caught an: " + fnfEx.getClass().getName());

View File

@ -38,138 +38,142 @@ public class BigExample {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
int rownum; int rownum;
// create a new file
FileOutputStream out = new FileOutputStream("workbook.xls");
// create a new workbook // create a new workbook
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
// create a new sheet try {
HSSFSheet s = wb.createSheet(); // create a new sheet
// declare a row object reference HSSFSheet s = wb.createSheet();
HSSFRow r = null; // declare a row object reference
// declare a cell object reference HSSFRow r = null;
HSSFCell c = null; // declare a cell object reference
// create 3 cell styles HSSFCell c = null;
HSSFCellStyle cs = wb.createCellStyle(); // create 3 cell styles
HSSFCellStyle cs2 = wb.createCellStyle(); HSSFCellStyle cs = wb.createCellStyle();
HSSFCellStyle cs3 = wb.createCellStyle(); HSSFCellStyle cs2 = wb.createCellStyle();
// create 2 fonts objects HSSFCellStyle cs3 = wb.createCellStyle();
HSSFFont f = wb.createFont(); // create 2 fonts objects
HSSFFont f2 = wb.createFont(); HSSFFont f = wb.createFont();
HSSFFont f2 = wb.createFont();
//set font 1 to 12 point type
f.setFontHeightInPoints((short) 12); //set font 1 to 12 point type
//make it red f.setFontHeightInPoints((short) 12);
f.setColor(HSSFColorPredefined.RED.getIndex()); //make it red
// make it bold f.setColor(HSSFColorPredefined.RED.getIndex());
//arial is the default font // make it bold
f.setBold(true); //arial is the default font
f.setBold(true);
//set font 2 to 10 point type
f2.setFontHeightInPoints((short) 10); //set font 2 to 10 point type
//make it the color at palette index 0xf (white) f2.setFontHeightInPoints((short) 10);
f2.setColor(HSSFColorPredefined.WHITE.getIndex()); //make it the color at palette index 0xf (white)
//make it bold f2.setColor(HSSFColorPredefined.WHITE.getIndex());
f2.setBold(true); //make it bold
f2.setBold(true);
//set cell stlye
cs.setFont(f); //set cell stlye
//set the cell format see HSSFDataFromat for a full list cs.setFont(f);
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); //set the cell format see HSSFDataFromat for a full list
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
//set a thin border
cs2.setBorderBottom(BorderStyle.THIN); //set a thin border
//fill w fg fill color cs2.setBorderBottom(BorderStyle.THIN);
cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND); //fill w fg fill color
// set foreground fill to red cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cs2.setFillForegroundColor(HSSFColorPredefined.RED.getIndex()); // set foreground fill to red
cs2.setFillForegroundColor(HSSFColorPredefined.RED.getIndex());
// set the font
cs2.setFont(f2); // set the font
cs2.setFont(f2);
// set the sheet name to HSSF Test
wb.setSheetName(0, "HSSF Test"); // set the sheet name to HSSF Test
// create a sheet with 300 rows (0-299) wb.setSheetName(0, "HSSF Test");
for (rownum = 0; rownum < 300; rownum++) // create a sheet with 300 rows (0-299)
{ for (rownum = 0; rownum < 300; rownum++)
// create a row {
// create a row
r = s.createRow(rownum);
// on every other row
if ((rownum % 2) == 0)
{
// make the row height bigger (in twips - 1/20 of a point)
r.setHeight((short) 0x249);
}
//r.setRowNum(( short ) rownum);
// create 50 cells (0-49) (the += 2 becomes apparent later
for (int cellnum = 0; cellnum < 50; cellnum += 2)
{
// create a numeric cell
c = r.createCell(cellnum);
// do some goofy math to demonstrate decimals
c.setCellValue(rownum * 10000 + cellnum
+ (((double) rownum / 1000)
+ ((double) cellnum / 10000)));
// on every other row
if ((rownum % 2) == 0)
{
// set this cell to the first cell style we defined
c.setCellStyle(cs);
}
// create a string cell (see why += 2 in the
c = r.createCell(cellnum + 1);
// set the cell's string value to "TEST"
c.setCellValue("TEST");
// make this column a bit wider
s.setColumnWidth(cellnum + 1, (int)((50 * 8) / ((double) 1 / 20)));
// on every other row
if ((rownum % 2) == 0)
{
// set this to the white on red cell style
// we defined above
c.setCellStyle(cs2);
}
}
}
//draw a thick black border on the row at the bottom using BLANKS
// advance 2 rows
rownum++;
rownum++;
r = s.createRow(rownum); r = s.createRow(rownum);
// on every other row
if ((rownum % 2) == 0) // define the third style to be the default
{ // except with a thick black border at the bottom
// make the row height bigger (in twips - 1/20 of a point) cs3.setBorderBottom(BorderStyle.THICK);
r.setHeight((short) 0x249);
} //create 50 cells
for (int cellnum =0; cellnum < 50; cellnum++) {
//r.setRowNum(( short ) rownum); //create a blank type cell (no value)
// create 50 cells (0-49) (the += 2 becomes apparent later
for (int cellnum = 0; cellnum < 50; cellnum += 2)
{
// create a numeric cell
c = r.createCell(cellnum); c = r.createCell(cellnum);
// do some goofy math to demonstrate decimals // set it to the thick black border style
c.setCellValue(rownum * 10000 + cellnum c.setCellStyle(cs3);
+ (((double) rownum / 1000)
+ ((double) cellnum / 10000)));
// on every other row
if ((rownum % 2) == 0)
{
// set this cell to the first cell style we defined
c.setCellStyle(cs);
}
// create a string cell (see why += 2 in the
c = r.createCell(cellnum + 1);
// set the cell's string value to "TEST"
c.setCellValue("TEST");
// make this column a bit wider
s.setColumnWidth(cellnum + 1, (int)((50 * 8) / ((double) 1 / 20)));
// on every other row
if ((rownum % 2) == 0)
{
// set this to the white on red cell style
// we defined above
c.setCellStyle(cs2);
}
} }
//end draw thick black border
// demonstrate adding/naming and deleting a sheet
// create a sheet, set its title then delete it
wb.createSheet();
wb.setSheetName(1, "DeletedSheet");
wb.removeSheetAt(1);
//end deleted sheet
// create a new file
FileOutputStream out = new FileOutputStream("workbook.xls");
// write the workbook to the output stream
// close our file (don't blow out our file handles
wb.write(out);
out.close();
} finally {
wb.close();
} }
//draw a thick black border on the row at the bottom using BLANKS
// advance 2 rows
rownum++;
rownum++;
r = s.createRow(rownum);
// define the third style to be the default
// except with a thick black border at the bottom
cs3.setBorderBottom(BorderStyle.THICK);
//create 50 cells
for (int cellnum =0; cellnum < 50; cellnum++) {
//create a blank type cell (no value)
c = r.createCell(cellnum);
// set it to the thick black border style
c.setCellStyle(cs3);
}
//end draw thick black border
// demonstrate adding/naming and deleting a sheet
// create a sheet, set its title then delete it
wb.createSheet();
wb.setSheetName(1, "DeletedSheet");
wb.removeSheetAt(1);
//end deleted sheet
// write the workbook to the output stream
// close our file (don't blow out our file handles
wb.write(out);
out.close();
wb.close();
} }
} }

View File

@ -34,32 +34,34 @@ import org.apache.poi.ss.usermodel.BorderStyle;
public class Borders { public class Borders {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet"); try {
HSSFSheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based. // Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(1); HSSFRow row = sheet.createRow(1);
// Create a cell and put a value in it. // Create a cell and put a value in it.
HSSFCell cell = row.createCell(1); HSSFCell cell = row.createCell(1);
cell.setCellValue(4); cell.setCellValue(4);
// Style the cell with borders all around. // Style the cell with borders all around.
HSSFCellStyle style = wb.createCellStyle(); HSSFCellStyle style = wb.createCellStyle();
style.setBorderBottom(BorderStyle.THIN); style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(HSSFColorPredefined.BLACK.getIndex()); style.setBottomBorderColor(HSSFColorPredefined.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(HSSFColorPredefined.GREEN.getIndex()); style.setLeftBorderColor(HSSFColorPredefined.GREEN.getIndex());
style.setBorderRight(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(HSSFColorPredefined.BLUE.getIndex()); style.setRightBorderColor(HSSFColorPredefined.BLUE.getIndex());
style.setBorderTop(BorderStyle.MEDIUM_DASHED); style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(HSSFColorPredefined.ORANGE.getIndex()); style.setTopBorderColor(HSSFColorPredefined.ORANGE.getIndex());
cell.setCellStyle(style); cell.setCellStyle(style);
// Write the output to a file // Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls"); FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
} finally {
wb.close(); wb.close();
}
} }
} }

View File

@ -31,76 +31,76 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
/** /**
* Demonstrates how to work with excel cell comments. * Demonstrates how to work with excel cell comments.<p>
* *
* <p>
* Excel comment is a kind of a text shape, * Excel comment is a kind of a text shape,
* so inserting a comment is very similar to placing a text box in a worksheet * so inserting a comment is very similar to placing a text box in a worksheet
* </p>
*/ */
public class CellComments { public class CellComments {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF"); try {
HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF");
// Create the drawing patriarch. This is the top level container for all shapes including cell comments.
HSSFPatriarch patr = sheet.createDrawingPatriarch(); // Create the drawing patriarch. This is the top level container for all shapes including cell comments.
HSSFPatriarch patr = sheet.createDrawingPatriarch();
//create a cell in row 3
HSSFCell cell1 = sheet.createRow(3).createCell(1); //create a cell in row 3
cell1.setCellValue(new HSSFRichTextString("Hello, World")); HSSFCell cell1 = sheet.createRow(3).createCell(1);
cell1.setCellValue(new HSSFRichTextString("Hello, World"));
//anchor defines size and position of the comment in worksheet
HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5)); //anchor defines size and position of the comment in worksheet
HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
// set text in the comment
comment1.setString(new HSSFRichTextString("We can set comments in POI")); // set text in the comment
comment1.setString(new HSSFRichTextString("We can set comments in POI"));
//set comment author.
//you can see it in the status bar when moving mouse over the commented cell //set comment author.
comment1.setAuthor("Apache Software Foundation"); //you can see it in the status bar when moving mouse over the commented cell
comment1.setAuthor("Apache Software Foundation");
// The first way to assign comment to a cell is via HSSFCell.setCellComment method
cell1.setCellComment(comment1); // The first way to assign comment to a cell is via HSSFCell.setCellComment method
cell1.setCellComment(comment1);
//create another cell in row 6
HSSFCell cell2 = sheet.createRow(6).createCell(1); //create another cell in row 6
cell2.setCellValue(36.6); HSSFCell cell2 = sheet.createRow(6).createCell(1);
cell2.setCellValue(36.6);
HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 8, (short) 6, 11));
//modify background color of the comment HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 8, (short) 6, 11));
comment2.setFillColor(204, 236, 255); //modify background color of the comment
comment2.setFillColor(204, 236, 255);
HSSFRichTextString string = new HSSFRichTextString("Normal body temperature");
HSSFRichTextString string = new HSSFRichTextString("Normal body temperature");
//apply custom font to the text in the comment
HSSFFont font = wb.createFont(); //apply custom font to the text in the comment
font.setFontName("Arial"); HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10); font.setFontName("Arial");
font.setBold(true); font.setFontHeightInPoints((short)10);
font.setColor(HSSFColorPredefined.RED.getIndex()); font.setBold(true);
string.applyFont(font); font.setColor(HSSFColorPredefined.RED.getIndex());
string.applyFont(font);
comment2.setString(string);
comment2.setVisible(true); //by default comments are hidden. This one is always visible. comment2.setString(string);
comment2.setVisible(true); //by default comments are hidden. This one is always visible.
comment2.setAuthor("Bill Gates");
comment2.setAuthor("Bill Gates");
/**
* The second way to assign comment to a cell is to implicitly specify its row and column. /**
* Note, it is possible to set row and column of a non-existing cell. * The second way to assign comment to a cell is to implicitly specify its row and column.
* It works, the comment is visible. * Note, it is possible to set row and column of a non-existing cell.
*/ * It works, the comment is visible.
comment2.setRow(6); */
comment2.setColumn(1); comment2.setRow(6);
comment2.setColumn(1);
FileOutputStream out = new FileOutputStream("poi_comment.xls");
wb.write(out); FileOutputStream out = new FileOutputStream("poi_comment.xls");
out.close(); wb.write(out);
out.close();
wb.close(); } finally {
wb.close();
}
} }
} }

View File

@ -29,19 +29,21 @@ import org.apache.poi.ss.usermodel.CellType;
public class CellTypes { public class CellTypes {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet"); try {
HSSFRow row = sheet.createRow(2); HSSFSheet sheet = wb.createSheet("new sheet");
row.createCell(0).setCellValue(1.1); HSSFRow row = sheet.createRow(2);
row.createCell(1).setCellValue(new Date()); row.createCell(0).setCellValue(1.1);
row.createCell(2).setCellValue("a string"); row.createCell(1).setCellValue(new Date());
row.createCell(3).setCellValue(true); row.createCell(2).setCellValue("a string");
row.createCell(4).setCellType(CellType.ERROR); row.createCell(3).setCellValue(true);
row.createCell(4).setCellType(CellType.ERROR);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls"); // Write the output to a file
wb.write(fileOut); FileOutputStream fileOut = new FileOutputStream("workbook.xls");
fileOut.close(); wb.write(fileOut);
fileOut.close();
wb.close(); } finally {
wb.close();
}
} }
} }

View File

@ -41,6 +41,7 @@ public class UserDefinedFunctionExample {
public static void main( String[] args ) throws Exception { public static void main( String[] args ) throws Exception {
if( args.length != 2 ) { if( args.length != 2 ) {
// e.g. src/examples/src/org/apache/poi/ss/examples/formula/mortgage-calculation.xls Sheet1!B4
System.out.println( "usage: UserDefinedFunctionExample fileName cellId" ) ; System.out.println( "usage: UserDefinedFunctionExample fileName cellId" ) ;
return; return;
} }
@ -50,32 +51,32 @@ public class UserDefinedFunctionExample {
File workbookFile = new File( args[0] ) ; File workbookFile = new File( args[0] ) ;
FileInputStream fis = new FileInputStream(workbookFile); Workbook workbook = WorkbookFactory.create(workbookFile, null, true);
Workbook workbook = WorkbookFactory.create(fis);
fis.close();
String[] functionNames = { "calculatePayment" } ; try {
FreeRefFunction[] functionImpls = { new CalculateMortgage() } ; String[] functionNames = { "calculatePayment" } ;
FreeRefFunction[] functionImpls = { new CalculateMortgage() } ;
UDFFinder udfToolpack = new DefaultUDFFinder( functionNames, functionImpls ) ;
UDFFinder udfToolpack = new DefaultUDFFinder( functionNames, functionImpls ) ;
// register the user-defined function in the workbook
workbook.addToolPack(udfToolpack); // register the user-defined function in the workbook
workbook.addToolPack(udfToolpack);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
CellReference cr = new CellReference( args[1] ) ;
String sheetName = cr.getSheetName() ; CellReference cr = new CellReference( args[1] ) ;
Sheet sheet = workbook.getSheet( sheetName ) ; String sheetName = cr.getSheetName() ;
int rowIdx = cr.getRow() ; Sheet sheet = workbook.getSheet( sheetName ) ;
int colIdx = cr.getCol() ; int rowIdx = cr.getRow() ;
Row row = sheet.getRow( rowIdx ) ; int colIdx = cr.getCol() ;
Cell cell = row.getCell( colIdx ) ; Row row = sheet.getRow( rowIdx ) ;
Cell cell = row.getCell( colIdx ) ;
CellValue value = evaluator.evaluate( cell ) ;
CellValue value = evaluator.evaluate( cell ) ;
System.out.println("returns value: " + value ) ;
System.out.println("returns value: " + value ) ;
workbook.close(); } finally {
workbook.close();
}
} }
} }

View File

@ -24,31 +24,30 @@ import java.io.FileOutputStream;
/** /**
* Merge multiple pptx presentations together * Merge multiple pptx presentations together
*
* @author Yegor Kozlov
*/ */
public final class MergePresentations { public final class MergePresentations {
public static void main(String args[]) throws Exception { public static void main(String args[]) throws Exception {
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
for(String arg : args){ try {
FileInputStream is = new FileInputStream(arg); for (String arg : args){
XMLSlideShow src = new XMLSlideShow(is); FileInputStream is = new FileInputStream(arg);
is.close(); XMLSlideShow src = new XMLSlideShow(is);
is.close();
for(XSLFSlide srcSlide : src.getSlides()){
ppt.createSlide().importContent(srcSlide); for(XSLFSlide srcSlide : src.getSlides()){
ppt.createSlide().importContent(srcSlide);
}
src.close();
} }
src.close(); FileOutputStream out = new FileOutputStream("merged.pptx");
ppt.write(out);
out.close();
} finally {
ppt.close();
} }
FileOutputStream out = new FileOutputStream("merged.pptx");
ppt.write(out);
out.close();
ppt.close();
} }
} }

View File

@ -25,50 +25,50 @@ import java.io.IOException;
/** /**
* Demonstrates how to create slides with predefined layout * Demonstrates how to create slides with predefined layout
* and fill the placeholder shapes * and fill the placeholder shapes
*
* @author Yegor Kozlov
*/ */
public class Tutorial1 { public class Tutorial1 {
public static void main(String[] args) throws IOException{ public static void main(String[] args) throws IOException{
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
// XSLFSlide#createSlide() with no arguments creates a blank slide try {
/*XSLFSlide blankSlide =*/ ppt.createSlide(); // XSLFSlide#createSlide() with no arguments creates a blank slide
/*XSLFSlide blankSlide =*/ ppt.createSlide();
XSLFSlideMaster master = ppt.getSlideMasters().get(0);
XSLFSlideMaster master = ppt.getSlideMasters().get(0);
XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);
XSLFSlide slide1 = ppt.createSlide(layout1) ; XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);
XSLFTextShape[] ph1 = slide1.getPlaceholders(); XSLFSlide slide1 = ppt.createSlide(layout1) ;
XSLFTextShape titlePlaceholder1 = ph1[0]; XSLFTextShape[] ph1 = slide1.getPlaceholders();
titlePlaceholder1.setText("This is a title"); XSLFTextShape titlePlaceholder1 = ph1[0];
XSLFTextShape subtitlePlaceholder1 = ph1[1]; titlePlaceholder1.setText("This is a title");
subtitlePlaceholder1.setText("this is a subtitle"); XSLFTextShape subtitlePlaceholder1 = ph1[1];
subtitlePlaceholder1.setText("this is a subtitle");
XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide2 = ppt.createSlide(layout2) ; XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFTextShape[] ph2 = slide2.getPlaceholders(); XSLFSlide slide2 = ppt.createSlide(layout2) ;
XSLFTextShape titlePlaceholder2 = ph2[0]; XSLFTextShape[] ph2 = slide2.getPlaceholders();
titlePlaceholder2.setText("This is a title"); XSLFTextShape titlePlaceholder2 = ph2[0];
XSLFTextShape bodyPlaceholder = ph2[1]; titlePlaceholder2.setText("This is a title");
// we are going to add text by paragraphs. Clear the default placehoder text before that XSLFTextShape bodyPlaceholder = ph2[1];
bodyPlaceholder.clearText(); // we are going to add text by paragraphs. Clear the default placehoder text before that
XSLFTextParagraph p1 = bodyPlaceholder.addNewTextParagraph(); bodyPlaceholder.clearText();
p1.setIndentLevel(0); XSLFTextParagraph p1 = bodyPlaceholder.addNewTextParagraph();
p1.addNewTextRun().setText("Level1 text"); p1.setIndentLevel(0);
XSLFTextParagraph p2 = bodyPlaceholder.addNewTextParagraph(); p1.addNewTextRun().setText("Level1 text");
p2.setIndentLevel(1); XSLFTextParagraph p2 = bodyPlaceholder.addNewTextParagraph();
p2.addNewTextRun().setText("Level2 text"); p2.setIndentLevel(1);
XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph(); p2.addNewTextRun().setText("Level2 text");
p3.setIndentLevel(2); XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph();
p3.addNewTextRun().setText("Level3 text"); p3.setIndentLevel(2);
p3.addNewTextRun().setText("Level3 text");
FileOutputStream out = new FileOutputStream("slides.pptx");
ppt.write(out); FileOutputStream out = new FileOutputStream("slides.pptx");
out.close(); ppt.write(out);
out.close();
ppt.close(); } finally {
ppt.close();
}
} }
} }

View File

@ -26,60 +26,60 @@ import java.io.IOException;
/** /**
* Basic paragraph and text formatting * Basic paragraph and text formatting
*
* @author Yegor Kozlov
*/ */
public class Tutorial2 { public class Tutorial2 {
public static void main(String[] args) throws IOException{ public static void main(String[] args) throws IOException{
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide1 = ppt.createSlide(); try {
XSLFTextBox shape1 = slide1.createTextBox(); XSLFSlide slide1 = ppt.createSlide();
// initial height of the text box is 100 pt but XSLFTextBox shape1 = slide1.createTextBox();
Rectangle anchor = new Rectangle(10, 100, 300, 100); // initial height of the text box is 100 pt but
shape1.setAnchor(anchor); Rectangle anchor = new Rectangle(10, 100, 300, 100);
shape1.setAnchor(anchor);
XSLFTextParagraph p1 = shape1.addNewTextParagraph();
XSLFTextRun r1 = p1.addNewTextRun(); XSLFTextParagraph p1 = shape1.addNewTextParagraph();
r1.setText("Paragraph Formatting"); XSLFTextRun r1 = p1.addNewTextRun();
r1.setFontSize(24d); r1.setText("Paragraph Formatting");
r1.setFontColor(new Color(85, 142, 213)); r1.setFontSize(24d);
r1.setFontColor(new Color(85, 142, 213));
XSLFTextParagraph p2 = shape1.addNewTextParagraph();
// If spaceBefore >= 0, then space is a percentage of normal line height. XSLFTextParagraph p2 = shape1.addNewTextParagraph();
// If spaceBefore < 0, the absolute value of linespacing is the spacing in points // If spaceBefore >= 0, then space is a percentage of normal line height.
p2.setSpaceBefore(-20d); // 20 pt from the previous paragraph // If spaceBefore < 0, the absolute value of linespacing is the spacing in points
p2.setSpaceAfter(300d); // 3 lines after the paragraph p2.setSpaceBefore(-20d); // 20 pt from the previous paragraph
XSLFTextRun r2 = p2.addNewTextRun(); p2.setSpaceAfter(300d); // 3 lines after the paragraph
r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph."); XSLFTextRun r2 = p2.addNewTextRun();
r2.setFontSize(16d); r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph.");
r2.setFontSize(16d);
XSLFTextParagraph p3 = shape1.addNewTextParagraph();
XSLFTextParagraph p3 = shape1.addNewTextParagraph();
XSLFTextRun r3 = p3.addNewTextRun();
r3.setText("Run Formatting"); XSLFTextRun r3 = p3.addNewTextRun();
r3.setFontSize(24d); r3.setText("Run Formatting");
r3.setFontColor(new Color(85, 142, 213)); r3.setFontSize(24d);
r3.setFontColor(new Color(85, 142, 213));
XSLFTextParagraph p4 = shape1.addNewTextParagraph();
p4.setSpaceBefore(-20d); // 20 pt from the previous paragraph XSLFTextParagraph p4 = shape1.addNewTextParagraph();
p4.setSpaceAfter(300d); // 3 lines after the paragraph p4.setSpaceBefore(-20d); // 20 pt from the previous paragraph
XSLFTextRun r4 = p4.addNewTextRun(); p4.setSpaceAfter(300d); // 3 lines after the paragraph
r4.setFontSize(16d); XSLFTextRun r4 = p4.addNewTextRun();
r4.setText( r4.setFontSize(16d);
"Run level formatting is the most granular property level and allows " + r4.setText(
"for the specifying of all low level text properties. The text run is " + "Run level formatting is the most granular property level and allows " +
"what all paragraphs are derived from and thus specifying various " + "for the specifying of all low level text properties. The text run is " +
"properties per run will allow for a diversely formatted text paragraph."); "what all paragraphs are derived from and thus specifying various " +
"properties per run will allow for a diversely formatted text paragraph.");
// resize the shape to fit text
shape1.resizeToFitText(); // resize the shape to fit text
shape1.resizeToFitText();
FileOutputStream out = new FileOutputStream("text.pptx");
ppt.write(out); FileOutputStream out = new FileOutputStream("text.pptx");
out.close(); ppt.write(out);
out.close();
ppt.close(); } finally {
ppt.close();
}
} }
} }

View File

@ -27,25 +27,25 @@ import org.apache.poi.sl.usermodel.Placeholder;
/** /**
* How to set slide title * How to set slide title
*
* @author Yegor Kozlov
*/ */
public class Tutorial3 { public class Tutorial3 {
public static void main(String[] args) throws IOException{ public static void main(String[] args) throws IOException{
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide = ppt.createSlide(); try {
XSLFSlide slide = ppt.createSlide();
XSLFTextShape titleShape = slide.createTextBox();
titleShape.setPlaceholder(Placeholder.TITLE); XSLFTextShape titleShape = slide.createTextBox();
titleShape.setText("This is a slide title"); titleShape.setPlaceholder(Placeholder.TITLE);
titleShape.setAnchor(new Rectangle(50, 50, 400, 100)); titleShape.setText("This is a slide title");
titleShape.setAnchor(new Rectangle(50, 50, 400, 100));
FileOutputStream out = new FileOutputStream("title.pptx");
ppt.write(out); FileOutputStream out = new FileOutputStream("title.pptx");
out.close(); ppt.write(out);
out.close();
ppt.close(); } finally {
ppt.close();
}
} }
} }

View File

@ -29,66 +29,64 @@ import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;
/** /**
* PPTX Tables * PPTX Tables
*
* @author Yegor Kozlov
*/ */
public class Tutorial4 { public class Tutorial4 {
public static void main(String[] args) throws IOException{ public static void main(String[] args) throws IOException{
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
// XSLFSlide#createSlide() with no arguments creates a blank slide try {
XSLFSlide slide = ppt.createSlide(); // XSLFSlide#createSlide() with no arguments creates a blank slide
XSLFSlide slide = ppt.createSlide();
XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(50, 50, 450, 300)); XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
int numColumns = 3;
int numRows = 5; int numColumns = 3;
XSLFTableRow headerRow = tbl.addRow(); int numRows = 5;
headerRow.setHeight(50); XSLFTableRow headerRow = tbl.addRow();
// header headerRow.setHeight(50);
for(int i = 0; i < numColumns; i++) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
XSLFTextRun r = p.addNewTextRun();
r.setText("Header " + (i+1));
r.setBold(true);
r.setFontColor(Color.white);
th.setFillColor(new Color(79, 129, 189));
th.setBorderWidth(BorderEdge.bottom, 2.0);
th.setBorderColor(BorderEdge.bottom, Color.white);
tbl.setColumnWidth(i, 150); // all columns are equally sized
}
// rows
for(int rownum = 0; rownum < numRows; rownum ++){
XSLFTableRow tr = tbl.addRow();
tr.setHeight(50);
// header // header
for(int i = 0; i < numColumns; i++) { for(int i = 0; i < numColumns; i++) {
XSLFTableCell cell = tr.addCell(); XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = cell.addNewTextParagraph(); XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
XSLFTextRun r = p.addNewTextRun(); XSLFTextRun r = p.addNewTextRun();
r.setText("Header " + (i+1));
r.setText("Cell " + (i+1)); r.setBold(true);
if(rownum % 2 == 0) r.setFontColor(Color.white);
cell.setFillColor(new Color(208, 216, 232)); th.setFillColor(new Color(79, 129, 189));
else th.setBorderWidth(BorderEdge.bottom, 2.0);
cell.setFillColor(new Color(233, 247, 244)); th.setBorderColor(BorderEdge.bottom, Color.white);
tbl.setColumnWidth(i, 150); // all columns are equally sized
} }
// rows
for(int rownum = 0; rownum < numRows; rownum ++){
XSLFTableRow tr = tbl.addRow();
tr.setHeight(50);
// header
for(int i = 0; i < numColumns; i++) {
XSLFTableCell cell = tr.addCell();
XSLFTextParagraph p = cell.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Cell " + (i+1));
if(rownum % 2 == 0)
cell.setFillColor(new Color(208, 216, 232));
else
cell.setFillColor(new Color(233, 247, 244));
}
}
FileOutputStream out = new FileOutputStream("table.pptx");
ppt.write(out);
out.close();
} finally {
ppt.close();
} }
FileOutputStream out = new FileOutputStream("table.pptx");
ppt.write(out);
out.close();
ppt.close();
} }
} }

View File

@ -27,25 +27,25 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType;
/** /**
* Images * Images
*
* @author Yegor Kozlov
*/ */
public class Tutorial5 { public class Tutorial5 {
public static void main(String[] args) throws IOException{ public static void main(String[] args) throws IOException{
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide = ppt.createSlide(); try {
XSLFSlide slide = ppt.createSlide();
File img = new File(System.getProperty("POI.testdata.path", "test-data"), "slideshow/clock.jpg");
XSLFPictureData pictureData = ppt.addPicture(img, PictureType.PNG); File img = new File(System.getProperty("POI.testdata.path", "test-data"), "slideshow/clock.jpg");
XSLFPictureData pictureData = ppt.addPicture(img, PictureType.PNG);
/*XSLFPictureShape shape =*/ slide.createPicture(pictureData);
/*XSLFPictureShape shape =*/ slide.createPicture(pictureData);
FileOutputStream out = new FileOutputStream("images.pptx");
ppt.write(out); FileOutputStream out = new FileOutputStream("images.pptx");
out.close(); ppt.write(out);
out.close();
ppt.close(); } finally {
ppt.close();
}
} }
} }

View File

@ -25,37 +25,37 @@ import java.io.IOException;
/** /**
* Hyperlinks * Hyperlinks
*
* @author Yegor Kozlov
*/ */
public class Tutorial6 { public class Tutorial6 {
public static void main(String[] args) throws IOException{ public static void main(String[] args) throws IOException{
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide1 = ppt.createSlide(); try {
XSLFSlide slide2 = ppt.createSlide(); XSLFSlide slide1 = ppt.createSlide();
XSLFSlide slide2 = ppt.createSlide();
XSLFTextBox shape1 = slide1.createTextBox();
shape1.setAnchor(new Rectangle(50, 50, 200, 50)); XSLFTextBox shape1 = slide1.createTextBox();
XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun(); shape1.setAnchor(new Rectangle(50, 50, 200, 50));
XSLFHyperlink link1 = r1.createHyperlink(); XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun();
r1.setText("http://poi.apache.org"); // visible text XSLFHyperlink link1 = r1.createHyperlink();
link1.setAddress("http://poi.apache.org"); // link address r1.setText("http://poi.apache.org"); // visible text
link1.setAddress("http://poi.apache.org"); // link address
XSLFTextBox shape2 = slide1.createTextBox();
shape2.setAnchor(new Rectangle(300, 50, 200, 50)); XSLFTextBox shape2 = slide1.createTextBox();
XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun(); shape2.setAnchor(new Rectangle(300, 50, 200, 50));
XSLFHyperlink link2 = r2.createHyperlink(); XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun();
r2.setText("Go to the second slide"); // visible text XSLFHyperlink link2 = r2.createHyperlink();
link2.linkToSlide(slide2); // link address r2.setText("Go to the second slide"); // visible text
link2.linkToSlide(slide2); // link address
FileOutputStream out = new FileOutputStream("hyperlinks.pptx");
ppt.write(out); FileOutputStream out = new FileOutputStream("hyperlinks.pptx");
out.close(); ppt.write(out);
out.close();
ppt.close(); } finally {
ppt.close();
}
} }
} }

View File

@ -28,63 +28,63 @@ import org.apache.poi.sl.usermodel.AutoNumberingScheme;
/** /**
* Bullets and numbering * Bullets and numbering
*
* @author Yegor Kozlov
*/ */
public class Tutorial7 { public class Tutorial7 {
public static void main(String[] args) throws IOException{ public static void main(String[] args) throws IOException {
XMLSlideShow ppt = new XMLSlideShow(); XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide = ppt.createSlide(); try {
XSLFTextBox shape = slide.createTextBox(); XSLFSlide slide = ppt.createSlide();
shape.setAnchor(new Rectangle(50, 50, 400, 200)); XSLFTextBox shape = slide.createTextBox();
shape.setAnchor(new Rectangle(50, 50, 400, 200));
XSLFTextParagraph p1 = shape.addNewTextParagraph();
p1.setIndentLevel(0); XSLFTextParagraph p1 = shape.addNewTextParagraph();
p1.setBullet(true); p1.setIndentLevel(0);
XSLFTextRun r1 = p1.addNewTextRun(); p1.setBullet(true);
r1.setText("Bullet1"); XSLFTextRun r1 = p1.addNewTextRun();
r1.setText("Bullet1");
XSLFTextParagraph p2 = shape.addNewTextParagraph();
// indentation before text XSLFTextParagraph p2 = shape.addNewTextParagraph();
p2.setLeftMargin(60d); // indentation before text
// the bullet is set 40 pt before the text p2.setLeftMargin(60d);
p2.setIndent(-40d); // the bullet is set 40 pt before the text
p2.setBullet(true); p2.setIndent(-40d);
// customize bullets p2.setBullet(true);
p2.setBulletFontColor(Color.red); // customize bullets
p2.setBulletFont("Wingdings"); p2.setBulletFontColor(Color.red);
p2.setBulletCharacter("\u0075"); p2.setBulletFont("Wingdings");
p2.setIndentLevel(1); p2.setBulletCharacter("\u0075");
XSLFTextRun r2 = p2.addNewTextRun(); p2.setIndentLevel(1);
r2.setText("Bullet2"); XSLFTextRun r2 = p2.addNewTextRun();
r2.setText("Bullet2");
// the next three paragraphs form an auto-numbered list
XSLFTextParagraph p3 = shape.addNewTextParagraph(); // the next three paragraphs form an auto-numbered list
p3.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1); XSLFTextParagraph p3 = shape.addNewTextParagraph();
p3.setIndentLevel(2); p3.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
XSLFTextRun r3 = p3.addNewTextRun(); p3.setIndentLevel(2);
r3.setText("Numbered List Item - 1"); XSLFTextRun r3 = p3.addNewTextRun();
r3.setText("Numbered List Item - 1");
XSLFTextParagraph p4 = shape.addNewTextParagraph();
p4.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 2); XSLFTextParagraph p4 = shape.addNewTextParagraph();
p4.setIndentLevel(2); p4.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 2);
XSLFTextRun r4 = p4.addNewTextRun(); p4.setIndentLevel(2);
r4.setText("Numbered List Item - 2"); XSLFTextRun r4 = p4.addNewTextRun();
r4.setText("Numbered List Item - 2");
XSLFTextParagraph p5 = shape.addNewTextParagraph();
p5.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 3); XSLFTextParagraph p5 = shape.addNewTextParagraph();
p5.setIndentLevel(2); p5.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 3);
XSLFTextRun r5 = p5.addNewTextRun(); p5.setIndentLevel(2);
r5.setText("Numbered List Item - 3"); XSLFTextRun r5 = p5.addNewTextRun();
r5.setText("Numbered List Item - 3");
shape.resizeToFitText();
shape.resizeToFitText();
FileOutputStream out = new FileOutputStream("list.pptx");
ppt.write(out); FileOutputStream out = new FileOutputStream("list.pptx");
out.close(); ppt.write(out);
out.close();
ppt.close(); } finally {
ppt.close();
}
} }
} }

View File

@ -164,12 +164,15 @@ public class EmbeddedExtractor implements Iterable<EmbeddedExtractor> {
protected EmbeddedData extract(DirectoryNode dn) throws IOException { protected EmbeddedData extract(DirectoryNode dn) throws IOException {
assert(canExtract(dn)); assert(canExtract(dn));
POIFSFileSystem dest = new POIFSFileSystem();
copyNodes(dn, dest.getRoot());
// start with a reasonable big size
ByteArrayOutputStream bos = new ByteArrayOutputStream(20000); ByteArrayOutputStream bos = new ByteArrayOutputStream(20000);
dest.writeFilesystem(bos); POIFSFileSystem dest = new POIFSFileSystem();
dest.close(); try {
copyNodes(dn, dest.getRoot());
// start with a reasonable big size
dest.writeFilesystem(bos);
} finally {
dest.close();
}
return new EmbeddedData(dn.getName(), bos.toByteArray(), CONTENT_TYPE_BYTES); return new EmbeddedData(dn.getName(), bos.toByteArray(), CONTENT_TYPE_BYTES);
} }

View File

@ -110,13 +110,15 @@ public class ExcelToFoConverter extends AbstractExcelConverter
public static Document process( File xlsFile ) throws Exception public static Document process( File xlsFile ) throws Exception
{ {
final HSSFWorkbook workbook = ExcelToFoUtils.loadXls( xlsFile ); final HSSFWorkbook workbook = ExcelToFoUtils.loadXls( xlsFile );
ExcelToFoConverter excelToHtmlConverter = new ExcelToFoConverter( try {
XMLHelper.getDocumentBuilderFactory().newDocumentBuilder() ExcelToFoConverter excelToHtmlConverter = new ExcelToFoConverter(
.newDocument() ); XMLHelper.getDocumentBuilderFactory().newDocumentBuilder()
excelToHtmlConverter.processWorkbook( workbook ); .newDocument() );
Document doc = excelToHtmlConverter.getDocument(); excelToHtmlConverter.processWorkbook( workbook );
workbook.close(); return excelToHtmlConverter.getDocument();
return doc; } finally {
workbook.close();
}
} }
private final FoDocumentFacade foDocumentFacade; private final FoDocumentFacade foDocumentFacade;