Adjust many examples for Java 8: try-with-resource, multi-catch and other code cleanup.

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1809354 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Dominik Stadler 2017-09-22 21:16:09 +00:00
parent 4ac6800974
commit ad5232f8f8
98 changed files with 2062 additions and 2326 deletions

View File

@ -69,7 +69,7 @@ public class OOXMLPasswordsTry implements Closeable {
// Try each password in turn, reporting progress
String valid = null;
String password = null;
String password;
while ((password = r.readLine()) != null) {
if (isValid(password)) {
valid = password;

View File

@ -123,9 +123,9 @@ public class CopyCompare
final CopyFile cf = new CopyFile(copyFileName);
r.registerListener(cf);
r.setNotifyEmptyDirectories(true);
FileInputStream fis = new FileInputStream(originalFileName);
r.read(fis);
fis.close();
try (FileInputStream fis = new FileInputStream(originalFileName)) {
r.read(fis);
}
/* Write the new POIFS to disk. */
cf.close();
@ -183,7 +183,7 @@ public class CopyCompare
for (final Entry e1 : d1) {
final String n1 = e1.getName();
if (!d2.hasEntry(n1)) {
msg.append("Document \"" + n1 + "\" exists only in the source.\n");
msg.append("Document \"").append(n1).append("\" exists only in the source.\n");
equal = false;
break;
}
@ -194,8 +194,7 @@ public class CopyCompare
} else if (e1.isDocumentEntry() && e2.isDocumentEntry()) {
equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg);
} else {
msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " +
"document while the other one is a directory.\n");
msg.append("One of \"").append(e1).append("\" and \"").append(e2).append("\" is a ").append("document while the other one is a directory.\n");
equal = false;
}
}
@ -208,8 +207,7 @@ public class CopyCompare
try {
e1 = d1.getEntry(n2);
} catch (FileNotFoundException ex) {
msg.append("Document \"" + e2 + "\" exitsts, document \"" +
e1 + "\" does not.\n");
msg.append("Document \"").append(e2).append("\" exitsts, document \"").append(e1).append("\" does not.\n");
equal = false;
break;
}
@ -243,11 +241,9 @@ public class CopyCompare
throws NoPropertySetStreamException, MarkUnsupportedException,
UnsupportedEncodingException, IOException
{
final DocumentInputStream dis1 = new DocumentInputStream(d1);
final DocumentInputStream dis2 = new DocumentInputStream(d2);
try {
try (DocumentInputStream dis1 = new DocumentInputStream(d1); DocumentInputStream dis2 = new DocumentInputStream(d2)) {
if (PropertySet.isPropertySetStream(dis1) &&
PropertySet.isPropertySetStream(dis2)) {
PropertySet.isPropertySetStream(dis2)) {
final PropertySet ps1 = PropertySetFactory.create(dis1);
final PropertySet ps2 = PropertySetFactory.create(dis2);
if (!ps1.equals(ps2)) {
@ -265,9 +261,6 @@ public class CopyCompare
}
} while (i1 > -1);
}
} finally {
dis2.close();
dis1.close();
}
return true;
}
@ -339,11 +332,7 @@ public class CopyCompare
* copy it unmodified to the destination POIFS. */
copy(poiFs, path, name, stream);
}
} catch (MarkUnsupportedException ex) {
t = ex;
} catch (IOException ex) {
t = ex;
} catch (WritingNotSupportedException ex) {
} catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) {
t = ex;
}

View File

@ -57,7 +57,7 @@ public class ReadTitle
@Override
public void processPOIFSReaderEvent(final POIFSReaderEvent event)
{
SummaryInformation si = null;
SummaryInformation si;
try
{
si = (SummaryInformation)

View File

@ -187,11 +187,7 @@ public class WriteAuthorAndTitle
* copy it unmodified to the destination POIFS. */
copy(poiFs, event.getPath(), event.getName(), stream);
}
} catch (MarkUnsupportedException ex) {
t = ex;
} catch (IOException ex) {
t = ex;
} catch (WritingNotSupportedException ex) {
} catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) {
t = ex;
}

View File

@ -79,23 +79,21 @@ public class WriteTitle
ms.setProperty(p);
/* Create the POI file system the property set is to be written to. */
final POIFSFileSystem poiFs = new POIFSFileSystem();
try (final POIFSFileSystem poiFs = new POIFSFileSystem()) {
/* For writing the property set into a POI file system it has to be
* handed over to the POIFS.createDocument() method as an input stream
* which produces the bytes making out the property set stream. */
final InputStream is = mps.toInputStream();
/* For writing the property set into a POI file system it has to be
* handed over to the POIFS.createDocument() method as an input stream
* which produces the bytes making out the property set stream. */
final InputStream is = mps.toInputStream();
/* Create the summary information property set in the POI file
* system. It is given the default name most (if not all) summary
* information property sets have. */
poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);
/* Create the summary information property set in the POI file
* system. It is given the default name most (if not all) summary
* information property sets have. */
poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);
/* Write the whole POI file system to a disk file. */
FileOutputStream fos = new FileOutputStream(fileName);
poiFs.writeFilesystem(fos);
fos.close();
poiFs.close();
/* Write the whole POI file system to a disk file. */
try (FileOutputStream fos = new FileOutputStream(fileName)) {
poiFs.writeFilesystem(fos);
}
}
}
}

View File

@ -51,28 +51,28 @@ import org.apache.poi.sl.usermodel.VerticalAlignment;
public final class ApacheconEU08 {
public static void main(String[] args) throws IOException {
SlideShow<?,?> ppt = new HSLFSlideShow();
// SlideShow<?,?> ppt = new XMLSlideShow();
ppt.setPageSize(new Dimension(720, 540));
try (SlideShow<?,?> ppt = new HSLFSlideShow()) {
// SlideShow<?,?> ppt = new XMLSlideShow();
ppt.setPageSize(new Dimension(720, 540));
slide1(ppt);
slide2(ppt);
slide3(ppt);
slide4(ppt);
slide5(ppt);
slide6(ppt);
slide7(ppt);
slide8(ppt);
slide9(ppt);
slide10(ppt);
slide11(ppt);
slide12(ppt);
slide1(ppt);
slide2(ppt);
slide3(ppt);
slide4(ppt);
slide5(ppt);
slide6(ppt);
slide7(ppt);
slide8(ppt);
slide9(ppt);
slide10(ppt);
slide11(ppt);
slide12(ppt);
String ext = ppt.getClass().getName().contains("HSLF") ? "ppt" : "pptx";
FileOutputStream out = new FileOutputStream("apachecon_eu_08."+ext);
ppt.write(out);
out.close();
ppt.close();
String ext = ppt.getClass().getName().contains("HSLF") ? "ppt" : "pptx";
try (FileOutputStream out = new FileOutputStream("apachecon_eu_08." + ext)) {
ppt.write(out);
}
}
}
public static void slide1(SlideShow<?,?> ppt) throws IOException {

View File

@ -32,11 +32,9 @@ import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
public final class BulletsDemo {
public static void main(String[] args) throws IOException {
HSLFSlideShow ppt = new HSLFSlideShow();
try {
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
HSLFSlide slide = ppt.createSlide();
HSLFTextBox shape = new HSLFTextBox();
HSLFTextParagraph rt = shape.getTextParagraphs().get(0);
rt.getTextRuns().get(0).setFontSize(42d);
@ -46,19 +44,17 @@ public final class BulletsDemo {
rt.setBulletChar('\u263A'); //bullet character
shape.setText(
"January\r" +
"February\r" +
"March\r" +
"April");
"February\r" +
"March\r" +
"April");
slide.addShape(shape);
shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide
slide.addShape(shape);
FileOutputStream out = new FileOutputStream("bullets.ppt");
ppt.write(out);
out.close();
} finally {
ppt.close();
try (FileOutputStream out = new FileOutputStream("bullets.ppt")) {
ppt.write(out);
}
}
}
}

View File

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

View File

@ -52,10 +52,10 @@ public final class DataExtraction {
//extract all sound files embedded in this presentation
HSLFSoundData[] sound = ppt.getSoundData();
for (int i = 0; i < sound.length; i++) {
String type = sound[i].getSoundType(); //*.wav
String name = sound[i].getSoundName(); //typically file name
byte[] data = sound[i].getData(); //raw bytes
for (HSLFSoundData aSound : sound) {
String type = aSound.getSoundType(); //*.wav
String name = aSound.getSoundName(); //typically file name
byte[] data = aSound.getData(); //raw bytes
//save the sound on disk
FileOutputStream out = new FileOutputStream(name + type);

View File

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

View File

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

View File

@ -37,8 +37,8 @@ import org.apache.poi.hslf.usermodel.HSLFTextRun;
public final class Hyperlinks {
public static void main(String[] args) throws Exception {
for (int i = 0; i < args.length; i++) {
FileInputStream is = new FileInputStream(args[i]);
for (String arg : args) {
FileInputStream is = new FileInputStream(arg);
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
@ -64,7 +64,7 @@ public final class Hyperlinks {
System.out.println("- reading hyperlinks from the slide's shapes");
for (HSLFShape sh : slide.getShapes()) {
if (sh instanceof HSLFSimpleShape) {
HSLFHyperlink link = ((HSLFSimpleShape)sh).getHyperlink();
HSLFHyperlink link = ((HSLFSimpleShape) sh).getHyperlink();
if (link != null) {
System.out.println(toStr(link, null));
}

View File

@ -30,23 +30,23 @@ import org.apache.poi.hslf.usermodel.HSLFSoundData;
*/
public class SoundFinder {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(args[0]);
HSLFSlideShow ppt = new HSLFSlideShow(fis);
HSLFSoundData[] sounds = ppt.getSoundData();
try (FileInputStream fis = new FileInputStream(args[0])) {
try (HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
HSLFSoundData[] sounds = ppt.getSoundData();
for (HSLFSlide slide : ppt.getSlides()) {
for (HSLFShape shape : slide.getShapes()) {
int soundRef = getSoundReference(shape);
if(soundRef == -1) continue;
for (HSLFSlide slide : ppt.getSlides()) {
for (HSLFShape shape : slide.getShapes()) {
int soundRef = getSoundReference(shape);
if (soundRef == -1) continue;
System.out.println("Slide["+slide.getSlideNumber()+"], shape["+shape.getShapeId()+"], soundRef: "+soundRef);
System.out.println(" " + sounds[soundRef].getSoundName());
System.out.println(" " + sounds[soundRef].getSoundType());
System.out.println("Slide[" + slide.getSlideNumber() + "], shape[" + shape.getShapeId() + "], soundRef: " + soundRef);
System.out.println(" " + sounds[soundRef].getSoundName());
System.out.println(" " + sounds[soundRef].getSoundType());
}
}
}
}
ppt.close();
fis.close();
}
/**

View File

@ -54,18 +54,14 @@ public final class TableDemo {
public static void main(String[] args) throws Exception {
HSLFSlideShow ppt = new HSLFSlideShow();
try {
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
HSLFSlide slide = ppt.createSlide();
create1stTable(slide);
create2ndTable(slide);
FileOutputStream out = new FileOutputStream("hslf-table.ppt");
ppt.write(out);
out.close();
} finally {
ppt.close();
try (FileOutputStream out = new FileOutputStream("hslf-table.ppt")) {
ppt.write(out);
}
}
}

View File

@ -157,12 +157,12 @@ public class Msg2txt {
if(args.length <= 0) {
System.err.println("No files names provided");
} else {
for(int i = 0; i < args.length; i++) {
for (String arg : args) {
try {
Msg2txt processor = new Msg2txt(args[i]);
Msg2txt processor = new Msg2txt(arg);
processor.processMessage();
} catch (IOException e) {
System.err.println("Could not process "+args[i]+": "+e);
System.err.println("Could not process " + arg + ": " + e);
}
}
}

View File

@ -251,10 +251,10 @@ public class AddDimensionedImage {
String imageFile, double reqImageWidthMM, double reqImageHeightMM,
int resizeBehaviour) throws FileNotFoundException, IOException,
IllegalArgumentException {
HSSFClientAnchor anchor = null;
HSSFPatriarch patriarch = null;
ClientAnchorDetail rowClientAnchorDetail = null;
ClientAnchorDetail colClientAnchorDetail = null;
HSSFClientAnchor anchor;
HSSFPatriarch patriarch;
ClientAnchorDetail rowClientAnchorDetail;
ClientAnchorDetail colClientAnchorDetail;
// Validate the resizeBehaviour parameter.
if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&
@ -334,9 +334,9 @@ public class AddDimensionedImage {
private ClientAnchorDetail fitImageToColumns(HSSFSheet sheet, int colNumber,
double reqImageWidthMM, int resizeBehaviour) {
double colWidthMM = 0.0D;
double colCoordinatesPerMM = 0.0D;
int pictureWidthCoordinates = 0;
double colWidthMM;
double colCoordinatesPerMM;
int pictureWidthCoordinates;
ClientAnchorDetail colClientAnchorDetail = null;
// Get the colum's width in millimetres
@ -417,21 +417,19 @@ public class AddDimensionedImage {
*/
private ClientAnchorDetail fitImageToRows(HSSFSheet sheet, int rowNumber,
double reqImageHeightMM, int resizeBehaviour) {
HSSFRow row = null;
double rowHeightMM = 0.0D;
double rowCoordinatesPerMM = 0.0D;
int pictureHeightCoordinates = 0;
double rowCoordinatesPerMM;
int pictureHeightCoordinates;
ClientAnchorDetail rowClientAnchorDetail = null;
// Get the row and it's height
row = sheet.getRow(rowNumber);
HSSFRow row = sheet.getRow(rowNumber);
if(row == null) {
// Create row if it does not exist.
row = sheet.createRow(rowNumber);
}
// Get the row's height in millimetres
rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE;
double rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE;
// Check that the row's height will accomodate the image at the required
// dimensions. If the height of the row is LESS than the required height
@ -494,13 +492,13 @@ public class AddDimensionedImage {
private ClientAnchorDetail calculateColumnLocation(HSSFSheet sheet,
int startingColumn,
double reqImageWidthMM) {
ClientAnchorDetail anchorDetail = null;
ClientAnchorDetail anchorDetail;
double totalWidthMM = 0.0D;
double colWidthMM = 0.0D;
double overlapMM = 0.0D;
double coordinatePositionsPerMM = 0.0D;
double overlapMM;
double coordinatePositionsPerMM;
int toColumn = startingColumn;
int inset = 0;
int inset;
// Calculate how many columns the image will have to
// span in order to be presented at the required size.
@ -593,14 +591,14 @@ public class AddDimensionedImage {
*/
private ClientAnchorDetail calculateRowLocation(HSSFSheet sheet,
int startingRow, double reqImageHeightMM) {
ClientAnchorDetail clientAnchorDetail = null;
HSSFRow row = null;
ClientAnchorDetail clientAnchorDetail;
HSSFRow row;
double rowHeightMM = 0.0D;
double totalRowHeightMM = 0.0D;
double overlapMM = 0.0D;
double rowCoordinatesPerMM = 0.0D;
double overlapMM;
double rowCoordinatesPerMM;
int toRow = startingRow;
int inset = 0;
int inset;
// Step through the rows in the sheet and accumulate a total of their
// heights.
@ -672,10 +670,10 @@ public class AddDimensionedImage {
* interrupted.
*/
private byte[] imageToBytes(String imageFilename) throws IOException {
File imageFile = null;
File imageFile;
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
int read = 0;
ByteArrayOutputStream bos;
int read;
try {
imageFile = new File(imageFilename);
fis = new FileInputStream(imageFile);
@ -718,10 +716,10 @@ public class AddDimensionedImage {
* @param args the command line arguments
*/
public static void main(String[] args) {
String imageFile = null;
String outputFile = null;
String imageFile;
String outputFile;
FileOutputStream fos = null;
HSSFSheet sheet = null;
HSSFSheet sheet;
try {
if(args.length < 2){
System.err.println("Usage: AddDimensionedImage imageFile outputFile");
@ -730,25 +728,15 @@ public class AddDimensionedImage {
imageFile = args[0];
outputFile = args[1];
HSSFWorkbook workbook = new HSSFWorkbook();
try {
try (HSSFWorkbook workbook = new HSSFWorkbook()) {
sheet = workbook.createSheet("Picture Test");
new AddDimensionedImage().addImageToSheet("A1", sheet,
imageFile, 125, 125,
AddDimensionedImage.EXPAND_ROW_AND_COLUMN);
fos = new FileOutputStream(outputFile);
workbook.write(fos);
} finally {
workbook.close();
}
}
catch(FileNotFoundException fnfEx) {
System.out.println("Caught an: " + fnfEx.getClass().getName());
System.out.println("Message: " + fnfEx.getMessage());
System.out.println("Stacktrace follows...........");
fnfEx.printStackTrace(System.out);
}
catch(IOException ioEx) {
} catch(IOException ioEx) {
System.out.println("Caught an: " + ioEx.getClass().getName());
System.out.println("Message: " + ioEx.getMessage());
System.out.println("Stacktrace follows...........");

View File

@ -36,23 +36,22 @@ import org.apache.poi.ss.usermodel.HorizontalAlignment;
*/
public class Alignment {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow(2);
createCell(wb, row, 0, HorizontalAlignment.CENTER);
createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION);
createCell(wb, row, 2, HorizontalAlignment.FILL);
createCell(wb, row, 3, HorizontalAlignment.GENERAL);
createCell(wb, row, 4, HorizontalAlignment.JUSTIFY);
createCell(wb, row, 5, HorizontalAlignment.LEFT);
createCell(wb, row, 6, HorizontalAlignment.RIGHT);
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow(2);
createCell(wb, row, 0, HorizontalAlignment.CENTER);
createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION);
createCell(wb, row, 2, HorizontalAlignment.FILL);
createCell(wb, row, 3, HorizontalAlignment.GENERAL);
createCell(wb, row, 4, HorizontalAlignment.JUSTIFY);
createCell(wb, row, 5, HorizontalAlignment.LEFT);
createCell(wb, row, 6, HorizontalAlignment.RIGHT);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
/**

View File

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

View File

@ -33,8 +33,7 @@ import org.apache.poi.ss.usermodel.BorderStyle;
*/
public class Borders {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
try {
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
@ -57,11 +56,9 @@ public class Borders {
cell.setCellStyle(style);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
} finally {
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

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

View File

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

View File

@ -32,25 +32,24 @@ import java.io.IOException;
*/
public class CreateCells {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(0);
// Create a cell and put a value in it.
HSSFCell cell = row.createCell(0);
cell.setCellValue(1);
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(0);
// Create a cell and put a value in it.
HSSFCell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue("This is a string");
row.createCell(3).setCellValue(true);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue("This is a string");
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -35,29 +35,28 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
*/
public class CreateDateCells {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(0);
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(0);
// Create a cell and put a date value in it. The first cell is not styled as a date.
HSSFCell cell = row.createCell(0);
cell.setCellValue(new Date());
// Create a cell and put a date value in it. The first cell is not styled as a date.
HSSFCell cell = row.createCell(0);
cell.setCellValue(new Date());
// we style the second cell as a date (and time). It is important to create a new cell style from the workbook
// otherwise you can end up modifying the built in style and effecting not only this cell but other cells.
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
// we style the second cell as a date (and time). It is important to create a new cell style from the workbook
// otherwise you can end up modifying the built in style and effecting not only this cell but other cells.
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -34,34 +34,34 @@ public class EmbeddedObjects {
@SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));
HSSFWorkbook workbook = new HSSFWorkbook(fs);
for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
//the OLE2 Class Name of the object
String oleName = obj.getOLE2ClassName();
DirectoryNode dn = (obj.hasDirectoryEntry()) ? (DirectoryNode) obj.getDirectory() : null;
Closeable document = null;
if (oleName.equals("Worksheet")) {
document = new HSSFWorkbook(dn, fs, false);
} else if (oleName.equals("Document")) {
document = new HWPFDocument(dn);
} else if (oleName.equals("Presentation")) {
document = new HSLFSlideShow(dn);
} else {
if(dn != null){
// The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
for (Entry entry : dn) {
String name = entry.getName();
}
try (HSSFWorkbook workbook = new HSSFWorkbook(fs)) {
for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
//the OLE2 Class Name of the object
String oleName = obj.getOLE2ClassName();
DirectoryNode dn = (obj.hasDirectoryEntry()) ? (DirectoryNode) obj.getDirectory() : null;
Closeable document = null;
if (oleName.equals("Worksheet")) {
document = new HSSFWorkbook(dn, fs, false);
} else if (oleName.equals("Document")) {
document = new HWPFDocument(dn);
} else if (oleName.equals("Presentation")) {
document = new HSLFSlideShow(dn);
} else {
// There is no DirectoryEntry
// Recover the object's data from the HSSFObjectData instance.
byte[] objectData = obj.getObjectData();
if (dn != null) {
// The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
for (Entry entry : dn) {
String name = entry.getName();
}
} else {
// There is no DirectoryEntry
// Recover the object's data from the HSSFObjectData instance.
byte[] objectData = obj.getObjectData();
}
}
if (document != null) {
document.close();
}
}
if (document != null) {
document.close();
}
}
workbook.close();
}
}

View File

@ -31,9 +31,7 @@ import java.io.InputStream;
/**
* This example shows how to use the event API for reading a file.
*/
public class EventExample
implements HSSFListener
{
public class EventExample implements HSSFListener {
private SSTRecord sstrec;
/**
@ -97,24 +95,22 @@ public class EventExample
{
// create a new file input stream with the input file specified
// at the command line
FileInputStream fin = new FileInputStream(args[0]);
// create a new org.apache.poi.poifs.filesystem.Filesystem
POIFSFileSystem poifs = new POIFSFileSystem(fin);
// get the Workbook (excel part) stream in a InputStream
InputStream din = poifs.createDocumentInputStream("Workbook");
// construct out HSSFRequest object
HSSFRequest req = new HSSFRequest();
// lazy listen for ALL records with the listener shown above
req.addListenerForAllRecords(new EventExample());
// create our event factory
HSSFEventFactory factory = new HSSFEventFactory();
// process our events based on the document input stream
factory.processEvents(req, din);
// once all the events are processed close our file input stream
fin.close();
// and our document input stream (don't want to leak these!)
din.close();
poifs.close();
try (FileInputStream fin = new FileInputStream(args[0])) {
// create a new org.apache.poi.poifs.filesystem.Filesystem
try (POIFSFileSystem poifs = new POIFSFileSystem(fin)) {
// get the Workbook (excel part) stream in a InputStream
try (InputStream din = poifs.createDocumentInputStream("Workbook")) {
// construct out HSSFRequest object
HSSFRequest req = new HSSFRequest();
// lazy listen for ALL records with the listener shown above
req.addListenerForAllRecords(new EventExample());
// create our event factory
HSSFEventFactory factory = new HSSFEventFactory();
// process our events based on the document input stream
factory.processEvents(req, din);
}
}
}
System.out.println("done.");
}
}

View File

@ -33,33 +33,32 @@ import org.apache.poi.ss.usermodel.FillPatternType;
*/
public class FrillsAndFills {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(1);
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(1);
// Aqua background
HSSFCellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(HSSFColorPredefined.AQUA.getIndex());
style.setFillPattern(FillPatternType.BIG_SPOTS);
HSSFCell cell = row.createCell(1);
cell.setCellValue("X");
cell.setCellStyle(style);
// Aqua background
HSSFCellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(HSSFColorPredefined.AQUA.getIndex());
style.setFillPattern(FillPatternType.BIG_SPOTS);
HSSFCell cell = row.createCell(1);
cell.setCellValue("X");
cell.setCellStyle(style);
// Orange "foreground", foreground being the fill foreground not the font color.
style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColorPredefined.ORANGE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell = row.createCell(2);
cell.setCellValue("X");
cell.setCellStyle(style);
// Orange "foreground", foreground being the fill foreground not the font color.
style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColorPredefined.ORANGE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell = row.createCell(2);
cell.setCellValue("X");
cell.setCellStyle(style);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -47,12 +47,9 @@ public final class HSSFReadWrite {
* creates an {@link HSSFWorkbook} with the specified OS filename.
*/
private static HSSFWorkbook readFile(String filename) throws IOException {
FileInputStream fis = new FileInputStream(filename);
try {
return new HSSFWorkbook(fis); // NOSONAR - should not be closed here
} finally {
fis.close();
}
try (FileInputStream fis = new FileInputStream(filename)) {
return new HSSFWorkbook(fis); // NOSONAR - should not be closed here
}
}
/**
@ -60,8 +57,7 @@ public final class HSSFReadWrite {
* rows/cells.
*/
private static void testCreateSampleSheet(String outputFilename) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
try {
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet s = wb.createSheet();
HSSFCellStyle cs = wb.createCellStyle();
HSSFCellStyle cs2 = wb.createCellStyle();
@ -125,14 +121,9 @@ public final class HSSFReadWrite {
wb.removeSheetAt(1);
// end deleted sheet
FileOutputStream out = new FileOutputStream(outputFilename);
try {
try (FileOutputStream out = new FileOutputStream(outputFilename)) {
wb.write(out);
} finally {
out.close();
}
} finally {
wb.close();
}
}
@ -166,9 +157,7 @@ public final class HSSFReadWrite {
try {
if (args.length < 2) {
HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
try {
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
System.out.println("Data dump:\n");
for (int k = 0; k < wb.getNumberOfSheets(); k++) {
@ -187,7 +176,7 @@ public final class HSSFReadWrite {
HSSFCell cell = row.getCell(c);
String value;
if(cell != null) {
if (cell != null) {
switch (cell.getCellType()) {
case FORMULA:
@ -223,8 +212,6 @@ public final class HSSFReadWrite {
}
}
}
} finally {
wb.close();
}
} else if (args.length == 2) {
if (args[1].toLowerCase(Locale.ROOT).equals("write")) {
@ -236,23 +223,16 @@ public final class HSSFReadWrite {
+ " ms generation time");
} else {
System.out.println("readwrite test");
HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
try {
FileOutputStream stream = new FileOutputStream(args[1]);
try {
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
try (FileOutputStream stream = new FileOutputStream(args[1])) {
wb.write(stream);
} finally {
stream.close();
}
} finally {
wb.close();
}
}
} else if (args.length == 3 && args[2].equalsIgnoreCase("modify1")) {
// delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"
HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
try {
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
HSSFSheet sheet = wb.getSheetAt(0);
for (int k = 0; k < 25; k++) {
@ -269,14 +249,9 @@ public final class HSSFReadWrite {
HSSFCell cell = row.getCell(3);
cell.setCellValue("MODIFIED CELL!!!!!");
FileOutputStream stream = new FileOutputStream(args[1]);
try {
try (FileOutputStream stream = new FileOutputStream(args[1])) {
wb.write(stream);
} finally {
stream.close();
}
} finally {
wb.close();
}
}
} catch (Exception e) {

View File

@ -31,17 +31,17 @@ import org.apache.poi.ss.usermodel.CellType;
*/
public class HyperlinkFormula {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow(0);
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellType(CellType.FORMULA);
cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")");
HSSFCell cell = row.createCell(0);
cell.setCellType(CellType.FORMULA);
cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")");
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -37,61 +37,61 @@ import org.apache.poi.ss.usermodel.Font;
public class Hyperlinks {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFCreationHelper helper = wb.getCreationHelper();
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFCreationHelper helper = wb.getCreationHelper();
//cell style for hyperlinks
//by default hyperlinks are blue and underlined
HSSFCellStyle hlink_style = wb.createCellStyle();
HSSFFont hlink_font = wb.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(HSSFColorPredefined.BLUE.getIndex());
hlink_style.setFont(hlink_font);
//cell style for hyperlinks
//by default hyperlinks are blue and underlined
HSSFCellStyle hlink_style = wb.createCellStyle();
HSSFFont hlink_font = wb.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(HSSFColorPredefined.BLUE.getIndex());
hlink_style.setFont(hlink_font);
HSSFCell cell;
HSSFSheet sheet = wb.createSheet("Hyperlinks");
HSSFCell cell;
HSSFSheet sheet = wb.createSheet("Hyperlinks");
//URL
cell = sheet.createRow(0).createCell(0);
cell.setCellValue("URL Link");
HSSFHyperlink link = helper.createHyperlink(HyperlinkType.URL);
link.setAddress("http://poi.apache.org/");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//URL
cell = sheet.createRow(0).createCell(0);
cell.setCellValue("URL Link");
HSSFHyperlink link = helper.createHyperlink(HyperlinkType.URL);
link.setAddress("http://poi.apache.org/");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//link to a file in the current directory
cell = sheet.createRow(1).createCell(0);
cell.setCellValue("File Link");
link = helper.createHyperlink(HyperlinkType.FILE);
link.setAddress("link1.xls");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//link to a file in the current directory
cell = sheet.createRow(1).createCell(0);
cell.setCellValue("File Link");
link = helper.createHyperlink(HyperlinkType.FILE);
link.setAddress("link1.xls");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//e-mail link
cell = sheet.createRow(2).createCell(0);
cell.setCellValue("Email Link");
link = helper.createHyperlink(HyperlinkType.EMAIL);
//note, if subject contains white spaces, make sure they are url-encoded
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//e-mail link
cell = sheet.createRow(2).createCell(0);
cell.setCellValue("Email Link");
link = helper.createHyperlink(HyperlinkType.EMAIL);
//note, if subject contains white spaces, make sure they are url-encoded
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//link to a place in this workbook
//link to a place in this workbook
//create a target sheet and cell
HSSFSheet sheet2 = wb.createSheet("Target Sheet");
sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
//create a target sheet and cell
HSSFSheet sheet2 = wb.createSheet("Target Sheet");
sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
cell = sheet.createRow(3).createCell(0);
cell.setCellValue("Worksheet Link");
link = helper.createHyperlink(HyperlinkType.DOCUMENT);
link.setAddress("'Target Sheet'!A1");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
cell = sheet.createRow(3).createCell(0);
cell.setCellValue("Worksheet Link");
link = helper.createHyperlink(HyperlinkType.DOCUMENT);
link.setAddress("'Target Sheet'!A1");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
FileOutputStream out = new FileOutputStream("hssf-links.xls");
wb.write(out);
out.close();
wb.close();
try (FileOutputStream out = new FileOutputStream("hssf-links.xls")) {
wb.write(out);
}
}
}
}

View File

@ -67,8 +67,7 @@ public class InCellLists {
* the Excel spreadsheet file this code will create.
*/
public void demonstrateMethodCalls(String outputFilename) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
try {
try (HSSFWorkbook workbook = new HSSFWorkbook()) {
HSSFSheet sheet = workbook.createSheet("In Cell Lists");
HSSFRow row = sheet.createRow(0);
@ -89,7 +88,7 @@ public class InCellLists {
this.listInCell(workbook, listItems, cell);
// The row height and cell width are set here to ensure that the
// list may be seen.
row.setHeight((short)1100);
row.setHeight((short) 1100);
sheet.setColumnWidth(0, 9500);
// Create a cell at A3 and insert a numbered list into that cell.
@ -100,7 +99,7 @@ public class InCellLists {
listItems.add("List Item Five.");
listItems.add("List Item Six.");
this.numberedListInCell(workbook, listItems, cell, 1, 2);
row.setHeight((short)1550);
row.setHeight((short) 1550);
// Create a cell at A4 and insert a numbered list into that cell.
// Note that a couple of items have been added to the listItems
@ -112,7 +111,7 @@ public class InCellLists {
listItems.add("List Item Nine.");
listItems.add("List Item Ten.");
this.bulletedListInCell(workbook, listItems, cell);
row.setHeight((short)2550);
row.setHeight((short) 2550);
// Insert a plain, multi-level list into cell A5. Note that
// the major difference here is that the list items are passed as
@ -143,7 +142,7 @@ public class InCellLists {
listItems.add("ML List Item Four - Sub Item Three.");
multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems));
this.multiLevelListInCell(workbook, multiLevelListItems, cell);
row.setHeight((short)2800);
row.setHeight((short) 2800);
// Insert a numbered multi-level list into cell A6. Note that the
// same ArrayList as constructed for the above plain multi-level
@ -151,8 +150,8 @@ public class InCellLists {
row = sheet.createRow(5);
cell = row.createCell(0);
this.multiLevelNumberedListInCell(workbook, multiLevelListItems,
cell, 1, 1, 1, 2);
row.setHeight((short)2800);
cell, 1, 1, 1, 2);
row.setHeight((short) 2800);
// Insert a numbered multi-level list into cell A7. Note that the
// same ArrayList as constructed for the plain multi-level list
@ -160,31 +159,18 @@ public class InCellLists {
row = sheet.createRow(6);
cell = row.createCell(0);
this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell);
row.setHeight((short)2800);
row.setHeight((short) 2800);
// Save the completed workbook
FileOutputStream fos = new FileOutputStream(new File(outputFilename));
try {
try (FileOutputStream fos = new FileOutputStream(new File(outputFilename))) {
workbook.write(fos);
} finally {
fos.close();
}
}
catch(FileNotFoundException fnfEx) {
System.out.println("Caught a: " + fnfEx.getClass().getName());
System.out.println("Message: " + fnfEx.getMessage());
System.out.println("Stacktrace follows...........");
fnfEx.printStackTrace(System.out);
}
catch(IOException ioEx) {
} catch (IOException ioEx) {
System.out.println("Caught a: " + ioEx.getClass().getName());
System.out.println("Message: " + ioEx.getMessage());
System.out.println("Stacktrace follows...........");
ioEx.printStackTrace(System.out);
}
finally {
workbook.close();
}
}
/**

View File

@ -31,19 +31,19 @@ import org.apache.poi.ss.util.CellRangeAddress;
*/
public class MergedCells {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow(1);
HSSFCell cell = row.createCell(1);
cell.setCellValue("This is a test of merging");
HSSFRow row = sheet.createRow(1);
HSSFCell cell = row.createCell(1);
cell.setCellValue("This is a test of merging");
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -33,31 +33,27 @@ import org.apache.poi.ss.usermodel.CellType;
*/
public class NewLinesInCells {
public static void main( String[] args ) throws IOException {
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet s = wb.createSheet();
HSSFFont f2 = wb.createFont();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFRow r = null;
HSSFCell c = null;
HSSFCellStyle cs = wb.createCellStyle();
HSSFFont f2 = wb.createFont();
HSSFCellStyle cs = wb.createCellStyle();
cs = wb.createCellStyle();
cs.setFont(f2);
// Word Wrap MUST be turned on
cs.setWrapText(true);
cs.setFont(f2);
// Word Wrap MUST be turned on
cs.setWrapText(true);
HSSFRow r = s.createRow(2);
r.setHeight((short) 0x349);
HSSFCell c = r.createCell(2);
c.setCellType(CellType.STRING);
c.setCellValue("Use \n with word wrap on to create a new line");
c.setCellStyle(cs);
s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20)));
r = s.createRow(2);
r.setHeight((short) 0x349);
c = r.createCell(2);
c.setCellType(CellType.STRING);
c.setCellValue("Use \n with word wrap on to create a new line");
c.setCellStyle(cs);
s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20)));
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -28,16 +28,17 @@ import org.apache.poi.ss.util.WorkbookUtil;
*/
public abstract class NewSheet {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("new sheet");
// create with default name
wb.createSheet();
final String name = "second sheet";
// setting sheet name later
wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name));
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
try (HSSFWorkbook wb = new HSSFWorkbook()) {
wb.createSheet("new sheet");
// create with default name
wb.createSheet();
final String name = "second sheet";
// setting sheet name later
wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name));
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -29,10 +29,10 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
*/
public class NewWorkbook {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
try (HSSFWorkbook wb = new HSSFWorkbook()) {
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -30,24 +30,25 @@ import java.io.*;
public class OfficeDrawing {
public static void main(String[] args) throws IOException {
// Create the workbook and sheets.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("new sheet");
HSSFSheet sheet2 = wb.createSheet("second sheet");
HSSFSheet sheet3 = wb.createSheet("third sheet");
HSSFSheet sheet4 = wb.createSheet("fourth sheet");
HSSFSheet sheet5 = wb.createSheet("fifth sheet");
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet1 = wb.createSheet("new sheet");
HSSFSheet sheet2 = wb.createSheet("second sheet");
HSSFSheet sheet3 = wb.createSheet("third sheet");
HSSFSheet sheet4 = wb.createSheet("fourth sheet");
HSSFSheet sheet5 = wb.createSheet("fifth sheet");
// Draw stuff in them
drawSheet1( sheet1 );
drawSheet2( sheet2 );
drawSheet3( sheet3 );
drawSheet4( sheet4, wb );
drawSheet5( sheet5, wb );
// Draw stuff in them
drawSheet1(sheet1);
drawSheet2(sheet2);
drawSheet3(sheet3);
drawSheet4(sheet4, wb);
drawSheet5(sheet5, wb);
// Write the file out.
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
// Write the file out.
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
private static void drawSheet1( HSSFSheet sheet1 )

View File

@ -32,51 +32,51 @@ public class OfficeDrawingWithGraphics {
public static void main( String[] args ) throws IOException {
// Create a workbook with one sheet and size the first three somewhat
// larger so we can fit the chemical structure diagram in.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet( "my drawing" );
sheet.setColumnWidth(1, 256 * 27);
HSSFRow row1 = sheet.createRow(0);
row1.setHeightInPoints(10 * 15f);
HSSFRow row2 = sheet.createRow(1);
row2.setHeightInPoints(5 * 15f);
HSSFRow row3 = sheet.createRow(2);
row3.setHeightInPoints(10 * 15f);
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("my drawing");
sheet.setColumnWidth(1, 256 * 27);
HSSFRow row1 = sheet.createRow(0);
row1.setHeightInPoints(10 * 15f);
HSSFRow row2 = sheet.createRow(1);
row2.setHeightInPoints(5 * 15f);
HSSFRow row3 = sheet.createRow(2);
row3.setHeightInPoints(10 * 15f);
// Add some cells so we can test that the anchoring works when we
// sort them.
row1.createCell(0).setCellValue("C");
row2.createCell(0).setCellValue("A");
row3.createCell(0).setCellValue("B");
// Add some cells so we can test that the anchoring works when we
// sort them.
row1.createCell(0).setCellValue("C");
row2.createCell(0).setCellValue("A");
row3.createCell(0).setCellValue("B");
// Create the top level drawing patriarch.
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// Create the top level drawing patriarch.
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
HSSFClientAnchor a;
HSSFShapeGroup group;
EscherGraphics g;
EscherGraphics2d g2d;
// Anchor entirely within one cell.
a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 );
group = patriarch.createGroup( a );
group.setCoordinates( 0, 0, 320, 276 );
float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel );
g2d = new EscherGraphics2d( g );
drawStar( g2d );
HSSFClientAnchor a;
HSSFShapeGroup group;
EscherGraphics g;
EscherGraphics2d g2d;
// Anchor entirely within one cell.
a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 1, 0, (short) 1, 0);
group = patriarch.createGroup(a);
group.setCoordinates(0, 0, 320, 276);
float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
g = new EscherGraphics(group, wb, Color.black, verticalPointsPerPixel);
g2d = new EscherGraphics2d(g);
drawStar(g2d);
a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 1, (short) 1, 1 );
group = patriarch.createGroup( a );
group.setCoordinates( 0, 0, 640, 276 );
verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 1, 1, (short) 1, 1);
group = patriarch.createGroup(a);
group.setCoordinates(0, 0, 640, 276);
verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
// verticalPixelsPerPoint = (float)Math.abs(group.getY2() - group.getY1()) / a.getAnchorHeightInPoints(sheet);
g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel );
g2d = new EscherGraphics2d( g );
drawStar( g2d );
FileOutputStream out = new FileOutputStream("workbook.xls");
wb.write(out);
out.close();
g = new EscherGraphics(group, wb, Color.black, verticalPointsPerPixel);
g2d = new EscherGraphics2d(g);
drawStar(g2d);
try (FileOutputStream out = new FileOutputStream("workbook.xls")) {
wb.write(out);
}
}
}
private static void drawStar( EscherGraphics2d g2d )

View File

@ -37,14 +37,11 @@ public class Outlines implements Closeable {
throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
POILogger LOGGER = POILogFactory.getLogger(Outlines.class);
for (int i=1; i<=13; i++) {
Outlines o = new Outlines();
try {
String log = (String)Outlines.class.getDeclaredMethod("test"+i).invoke(o);
String filename = "outline"+i+".xls";
try (Outlines o = new Outlines()) {
String log = (String) Outlines.class.getDeclaredMethod("test" + i).invoke(o);
String filename = "outline" + i + ".xls";
o.writeOut(filename);
LOGGER.log(POILogger.INFO, filename+" written. "+log);
} finally {
o.close();
LOGGER.log(POILogger.INFO, filename + " written. " + log);
}
}
}
@ -53,11 +50,8 @@ public class Outlines implements Closeable {
private final HSSFSheet sheet1 = wb.createSheet("new sheet");
public void writeOut(String filename) throws IOException {
FileOutputStream fileOut = new FileOutputStream(filename);
try {
try (FileOutputStream fileOut = new FileOutputStream(filename)) {
wb.write(fileOut);
} finally {
fileOut.close();
}
}

View File

@ -36,12 +36,7 @@ import org.apache.poi.ss.usermodel.CellType;
*/
public class ReadWriteWorkbook {
public static void main(String[] args) throws IOException {
FileInputStream fileIn = null;
FileOutputStream fileOut = null;
try
{
fileIn = new FileInputStream("workbook.xls");
try (FileInputStream fileIn = new FileInputStream("workbook.xls")) {
POIFSFileSystem fs = new POIFSFileSystem(fileIn);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
@ -55,13 +50,9 @@ public class ReadWriteWorkbook {
cell.setCellValue("a test");
// Write the output to a file
fileOut = new FileOutputStream("workbookout.xls");
wb.write(fileOut);
} finally {
if (fileOut != null)
fileOut.close();
if (fileIn != null)
fileIn.close();
try (FileOutputStream fileOut = new FileOutputStream("workbookout.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -30,35 +30,35 @@ import org.apache.poi.ss.util.CellRangeAddress;
public class RepeatingRowsAndColumns {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("first sheet");
HSSFSheet sheet2 = wb.createSheet("second sheet");
HSSFSheet sheet3 = wb.createSheet("third sheet");
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet1 = wb.createSheet("first sheet");
HSSFSheet sheet2 = wb.createSheet("second sheet");
HSSFSheet sheet3 = wb.createSheet("third sheet");
HSSFFont boldFont = wb.createFont();
boldFont.setFontHeightInPoints((short)22);
boldFont.setBold(true);
HSSFFont boldFont = wb.createFont();
boldFont.setFontHeightInPoints((short) 22);
boldFont.setBold(true);
HSSFCellStyle boldStyle = wb.createCellStyle();
boldStyle.setFont(boldFont);
HSSFCellStyle boldStyle = wb.createCellStyle();
boldStyle.setFont(boldFont);
HSSFRow row = sheet1.createRow(1);
HSSFCell cell = row.createCell(0);
cell.setCellValue("This quick brown fox");
cell.setCellStyle(boldStyle);
HSSFRow row = sheet1.createRow(1);
HSSFCell cell = row.createCell(0);
cell.setCellValue("This quick brown fox");
cell.setCellStyle(boldStyle);
// Set the columns to repeat from column 0 to 2 on the first sheet
sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
// Set the rows to repeat from row 0 to 2 on the second sheet.
sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:3"));
// Set the the repeating rows and columns on the third sheet.
CellRangeAddress cra = CellRangeAddress.valueOf("D1:E2");
sheet3.setRepeatingColumns(cra);
sheet3.setRepeatingRows(cra);
// Set the columns to repeat from column 0 to 2 on the first sheet
sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
// Set the rows to repeat from row 0 to 2 on the second sheet.
sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:3"));
// Set the the repeating rows and columns on the third sheet.
CellRangeAddress cra = CellRangeAddress.valueOf("D1:E2");
sheet3.setRepeatingColumns(cra);
sheet3.setRepeatingRows(cra);
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -28,24 +28,24 @@ import org.apache.poi.ss.usermodel.Sheet;
public class SplitAndFreezePanes {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("new sheet");
HSSFSheet sheet2 = wb.createSheet("second sheet");
HSSFSheet sheet3 = wb.createSheet("third sheet");
HSSFSheet sheet4 = wb.createSheet("fourth sheet");
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet1 = wb.createSheet("new sheet");
HSSFSheet sheet2 = wb.createSheet("second sheet");
HSSFSheet sheet3 = wb.createSheet("third sheet");
HSSFSheet sheet4 = wb.createSheet("fourth sheet");
// Freeze just one row
sheet1.createFreezePane( 0, 1, 0, 1 );
// Freeze just one column
sheet2.createFreezePane( 1, 0, 1, 0 );
// Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
sheet3.createFreezePane( 2, 2 );
// Create a split with the lower left side being the active quadrant
sheet4.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
// Freeze just one row
sheet1.createFreezePane(0, 1, 0, 1);
// Freeze just one column
sheet2.createFreezePane(1, 0, 1, 0);
// Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
sheet3.createFreezePane(2, 2);
// Create a split with the lower left side being the active quadrant
sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -32,32 +32,32 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
*/
public class WorkingWithFonts {
public static void main(String[] args) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(1);
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow(1);
// Create a new font and alter it.
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)24);
font.setFontName("Courier New");
font.setItalic(true);
font.setStrikeout(true);
// Create a new font and alter it.
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short) 24);
font.setFontName("Courier New");
font.setItalic(true);
font.setStrikeout(true);
// Fonts are set into a style so create a new one to use.
HSSFCellStyle style = wb.createCellStyle();
style.setFont(font);
// Fonts are set into a style so create a new one to use.
HSSFCellStyle style = wb.createCellStyle();
style.setFont(font);
// Create a cell and put a value in it.
HSSFCell cell = row.createCell(1);
cell.setCellValue("This is a test of fonts");
cell.setCellStyle(style);
// Create a cell and put a value in it.
HSSFCell cell = row.createCell(1);
cell.setCellValue("This is a test of fonts");
cell.setCellStyle(style);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -32,15 +32,14 @@ import java.io.FileOutputStream;
*/
public class ZoomSheet
{
public static void main(String[] args)
throws IOException
{
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("new sheet");
sheet1.setZoom(75); // 75 percent magnification
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
wb.close();
public static void main(String[] args) throws IOException {
try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet1 = wb.createSheet("new sheet");
sheet1.setZoom(75); // 75 percent magnification
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
}
}
}

View File

@ -216,13 +216,9 @@ public final class Word2Forrest
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream(args[0]);
OutputStream out = new FileOutputStream("test.xml");
try {
new Word2Forrest(new HWPFDocument(is), out);
} finally {
out.close();
is.close();
}
try (InputStream is = new FileInputStream(args[0]);
OutputStream out = new FileOutputStream("test.xml")) {
new Word2Forrest(new HWPFDocument(is), out);
}
}
}

View File

@ -29,30 +29,29 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class AligningCells {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(2);
row.setHeightInPoints(30);
for (int i = 0; i < 8; i++) {
//column width is set in units of 1/256th of a character width
sheet.setColumnWidth(i, 256 * 15);
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(2);
row.setHeightInPoints(30);
for (int i = 0; i < 8; i++) {
//column width is set in units of 1/256th of a character width
sheet.setColumnWidth(i, 256 * 15);
}
createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("ss-example-align.xlsx")) {
wb.write(fileOut);
}
}
createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
// Write the output to a file
OutputStream fileOut = new FileOutputStream("ss-example-align.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
/**

View File

@ -51,97 +51,97 @@ public class CalendarDemo {
Calendar calendar = Calendar.getInstance();
boolean xlsx = true;
for (int i = 0; i < args.length; i++) {
if(args[i].charAt(0) == '-'){
xlsx = args[i].equals("-xlsx");
for (String arg : args) {
if (arg.charAt(0) == '-') {
xlsx = arg.equals("-xlsx");
} else {
calendar.set(Calendar.YEAR, Integer.parseInt(args[i]));
calendar.set(Calendar.YEAR, Integer.parseInt(arg));
}
}
int year = calendar.get(Calendar.YEAR);
Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook();
try (Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook()) {
Map<String, CellStyle> styles = createStyles(wb);
Map<String, CellStyle> styles = createStyles(wb);
for (int month = 0; month < 12; month++) {
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
//create a sheet for each month
Sheet sheet = wb.createSheet(months[month]);
for (int month = 0; month < 12; month++) {
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
//create a sheet for each month
Sheet sheet = wb.createSheet(months[month]);
//turn off gridlines
sheet.setDisplayGridlines(false);
sheet.setPrintGridlines(false);
sheet.setFitToPage(true);
sheet.setHorizontallyCenter(true);
PrintSetup printSetup = sheet.getPrintSetup();
printSetup.setLandscape(true);
//turn off gridlines
sheet.setDisplayGridlines(false);
sheet.setPrintGridlines(false);
sheet.setFitToPage(true);
sheet.setHorizontallyCenter(true);
PrintSetup printSetup = sheet.getPrintSetup();
printSetup.setLandscape(true);
//the following three statements are required only for HSSF
sheet.setAutobreaks(true);
printSetup.setFitHeight((short)1);
printSetup.setFitWidth((short)1);
//the following three statements are required only for HSSF
sheet.setAutobreaks(true);
printSetup.setFitHeight((short) 1);
printSetup.setFitWidth((short) 1);
//the header row: centered text in 48pt font
Row headerRow = sheet.createRow(0);
headerRow.setHeightInPoints(80);
Cell titleCell = headerRow.createCell(0);
titleCell.setCellValue(months[month] + " " + year);
titleCell.setCellStyle(styles.get("title"));
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
//the header row: centered text in 48pt font
Row headerRow = sheet.createRow(0);
headerRow.setHeightInPoints(80);
Cell titleCell = headerRow.createCell(0);
titleCell.setCellValue(months[month] + " " + year);
titleCell.setCellStyle(styles.get("title"));
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
//header with month titles
Row monthRow = sheet.createRow(1);
for (int i = 0; i < days.length; i++) {
//set column widths, the width is measured in units of 1/256th of a character width
sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide
sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide
sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1));
Cell monthCell = monthRow.createCell(i*2);
monthCell.setCellValue(days[i]);
monthCell.setCellStyle(styles.get("month"));
//header with month titles
Row monthRow = sheet.createRow(1);
for (int i = 0; i < days.length; i++) {
//set column widths, the width is measured in units of 1/256th of a character width
sheet.setColumnWidth(i * 2, 5 * 256); //the column is 5 characters wide
sheet.setColumnWidth(i * 2 + 1, 13 * 256); //the column is 13 characters wide
sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1));
Cell monthCell = monthRow.createCell(i * 2);
monthCell.setCellValue(days[i]);
monthCell.setCellStyle(styles.get("month"));
}
int cnt = 1, day = 1;
int rownum = 2;
for (int j = 0; j < 6; j++) {
Row row = sheet.createRow(rownum++);
row.setHeightInPoints(100);
for (int i = 0; i < days.length; i++) {
Cell dayCell_1 = row.createCell(i * 2);
Cell dayCell_2 = row.createCell(i * 2 + 1);
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
if (cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
dayCell_1.setCellValue(day);
calendar.set(Calendar.DAY_OF_MONTH, ++day);
if (i == 0 || i == days.length - 1) {
dayCell_1.setCellStyle(styles.get("weekend_left"));
dayCell_2.setCellStyle(styles.get("weekend_right"));
} else {
dayCell_1.setCellStyle(styles.get("workday_left"));
dayCell_2.setCellStyle(styles.get("workday_right"));
}
} else {
dayCell_1.setCellStyle(styles.get("grey_left"));
dayCell_2.setCellStyle(styles.get("grey_right"));
}
cnt++;
}
if (calendar.get(Calendar.MONTH) > month) break;
}
}
int cnt = 1, day=1;
int rownum = 2;
for (int j = 0; j < 6; j++) {
Row row = sheet.createRow(rownum++);
row.setHeightInPoints(100);
for (int i = 0; i < days.length; i++) {
Cell dayCell_1 = row.createCell(i*2);
Cell dayCell_2 = row.createCell(i*2 + 1);
// Write the output to a file
String file = "calendar.xls";
if (wb instanceof XSSFWorkbook) file += "x";
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
dayCell_1.setCellValue(day);
calendar.set(Calendar.DAY_OF_MONTH, ++day);
if(i == 0 || i == days.length-1) {
dayCell_1.setCellStyle(styles.get("weekend_left"));
dayCell_2.setCellStyle(styles.get("weekend_right"));
} else {
dayCell_1.setCellStyle(styles.get("workday_left"));
dayCell_2.setCellStyle(styles.get("workday_right"));
}
} else {
dayCell_1.setCellStyle(styles.get("grey_left"));
dayCell_2.setCellStyle(styles.get("grey_right"));
}
cnt++;
}
if(calendar.get(Calendar.MONTH) > month) break;
try (FileOutputStream out = new FileOutputStream(file)) {
wb.write(out);
}
}
// Write the output to a file
String file = "calendar.xls";
if(wb instanceof XSSFWorkbook) file += "x";
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
wb.close();
}
/**

View File

@ -43,45 +43,44 @@ public class CellStyleDetails {
throw new IllegalArgumentException("Filename must be given");
}
Workbook wb = WorkbookFactory.create(new File(args[0]));
DataFormatter formatter = new DataFormatter();
for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {
Sheet sheet = wb.getSheetAt(sn);
System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());
for(Row row : sheet) {
System.out.println(" Row " + row.getRowNum());
for(Cell cell : row) {
CellReference ref = new CellReference(cell);
System.out.print(" " + ref.formatAsString());
System.out.print(" (" + cell.getColumnIndex() + ") ");
CellStyle style = cell.getCellStyle();
System.out.print("Format=" + style.getDataFormatString() + " ");
System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");
Font font = wb.getFontAt( style.getFontIndex() );
System.out.print("Font=" + font.getFontName() + " ");
System.out.print("FontColor=");
if(font instanceof HSSFFont) {
System.out.print( renderColor( ((HSSFFont)font).getHSSFColor((HSSFWorkbook)wb)) );
}
if(font instanceof XSSFFont) {
System.out.print( renderColor( ((XSSFFont)font).getXSSFColor()) );
}
System.out.println();
System.out.println(" " + formatter.formatCellValue(cell));
}
}
System.out.println();
try (Workbook wb = WorkbookFactory.create(new File(args[0]))) {
DataFormatter formatter = new DataFormatter();
for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) {
Sheet sheet = wb.getSheetAt(sn);
System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());
for (Row row : sheet) {
System.out.println(" Row " + row.getRowNum());
for (Cell cell : row) {
CellReference ref = new CellReference(cell);
System.out.print(" " + ref.formatAsString());
System.out.print(" (" + cell.getColumnIndex() + ") ");
CellStyle style = cell.getCellStyle();
System.out.print("Format=" + style.getDataFormatString() + " ");
System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");
Font font = wb.getFontAt(style.getFontIndex());
System.out.print("Font=" + font.getFontName() + " ");
System.out.print("FontColor=");
if (font instanceof HSSFFont) {
System.out.print(renderColor(((HSSFFont) font).getHSSFColor((HSSFWorkbook) wb)));
}
if (font instanceof XSSFFont) {
System.out.print(renderColor(((XSSFFont) font).getXSSFColor()));
}
System.out.println();
System.out.println(" " + formatter.formatCellValue(cell));
}
}
System.out.println();
}
}
wb.close();
}
private static String renderColor(Color color) {

View File

@ -74,22 +74,20 @@ public class SettingExternalFunction {
public static void main( String[] args ) throws IOException {
Workbook wb = new XSSFWorkbook(); // or new HSSFWorkbook()
try (Workbook wb = new XSSFWorkbook()) { // or new HSSFWorkbook()
// register the add-in
wb.addToolPack(new BloombergAddIn());
// register the add-in
wb.addToolPack(new BloombergAddIn());
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100");
row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") ");
row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") ");
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100");
row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") ");
row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") ");
FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx");
wb.write(out);
out.close();
wb.close();
try (FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx")) {
wb.write(out);
}
}
}
}

View File

@ -17,7 +17,6 @@
package org.apache.poi.ss.examples.formula;
import java.io.File ;
import java.io.FileInputStream ;
import org.apache.poi.ss.formula.functions.FreeRefFunction ;
import org.apache.poi.ss.formula.udf.DefaultUDFFinder ;
@ -50,33 +49,29 @@ public class UserDefinedFunctionExample {
System.out.println( "cell: " + args[1] ) ;
File workbookFile = new File( args[0] ) ;
Workbook workbook = WorkbookFactory.create(workbookFile, null, true);
try {
String[] functionNames = { "calculatePayment" } ;
FreeRefFunction[] functionImpls = { new CalculateMortgage() } ;
UDFFinder udfToolpack = new DefaultUDFFinder( functionNames, functionImpls ) ;
try (Workbook workbook = WorkbookFactory.create(workbookFile, null, true)) {
String[] functionNames = {"calculatePayment"};
FreeRefFunction[] functionImpls = {new CalculateMortgage()};
UDFFinder udfToolpack = new DefaultUDFFinder(functionNames, functionImpls);
// register the user-defined function in the workbook
workbook.addToolPack(udfToolpack);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
CellReference cr = new CellReference( args[1] ) ;
String sheetName = cr.getSheetName() ;
Sheet sheet = workbook.getSheet( sheetName ) ;
int rowIdx = cr.getRow() ;
int colIdx = cr.getCol() ;
Row row = sheet.getRow( rowIdx ) ;
Cell cell = row.getCell( colIdx ) ;
CellValue value = evaluator.evaluate( cell ) ;
System.out.println("returns value: " + value ) ;
} finally {
workbook.close();
CellReference cr = new CellReference(args[1]);
String sheetName = cr.getSheetName();
Sheet sheet = workbook.getSheet(sheetName);
int rowIdx = cr.getRow();
int colIdx = cr.getCol();
Row row = sheet.getRow(rowIdx);
Cell cell = row.getCell(colIdx);
CellValue value = evaluator.evaluate(cell);
System.out.println("returns value: " + value);
}
}
}

View File

@ -43,53 +43,52 @@ public final class DataExtraction {
}
FileInputStream is = new FileInputStream(args[0]);
XMLSlideShow ppt = new XMLSlideShow(is);
is.close();
try (XMLSlideShow ppt = new XMLSlideShow(is)) {
is.close();
// Get the document's embedded files.
for (PackagePart p : ppt.getAllEmbedds()) {
String type = p.getContentType();
// typically file name
String name = p.getPartName().getName();
out.println("Embedded file ("+type+"): "+name);
InputStream pIs = p.getInputStream();
// make sense of the part data
pIs.close();
}
// Get the document's embedded files.
for (PackagePart p : ppt.getAllEmbedds()) {
String type = p.getContentType();
// typically file name
String name = p.getPartName().getName();
out.println("Embedded file (" + type + "): " + name);
// Get the document's embedded files.
for (XSLFPictureData data : ppt.getPictureData()) {
String type = data.getContentType();
String name = data.getFileName();
out.println("Picture ("+type+"): "+name);
InputStream pIs = p.getInputStream();
// make sense of the part data
pIs.close();
InputStream pIs = data.getInputStream();
// make sense of the image data
pIs.close();
}
}
// size of the canvas in points
Dimension pageSize = ppt.getPageSize();
out.println("Pagesize: "+pageSize);
for(XSLFSlide slide : ppt.getSlides()) {
for(XSLFShape shape : slide){
if(shape instanceof XSLFTextShape) {
XSLFTextShape txShape = (XSLFTextShape)shape;
out.println(txShape.getText());
} else if (shape instanceof XSLFPictureShape){
XSLFPictureShape pShape = (XSLFPictureShape)shape;
XSLFPictureData pData = pShape.getPictureData();
out.println(pData.getFileName());
} else {
out.println("Process me: " + shape.getClass());
// Get the document's embedded files.
for (XSLFPictureData data : ppt.getPictureData()) {
String type = data.getContentType();
String name = data.getFileName();
out.println("Picture (" + type + "): " + name);
InputStream pIs = data.getInputStream();
// make sense of the image data
pIs.close();
}
// size of the canvas in points
Dimension pageSize = ppt.getPageSize();
out.println("Pagesize: " + pageSize);
for (XSLFSlide slide : ppt.getSlides()) {
for (XSLFShape shape : slide) {
if (shape instanceof XSLFTextShape) {
XSLFTextShape txShape = (XSLFTextShape) shape;
out.println(txShape.getText());
} else if (shape instanceof XSLFPictureShape) {
XSLFPictureShape pShape = (XSLFPictureShape) shape;
XSLFPictureData pData = pShape.getPictureData();
out.println(pData.getFileName());
} else {
out.println("Process me: " + shape.getClass());
}
}
}
}
ppt.close();
}
}

View File

@ -28,26 +28,22 @@ import java.io.FileOutputStream;
public final class MergePresentations {
public static void main(String args[]) throws Exception {
XMLSlideShow ppt = new XMLSlideShow();
try {
for (String arg : args){
try (XMLSlideShow ppt = new XMLSlideShow()) {
for (String arg : args) {
FileInputStream is = new FileInputStream(arg);
XMLSlideShow src = new XMLSlideShow(is);
is.close();
for(XSLFSlide srcSlide : src.getSlides()){
for (XSLFSlide srcSlide : src.getSlides()) {
ppt.createSlide().importContent(srcSlide);
}
src.close();
}
FileOutputStream out = new FileOutputStream("merged.pptx");
ppt.write(out);
out.close();
} finally {
ppt.close();
try (FileOutputStream out = new FileOutputStream("merged.pptx")) {
ppt.write(out);
}
}
}
}

View File

@ -62,104 +62,91 @@ public class PieChartDemo {
return;
}
BufferedReader modelReader = new BufferedReader(new FileReader(args[1]));
XMLSlideShow pptx = null;
try {
try (BufferedReader modelReader = new BufferedReader(new FileReader(args[1]))) {
String chartTitle = modelReader.readLine(); // first line is chart title
pptx = new XMLSlideShow(new FileInputStream(args[0]));
XSLFSlide slide = pptx.getSlides().get(0);
// find chart in the slide
XSLFChart chart = null;
for(POIXMLDocumentPart part : slide.getRelations()){
if(part instanceof XSLFChart){
chart = (XSLFChart) part;
break;
try (XMLSlideShow pptx = new XMLSlideShow(new FileInputStream(args[0]))) {
XSLFSlide slide = pptx.getSlides().get(0);
// find chart in the slide
XSLFChart chart = null;
for (POIXMLDocumentPart part : slide.getRelations()) {
if (part instanceof XSLFChart) {
chart = (XSLFChart) part;
break;
}
}
if (chart == null) throw new IllegalStateException("chart not found in the template");
// embedded Excel workbook that holds the chart data
POIXMLDocumentPart xlsPart = chart.getRelations().get(0);
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
CTChart ctChart = chart.getCTChart();
CTPlotArea plotArea = ctChart.getPlotArea();
CTPieChart pieChart = plotArea.getPieChartArray(0);
//Pie Chart Series
CTPieSer ser = pieChart.getSerArray(0);
// Series Text
CTSerTx tx = ser.getTx();
tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle);
sheet.createRow(0).createCell(1).setCellValue(chartTitle);
String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString();
tx.getStrRef().setF(titleRef);
// Category Axis Data
CTAxDataSource cat = ser.getCat();
CTStrData strData = cat.getStrRef().getStrCache();
// Values
CTNumDataSource val = ser.getVal();
CTNumData numData = val.getNumRef().getNumCache();
strData.setPtArray(null); // unset old axis text
numData.setPtArray(null); // unset old values
// set model
int idx = 0;
int rownum = 1;
String ln;
while ((ln = modelReader.readLine()) != null) {
String[] vals = ln.split("\\s+");
CTNumVal numVal = numData.addNewPt();
numVal.setIdx(idx);
numVal.setV(vals[1]);
CTStrVal sVal = strData.addNewPt();
sVal.setIdx(idx);
sVal.setV(vals[0]);
idx++;
XSSFRow row = sheet.createRow(rownum++);
row.createCell(0).setCellValue(vals[0]);
row.createCell(1).setCellValue(Double.valueOf(vals[1]));
}
numData.getPtCount().setVal(idx);
strData.getPtCount().setVal(idx);
String numDataRange = new CellRangeAddress(1, rownum - 1, 1, 1).formatAsString(sheet.getSheetName(), true);
val.getNumRef().setF(numDataRange);
String axisDataRange = new CellRangeAddress(1, rownum - 1, 0, 0).formatAsString(sheet.getSheetName(), true);
cat.getStrRef().setF(axisDataRange);
// updated the embedded workbook with the data
try (OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream()) {
wb.write(xlsOut);
}
// save the result
try (OutputStream out = new FileOutputStream("pie-chart-demo-output.pptx")) {
pptx.write(out);
}
}
}
if(chart == null) throw new IllegalStateException("chart not found in the template");
// embedded Excel workbook that holds the chart data
POIXMLDocumentPart xlsPart = chart.getRelations().get(0);
XSSFWorkbook wb = new XSSFWorkbook();
try {
XSSFSheet sheet = wb.createSheet();
CTChart ctChart = chart.getCTChart();
CTPlotArea plotArea = ctChart.getPlotArea();
CTPieChart pieChart = plotArea.getPieChartArray(0);
//Pie Chart Series
CTPieSer ser = pieChart.getSerArray(0);
// Series Text
CTSerTx tx = ser.getTx();
tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle);
sheet.createRow(0).createCell(1).setCellValue(chartTitle);
String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString();
tx.getStrRef().setF(titleRef);
// Category Axis Data
CTAxDataSource cat = ser.getCat();
CTStrData strData = cat.getStrRef().getStrCache();
// Values
CTNumDataSource val = ser.getVal();
CTNumData numData = val.getNumRef().getNumCache();
strData.setPtArray(null); // unset old axis text
numData.setPtArray(null); // unset old values
// set model
int idx = 0;
int rownum = 1;
String ln;
while((ln = modelReader.readLine()) != null){
String[] vals = ln.split("\\s+");
CTNumVal numVal = numData.addNewPt();
numVal.setIdx(idx);
numVal.setV(vals[1]);
CTStrVal sVal = strData.addNewPt();
sVal.setIdx(idx);
sVal.setV(vals[0]);
idx++;
XSSFRow row = sheet.createRow(rownum++);
row.createCell(0).setCellValue(vals[0]);
row.createCell(1).setCellValue(Double.valueOf(vals[1]));
}
numData.getPtCount().setVal(idx);
strData.getPtCount().setVal(idx);
String numDataRange = new CellRangeAddress(1, rownum-1, 1, 1).formatAsString(sheet.getSheetName(), true);
val.getNumRef().setF(numDataRange);
String axisDataRange = new CellRangeAddress(1, rownum-1, 0, 0).formatAsString(sheet.getSheetName(), true);
cat.getStrRef().setF(axisDataRange);
// updated the embedded workbook with the data
OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream();
try {
wb.write(xlsOut);
} finally {
xlsOut.close();
}
// save the result
OutputStream out = new FileOutputStream("pie-chart-demo-output.pptx");
try {
pptx.write(out);
} finally {
out.close();
}
} finally {
wb.close();
}
} finally {
if (pptx != null) pptx.close();
modelReader.close();
}
}
}

View File

@ -29,25 +29,24 @@ import java.io.IOException;
public class Tutorial1 {
public static void main(String[] args) throws IOException{
XMLSlideShow ppt = new XMLSlideShow();
try {
try (XMLSlideShow ppt = new XMLSlideShow()) {
// XSLFSlide#createSlide() with no arguments creates a blank slide
/*XSLFSlide blankSlide =*/ ppt.createSlide();
/*XSLFSlide blankSlide =*/
ppt.createSlide();
XSLFSlideMaster master = ppt.getSlideMasters().get(0);
XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);
XSLFSlide slide1 = ppt.createSlide(layout1) ;
XSLFSlide slide1 = ppt.createSlide(layout1);
XSLFTextShape[] ph1 = slide1.getPlaceholders();
XSLFTextShape titlePlaceholder1 = ph1[0];
titlePlaceholder1.setText("This is a title");
XSLFTextShape subtitlePlaceholder1 = ph1[1];
subtitlePlaceholder1.setText("this is a subtitle");
XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide2 = ppt.createSlide(layout2) ;
XSLFSlide slide2 = ppt.createSlide(layout2);
XSLFTextShape[] ph2 = slide2.getPlaceholders();
XSLFTextShape titlePlaceholder2 = ph2[0];
titlePlaceholder2.setText("This is a title");
@ -63,12 +62,10 @@ public class Tutorial1 {
XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph();
p3.setIndentLevel(2);
p3.addNewTextRun().setText("Level3 text");
FileOutputStream out = new FileOutputStream("slides.pptx");
ppt.write(out);
out.close();
} finally {
ppt.close();
try (FileOutputStream out = new FileOutputStream("slides.pptx")) {
ppt.write(out);
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -32,19 +32,17 @@ import org.apache.poi.sl.usermodel.AutoNumberingScheme;
public class Tutorial7 {
public static void main(String[] args) throws IOException {
XMLSlideShow ppt = new XMLSlideShow();
try {
try (XMLSlideShow ppt = new XMLSlideShow()) {
XSLFSlide slide = ppt.createSlide();
XSLFTextBox shape = slide.createTextBox();
shape.setAnchor(new Rectangle(50, 50, 400, 200));
XSLFTextParagraph p1 = shape.addNewTextParagraph();
p1.setIndentLevel(0);
p1.setBullet(true);
XSLFTextRun r1 = p1.addNewTextRun();
r1.setText("Bullet1");
XSLFTextParagraph p2 = shape.addNewTextParagraph();
// indentation before text
p2.setLeftMargin(60d);
@ -58,33 +56,31 @@ public class Tutorial7 {
p2.setIndentLevel(1);
XSLFTextRun r2 = p2.addNewTextRun();
r2.setText("Bullet2");
// the next three paragraphs form an auto-numbered list
XSLFTextParagraph p3 = shape.addNewTextParagraph();
p3.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
p3.setIndentLevel(2);
XSLFTextRun r3 = p3.addNewTextRun();
r3.setText("Numbered List Item - 1");
XSLFTextParagraph p4 = shape.addNewTextParagraph();
p4.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 2);
p4.setIndentLevel(2);
XSLFTextRun r4 = p4.addNewTextRun();
r4.setText("Numbered List Item - 2");
XSLFTextParagraph p5 = shape.addNewTextParagraph();
p5.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 3);
p5.setIndentLevel(2);
XSLFTextRun r5 = p5.addNewTextRun();
r5.setText("Numbered List Item - 3");
shape.resizeToFitText();
FileOutputStream out = new FileOutputStream("list.pptx");
ppt.write(out);
out.close();
} finally {
ppt.close();
try (FileOutputStream out = new FileOutputStream("list.pptx")) {
ppt.write(out);
}
}
}
}

View File

@ -40,31 +40,30 @@ public class Step1 {
}
FileInputStream fis = new FileInputStream(args[0]);
XMLSlideShow ppt = new XMLSlideShow(fis);
fis.close();
try (XMLSlideShow ppt = new XMLSlideShow(fis)) {
fis.close();
for(XSLFSlide slide : ppt.getSlides()){
System.out.println("Title: " + slide.getTitle());
for (XSLFSlide slide : ppt.getSlides()) {
System.out.println("Title: " + slide.getTitle());
for(XSLFShape shape : slide.getShapes()){
if(shape instanceof XSLFTextShape) {
XSLFTextShape tsh = (XSLFTextShape)shape;
for(XSLFTextParagraph p : tsh){
System.out.println("Paragraph level: " + p.getIndentLevel());
for(XSLFTextRun r : p){
System.out.println(r.getRawText());
System.out.println(" bold: " + r.isBold());
System.out.println(" italic: " + r.isItalic());
System.out.println(" underline: " + r.isUnderlined());
System.out.println(" font.family: " + r.getFontFamily());
System.out.println(" font.size: " + r.getFontSize());
System.out.println(" font.color: " + r.getFontColor());
for (XSLFShape shape : slide.getShapes()) {
if (shape instanceof XSLFTextShape) {
XSLFTextShape tsh = (XSLFTextShape) shape;
for (XSLFTextParagraph p : tsh) {
System.out.println("Paragraph level: " + p.getIndentLevel());
for (XSLFTextRun r : p) {
System.out.println(r.getRawText());
System.out.println(" bold: " + r.isBold());
System.out.println(" italic: " + r.isItalic());
System.out.println(" underline: " + r.isUnderlined());
System.out.println(" font.family: " + r.getFontFamily());
System.out.println(" font.size: " + r.getFontSize());
System.out.println(" font.color: " + r.getFontColor());
}
}
}
}
}
}
ppt.close();
}
}

View File

@ -33,45 +33,45 @@ import java.io.FileOutputStream;
*/
public class Step2 {
public static void main(String[] args) throws Exception{
XMLSlideShow ppt = new XMLSlideShow();
try (XMLSlideShow ppt = new XMLSlideShow()) {
// first see what slide layouts are available by default
System.out.println("Available slide layouts:");
for(XSLFSlideMaster master : ppt.getSlideMasters()){
for(XSLFSlideLayout layout : master.getSlideLayouts()){
System.out.println(layout.getType());
// first see what slide layouts are available by default
System.out.println("Available slide layouts:");
for (XSLFSlideMaster master : ppt.getSlideMasters()) {
for (XSLFSlideLayout layout : master.getSlideLayouts()) {
System.out.println(layout.getType());
}
}
// blank slide
/*XSLFSlide blankSlide =*/
ppt.createSlide();
XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);
// title slide
XSLFSlideLayout titleLayout = defaultMaster.getLayout(SlideLayout.TITLE);
XSLFSlide slide1 = ppt.createSlide(titleLayout);
XSLFTextShape title1 = slide1.getPlaceholder(0);
title1.setText("First Title");
// title and content
XSLFSlideLayout titleBodyLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide2 = ppt.createSlide(titleBodyLayout);
XSLFTextShape title2 = slide2.getPlaceholder(0);
title2.setText("Second Title");
XSLFTextShape body2 = slide2.getPlaceholder(1);
body2.clearText(); // unset any existing text
body2.addNewTextParagraph().addNewTextRun().setText("First paragraph");
body2.addNewTextParagraph().addNewTextRun().setText("Second paragraph");
body2.addNewTextParagraph().addNewTextRun().setText("Third paragraph");
try (FileOutputStream out = new FileOutputStream("step2.pptx")) {
ppt.write(out);
}
}
// blank slide
/*XSLFSlide blankSlide =*/ ppt.createSlide();
XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);
// title slide
XSLFSlideLayout titleLayout = defaultMaster.getLayout(SlideLayout.TITLE);
XSLFSlide slide1 = ppt.createSlide(titleLayout);
XSLFTextShape title1 = slide1.getPlaceholder(0);
title1.setText("First Title");
// title and content
XSLFSlideLayout titleBodyLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide2 = ppt.createSlide(titleBodyLayout);
XSLFTextShape title2 = slide2.getPlaceholder(0);
title2.setText("Second Title");
XSLFTextShape body2 = slide2.getPlaceholder(1);
body2.clearText(); // unset any existing text
body2.addNewTextParagraph().addNewTextRun().setText("First paragraph");
body2.addNewTextParagraph().addNewTextRun().setText("Second paragraph");
body2.addNewTextParagraph().addNewTextRun().setText("Third paragraph");
FileOutputStream out = new FileOutputStream("step2.pptx");
ppt.write(out);
out.close();
ppt.close();
}
}

View File

@ -42,8 +42,7 @@ import org.xml.sax.helpers.XMLReaderFactory;
*/
public class FromHowTo {
public void processFirstSheet(String filename) throws Exception {
OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
try {
try (OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ)) {
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
@ -54,14 +53,11 @@ public class FromHowTo {
InputSource sheetSource = new InputSource(sheet2);
parser.parse(sheetSource);
sheet2.close();
} finally {
pkg.close();
}
}
public void processAllSheets(String filename) throws Exception {
OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
try {
try (OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ)) {
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
@ -76,8 +72,6 @@ public class FromHowTo {
sheet.close();
System.out.println("");
}
} finally {
pkg.close();
}
}

View File

@ -31,26 +31,24 @@ public class Outlining {
}
private void collapseRow() throws IOException {
SXSSFWorkbook wb2 = new SXSSFWorkbook(100);
SXSSFSheet sheet2 = wb2.createSheet("new sheet");
try (SXSSFWorkbook wb2 = new SXSSFWorkbook(100)) {
SXSSFSheet sheet2 = wb2.createSheet("new sheet");
int rowCount = 20;
for (int i = 0; i < rowCount; i++) {
sheet2.createRow(i);
}
int rowCount = 20;
for (int i = 0; i < rowCount; i++) {
sheet2.createRow(i);
}
sheet2.groupRow(4, 9);
sheet2.groupRow(11, 19);
sheet2.groupRow(4, 9);
sheet2.groupRow(11, 19);
sheet2.setRowGroupCollapsed(4, true);
sheet2.setRowGroupCollapsed(4, true);
FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx");
try {
wb2.write(fileOut);
} finally {
fileOut.close();
wb2.dispose();
wb2.close();
try (FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx")) {
wb2.write(fileOut);
} finally {
wb2.dispose();
}
}
}
}

View File

@ -45,34 +45,33 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl;
public class AligningCells {
public static void main(String[] args) throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(2);
row.setHeightInPoints(30);
for (int i = 0; i < 8; i++) {
//column width is set in units of 1/256th of a character width
sheet.setColumnWidth(i, 256 * 15);
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(2);
row.setHeightInPoints(30);
for (int i = 0; i < 8; i++) {
//column width is set in units of 1/256th of a character width
sheet.setColumnWidth(i, 256 * 15);
}
createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
//center text over B4, C4, D4
row = sheet.createRow(3);
centerAcrossSelection(wb, row, 1, 3, VerticalAlignment.CENTER);
// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("xssf-align.xlsx")) {
wb.write(fileOut);
}
}
createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
//center text over B4, C4, D4
row = sheet.createRow(3);
centerAcrossSelection(wb, row, 1, 3, VerticalAlignment.CENTER);
// Write the output to a file
OutputStream fileOut = new FileOutputStream("xssf-align.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
/**

View File

@ -86,30 +86,29 @@ public class BigGridDemo {
// Step 1. Create a template file. Setup sheets and workbook-level objects such as
// cell styles, number formats, etc.
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Big Grid");
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet("Big Grid");
Map<String, XSSFCellStyle> styles = createStyles(wb);
//name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml
String sheetRef = sheet.getPackagePart().getPartName().getName();
Map<String, XSSFCellStyle> styles = createStyles(wb);
//name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml
String sheetRef = sheet.getPackagePart().getPartName().getName();
//save the template
FileOutputStream os = new FileOutputStream("template.xlsx");
wb.write(os);
os.close();
//save the template
FileOutputStream os = new FileOutputStream("template.xlsx");
wb.write(os);
os.close();
//Step 2. Generate XML file.
File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING);
generate(fw, styles);
fw.close();
//Step 2. Generate XML file.
File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING);
generate(fw, styles);
fw.close();
//Step 3. Substitute the template entry with the generated data
FileOutputStream out = new FileOutputStream("big-grid.xlsx");
substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out);
out.close();
wb.close();
//Step 3. Substitute the template entry with the generated data
try (FileOutputStream out = new FileOutputStream("big-grid.xlsx")) {
substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out);
}
}
}
/**
@ -194,28 +193,23 @@ public class BigGridDemo {
* @param out the stream to write the result to
*/
private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException {
ZipFile zip = ZipHelper.openZipFile(zipfile);
try {
ZipOutputStream zos = new ZipOutputStream(out);
Enumeration<? extends ZipEntry> en = zip.entries();
while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
if(!ze.getName().equals(entry)){
zos.putNextEntry(new ZipEntry(ze.getName()));
InputStream is = zip.getInputStream(ze);
try (ZipFile zip = ZipHelper.openZipFile(zipfile)) {
try (ZipOutputStream zos = new ZipOutputStream(out)) {
Enumeration<? extends ZipEntry> en = zip.entries();
while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
if (!ze.getName().equals(entry)) {
zos.putNextEntry(new ZipEntry(ze.getName()));
try (InputStream is = zip.getInputStream(ze)) {
copyStream(is, zos);
}
}
}
zos.putNextEntry(new ZipEntry(entry));
try (InputStream is = new FileInputStream(tmpfile)) {
copyStream(is, zos);
is.close();
}
}
zos.putNextEntry(new ZipEntry(entry));
InputStream is = new FileInputStream(tmpfile);
copyStream(is, zos);
is.close();
zos.close();
} finally {
zip.close();
}
}

View File

@ -55,80 +55,80 @@ public class CalendarDemo {
int year = calendar.get(Calendar.YEAR);
XSSFWorkbook wb = new XSSFWorkbook();
Map<String, XSSFCellStyle> styles = createStyles(wb);
try (XSSFWorkbook wb = new XSSFWorkbook()) {
Map<String, XSSFCellStyle> styles = createStyles(wb);
for (int month = 0; month < 12; month++) {
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
//create a sheet for each month
XSSFSheet sheet = wb.createSheet(months[month]);
for (int month = 0; month < 12; month++) {
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
//create a sheet for each month
XSSFSheet sheet = wb.createSheet(months[month]);
//turn off gridlines
sheet.setDisplayGridlines(false);
sheet.setPrintGridlines(false);
XSSFPrintSetup printSetup = sheet.getPrintSetup();
printSetup.setOrientation(PrintOrientation.LANDSCAPE);
sheet.setFitToPage(true);
sheet.setHorizontallyCenter(true);
//turn off gridlines
sheet.setDisplayGridlines(false);
sheet.setPrintGridlines(false);
XSSFPrintSetup printSetup = sheet.getPrintSetup();
printSetup.setOrientation(PrintOrientation.LANDSCAPE);
sheet.setFitToPage(true);
sheet.setHorizontallyCenter(true);
//the header row: centered text in 48pt font
XSSFRow headerRow = sheet.createRow(0);
headerRow.setHeightInPoints(80);
XSSFCell titleCell = headerRow.createCell(0);
titleCell.setCellValue(months[month] + " " + year);
titleCell.setCellStyle(styles.get("title"));
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
//the header row: centered text in 48pt font
XSSFRow headerRow = sheet.createRow(0);
headerRow.setHeightInPoints(80);
XSSFCell titleCell = headerRow.createCell(0);
titleCell.setCellValue(months[month] + " " + year);
titleCell.setCellStyle(styles.get("title"));
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
//header with month titles
XSSFRow monthRow = sheet.createRow(1);
for (int i = 0; i < days.length; i++) {
//for compatibility with HSSF we have to set column width in units of 1/256th of a character width
sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide
sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide
sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1));
XSSFCell monthCell = monthRow.createCell(i*2);
monthCell.setCellValue(days[i]);
monthCell.setCellStyle(styles.get("month"));
}
int cnt = 1, day=1;
int rownum = 2;
for (int j = 0; j < 6; j++) {
XSSFRow row = sheet.createRow(rownum++);
row.setHeightInPoints(100);
//header with month titles
XSSFRow monthRow = sheet.createRow(1);
for (int i = 0; i < days.length; i++) {
XSSFCell dayCell_1 = row.createCell(i*2);
XSSFCell dayCell_2 = row.createCell(i*2 + 1);
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
dayCell_1.setCellValue(day);
calendar.set(Calendar.DAY_OF_MONTH, ++day);
if(i == 0 || i == days.length-1) {
dayCell_1.setCellStyle(styles.get("weekend_left"));
dayCell_2.setCellStyle(styles.get("weekend_right"));
} else {
dayCell_1.setCellStyle(styles.get("workday_left"));
dayCell_2.setCellStyle(styles.get("workday_right"));
}
} else {
dayCell_1.setCellStyle(styles.get("grey_left"));
dayCell_2.setCellStyle(styles.get("grey_right"));
}
cnt++;
//for compatibility with HSSF we have to set column width in units of 1/256th of a character width
sheet.setColumnWidth(i * 2, 5 * 256); //the column is 5 characters wide
sheet.setColumnWidth(i * 2 + 1, 13 * 256); //the column is 13 characters wide
sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1));
XSSFCell monthCell = monthRow.createCell(i * 2);
monthCell.setCellValue(days[i]);
monthCell.setCellStyle(styles.get("month"));
}
if(calendar.get(Calendar.MONTH) > month) break;
}
}
// Write the output to a file
FileOutputStream out = new FileOutputStream("calendar-"+year+".xlsx");
wb.write(out);
out.close();
wb.close();
int cnt = 1, day = 1;
int rownum = 2;
for (int j = 0; j < 6; j++) {
XSSFRow row = sheet.createRow(rownum++);
row.setHeightInPoints(100);
for (int i = 0; i < days.length; i++) {
XSSFCell dayCell_1 = row.createCell(i * 2);
XSSFCell dayCell_2 = row.createCell(i * 2 + 1);
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
if (cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
dayCell_1.setCellValue(day);
calendar.set(Calendar.DAY_OF_MONTH, ++day);
if (i == 0 || i == days.length - 1) {
dayCell_1.setCellStyle(styles.get("weekend_left"));
dayCell_2.setCellStyle(styles.get("weekend_right"));
} else {
dayCell_1.setCellStyle(styles.get("workday_left"));
dayCell_2.setCellStyle(styles.get("workday_right"));
}
} else {
dayCell_1.setCellStyle(styles.get("grey_left"));
dayCell_2.setCellStyle(styles.get("grey_right"));
}
cnt++;
}
if (calendar.get(Calendar.MONTH) > month) break;
}
}
// Write the output to a file
try (FileOutputStream out = new FileOutputStream("calendar-" + year + ".xlsx")) {
wb.write(out);
}
}
}
/**

View File

@ -44,47 +44,45 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class CellComments {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
try (Workbook wb = new XSSFWorkbook()) {
CreationHelper factory = wb.getCreationHelper();
CreationHelper factory = wb.getCreationHelper();
Sheet sheet = wb.createSheet();
Sheet sheet = wb.createSheet();
Cell cell1 = sheet.createRow(3).createCell(5);
cell1.setCellValue("F4");
Cell cell1 = sheet.createRow(3).createCell(5);
cell1.setCellValue("F4");
Drawing<?> drawing = sheet.createDrawingPatriarch();
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = factory.createClientAnchor();
ClientAnchor anchor = factory.createClientAnchor();
Comment comment1 = drawing.createCellComment(anchor);
RichTextString str1 = factory.createRichTextString("Hello, World!");
comment1.setString(str1);
comment1.setAuthor("Apache POI");
cell1.setCellComment(comment1);
Comment comment1 = drawing.createCellComment(anchor);
RichTextString str1 = factory.createRichTextString("Hello, World!");
comment1.setString(str1);
comment1.setAuthor("Apache POI");
cell1.setCellComment(comment1);
Cell cell2 = sheet.createRow(2).createCell(2);
cell2.setCellValue("C3");
Cell cell2 = sheet.createRow(2).createCell(2);
cell2.setCellValue("C3");
Comment comment2 = drawing.createCellComment(anchor);
RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
//apply custom font to the text in the comment
Font font = wb.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short)14);
font.setBold(true);
font.setColor(IndexedColors.RED.getIndex());
str2.applyFont(font);
Comment comment2 = drawing.createCellComment(anchor);
RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
//apply custom font to the text in the comment
Font font = wb.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 14);
font.setBold(true);
font.setColor(IndexedColors.RED.getIndex());
str2.applyFont(font);
comment2.setString(str2);
comment2.setAuthor("Apache POI");
comment2.setAddress(new CellAddress("C3"));
comment2.setString(str2);
comment2.setAuthor("Apache POI");
comment2.setAddress(new CellAddress("C3"));
String fname = "comments.xlsx";
FileOutputStream out = new FileOutputStream(fname);
wb.write(out);
out.close();
wb.close();
try (FileOutputStream out = new FileOutputStream("comments.xlsx")) {
wb.write(out);
}
}
}
}

View File

@ -36,54 +36,53 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class CreateCell {
public static void main(String[] args) throws IOException {
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
CreationHelper creationHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
CreationHelper creationHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short) 0);
// Create a cell and put a value in it.
Cell cell = row.createCell((short) 0);
cell.setCellValue(1);
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell((short)0);
cell.setCellValue(1);
//numeric value
row.createCell(1).setCellValue(1.2);
//numeric value
row.createCell(1).setCellValue(1.2);
//plain string value
row.createCell(2).setCellValue("This is a string cell");
//plain string value
row.createCell(2).setCellValue("This is a string cell");
//rich text string
RichTextString str = creationHelper.createRichTextString("Apache");
Font font = wb.createFont();
font.setItalic(true);
font.setUnderline(Font.U_SINGLE);
str.applyFont(font);
row.createCell(3).setCellValue(str);
//rich text string
RichTextString str = creationHelper.createRichTextString("Apache");
Font font = wb.createFont();
font.setItalic(true);
font.setUnderline(Font.U_SINGLE);
str.applyFont(font);
row.createCell(3).setCellValue(str);
//boolean value
row.createCell(4).setCellValue(true);
//boolean value
row.createCell(4).setCellValue(true);
//formula
row.createCell(5).setCellFormula("SUM(A1:B1)");
//formula
row.createCell(5).setCellFormula("SUM(A1:B1)");
//date
CellStyle style = wb.createCellStyle();
style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(6);
cell.setCellValue(new Date());
cell.setCellStyle(style);
//date
CellStyle style = wb.createCellStyle();
style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(6);
cell.setCellValue(new Date());
cell.setCellStyle(style);
//hyperlink
row.createCell(7).setCellFormula("SUM(A1:B1)");
cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")");
//hyperlink
row.createCell(7).setCellFormula("SUM(A1:B1)");
cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -34,31 +34,31 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreatePivotTable {
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
//Create some data to build the pivot table on
setCellData(sheet);
//Create some data to build the pivot table on
setCellData(sheet);
AreaReference source = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
CellReference position = new CellReference("H5");
// Create a pivot table on this sheet, with H5 as the top-left cell..
// The pivot table's data source is on the same sheet in A1:D4
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
//Configure the pivot table
//Use first column as row label
pivotTable.addRowLabel(0);
//Sum up the second column
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
//Set the third column as filter
pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
//Add filter on forth column
pivotTable.addReportFilter(3);
AreaReference source = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
CellReference position = new CellReference("H5");
// Create a pivot table on this sheet, with H5 as the top-left cell..
// The pivot table's data source is on the same sheet in A1:D4
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
//Configure the pivot table
//Use first column as row label
pivotTable.addRowLabel(0);
//Sum up the second column
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
//Set the third column as filter
pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
//Add filter on forth column
pivotTable.addReportFilter(3);
FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable.xlsx")) {
wb.write(fileOut);
}
}
}
public static void setCellData(XSSFSheet sheet){

View File

@ -38,32 +38,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreatePivotTable2 {
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
//Create some data to build the pivot table on
setCellData(sheet);
//Create some data to build the pivot table on
setCellData(sheet);
AreaReference source = new AreaReference("A1:E7", SpreadsheetVersion.EXCEL2007);
CellReference position = new CellReference("H1");
// Create a pivot table on this sheet, with H1 as the top-left cell..
// The pivot table's data source is on the same sheet in A1:E7
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
//Configure the pivot table
//Use first column as row label
pivotTable.addRowLabel(0);
//Sum up the second column with column title and data format
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1, "Values", "#,##0.00");
//Use third column (month) as columns (side by side)
pivotTable.addColLabel(3, "DD.MM.YYYY");
AreaReference source = new AreaReference("A1:E7", SpreadsheetVersion.EXCEL2007);
CellReference position = new CellReference("H1");
// Create a pivot table on this sheet, with H1 as the top-left cell..
// The pivot table's data source is on the same sheet in A1:E7
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
//Configure the pivot table
//Use first column as row label
pivotTable.addRowLabel(0);
//Sum up the second column with column title and data format
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1, "Values", "#,##0.00");
//Use third column (month) as columns (side by side)
pivotTable.addColLabel(3, "DD.MM.YYYY");
//Add filter on forth column
pivotTable.addReportFilter(4);
//Add filter on forth column
pivotTable.addReportFilter(4);
FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable2.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable2.xlsx")) {
wb.write(fileOut);
}
}
}
public static void setCellData(XSSFSheet sheet){

View File

@ -36,58 +36,58 @@ public class CreateTable {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
// Create
XSSFTable table = sheet.createTable();
table.setName("Test");
table.setDisplayName("Test_Table");
// For now, create the initial style in a low-level way
table.getCTTable().addNewTableStyleInfo();
table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
// Style the table
XSSFTableStyleInfo style = (XSSFTableStyleInfo)table.getStyle();
style.setName("TableStyleMedium2");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
style.setFirstColumn(false);
style.setLastColumn(false);
style.setShowRowStripes(true);
style.setShowColumnStripes(true);
// Set the values for the table
XSSFRow row;
XSSFCell cell;
for(int i=0; i<3; i++) {
// Create row
row = sheet.createRow(i);
for(int j=0; j<3; j++) {
// Create cell
cell = row.createCell(j);
if(i == 0) {
cell.setCellValue("Column"+(j+1));
} else {
cell.setCellValue((i+1)*(j+1));
try (Workbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
// Create
XSSFTable table = sheet.createTable();
table.setName("Test");
table.setDisplayName("Test_Table");
// For now, create the initial style in a low-level way
table.getCTTable().addNewTableStyleInfo();
table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
// Style the table
XSSFTableStyleInfo style = (XSSFTableStyleInfo) table.getStyle();
style.setName("TableStyleMedium2");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
style.setFirstColumn(false);
style.setLastColumn(false);
style.setShowRowStripes(true);
style.setShowColumnStripes(true);
// Set the values for the table
XSSFRow row;
XSSFCell cell;
for (int i = 0; i < 3; i++) {
// Create row
row = sheet.createRow(i);
for (int j = 0; j < 3; j++) {
// Create cell
cell = row.createCell(j);
if (i == 0) {
cell.setCellValue("Column" + (j + 1));
} else {
cell.setCellValue((i + 1) * (j + 1));
}
}
}
}
// Create the columns
table.addColumn();
table.addColumn();
table.addColumn();
// Set which area the table should be placed in
AreaReference reference = wb.getCreationHelper().createAreaReference(
new CellReference(0, 0), new CellReference(2, 2));
table.setCellReferences(reference);
// Create the columns
table.addColumn();
table.addColumn();
table.addColumn();
// Save
FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
// Set which area the table should be placed in
AreaReference reference = wb.getCreationHelper().createAreaReference(
new CellReference(0, 0), new CellReference(2, 2));
table.setCellReferences(reference);
// Save
try (FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -35,34 +35,33 @@ public class CreateUserDefinedDataFormats {
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
CellStyle style;
DataFormat format = wb.createDataFormat();
Row row;
Cell cell;
short rowNum = 0;
short colNum = 0;
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
CellStyle style;
DataFormat format = wb.createDataFormat();
Row row;
Cell cell;
short rowNum = 0;
short colNum = 0;
row = sheet.createRow(rowNum);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("0.0"));
cell.setCellStyle(style);
row = sheet.createRow(rowNum);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("0.0"));
cell.setCellStyle(style);
row = sheet.createRow(++rowNum);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#,##0.0000"));
cell.setCellStyle(style);
row = sheet.createRow(++rowNum);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#,##0.0000"));
cell.setCellStyle(style);
FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -29,18 +29,16 @@ import java.io.ByteArrayOutputStream;
public class CustomXMLMapping {
public static void main(String[] args) throws Exception {
OPCPackage pkg = OPCPackage.open(args[0]);
XSSFWorkbook wb = new XSSFWorkbook(pkg);
try (OPCPackage pkg = OPCPackage.open(args[0]);
XSSFWorkbook wb = new XSSFWorkbook(pkg)) {
for (XSSFMap map : wb.getCustomXMLMappings()) {
XSSFExportToXml exporter = new XSSFExportToXml(map);
for (XSSFMap map : wb.getCustomXMLMappings()) {
XSSFExportToXml exporter = new XSSFExportToXml(map);
ByteArrayOutputStream os = new ByteArrayOutputStream();
exporter.exportToXML(os, true);
String xml = os.toString("UTF-8");
System.out.println(xml);
ByteArrayOutputStream os = new ByteArrayOutputStream();
exporter.exportToXML(os, true);
String xml = os.toString("UTF-8");
System.out.println(xml);
}
}
pkg.close();
wb.close();
}
}

View File

@ -32,36 +32,36 @@ import org.apache.poi.xwpf.usermodel.XWPFDocument;
*/
public class EmbeddedObjects {
public static void main(String[] args) throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook(args[0]);
for (PackagePart pPart : workbook.getAllEmbedds()) {
String contentType = pPart.getContentType();
InputStream is = pPart.getInputStream();
Closeable document;
if (contentType.equals("application/vnd.ms-excel")) {
// Excel Workbook - either binary or OpenXML
document = new HSSFWorkbook(is);
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
// Excel Workbook - OpenXML file format
document = new XSSFWorkbook(is);
} else if (contentType.equals("application/msword")) {
// Word Document - binary (OLE2CDF) file format
document = new HWPFDocument(is);
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
// Word Document - OpenXML file format
document = new XWPFDocument(is);
} else if (contentType.equals("application/vnd.ms-powerpoint")) {
// PowerPoint Document - binary file format
document = new HSLFSlideShow(is);
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
// PowerPoint Document - OpenXML file format
document = new XMLSlideShow(is);
} else {
// Any other type of embedded object.
document = is;
try (XSSFWorkbook workbook = new XSSFWorkbook(args[0])) {
for (PackagePart pPart : workbook.getAllEmbedds()) {
String contentType = pPart.getContentType();
try (InputStream is = pPart.getInputStream()) {
Closeable document;
if (contentType.equals("application/vnd.ms-excel")) {
// Excel Workbook - either binary or OpenXML
document = new HSSFWorkbook(is);
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
// Excel Workbook - OpenXML file format
document = new XSSFWorkbook(is);
} else if (contentType.equals("application/msword")) {
// Word Document - binary (OLE2CDF) file format
document = new HWPFDocument(is);
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
// Word Document - OpenXML file format
document = new XWPFDocument(is);
} else if (contentType.equals("application/vnd.ms-powerpoint")) {
// PowerPoint Document - binary file format
document = new HSLFSlideShow(is);
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
// PowerPoint Document - OpenXML file format
document = new XMLSlideShow(is);
} else {
// Any other type of embedded object.
document = is;
}
document.close();
}
}
document.close();
is.close();
}
workbook.close();
}
}

View File

@ -34,32 +34,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class FillsAndColors {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(1);
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(1);
// Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(FillPatternType.BIG_SPOTS);
Cell cell = row.createCell(1);
cell.setCellValue(new XSSFRichTextString("X"));
cell.setCellStyle(style);
// Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(FillPatternType.BIG_SPOTS);
Cell cell = row.createCell(1);
cell.setCellValue(new XSSFRichTextString("X"));
cell.setCellStyle(style);
// Orange "foreground", foreground being the fill foreground not the font color.
style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell = row.createCell(2);
cell.setCellValue(new XSSFRichTextString("X"));
cell.setCellStyle(style);
// Orange "foreground", foreground being the fill foreground not the font color.
style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell = row.createCell(2);
cell.setCellValue(new XSSFRichTextString("X"));
cell.setCellStyle(style);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -27,20 +27,20 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FitSheetToOnePage {
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
PrintSetup ps = sheet.getPrintSetup();
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
PrintSetup ps = sheet.getPrintSetup();
sheet.setAutobreaks(true);
sheet.setAutobreaks(true);
ps.setFitHeight((short) 1);
ps.setFitWidth((short) 1);
ps.setFitHeight((short) 1);
ps.setFitWidth((short) 1);
// Create various cells and rows for spreadsheet.
// Create various cells and rows for spreadsheet.
FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -28,58 +28,57 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class HeadersAndFooters {
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("first-header - format sheet");
sheet.createRow(0).createCell(0).setCellValue(123);
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("first-header - format sheet");
sheet.createRow(0).createCell(0).setCellValue(123);
//set page numbers in the footer
Footer footer = sheet.getFooter();
//&P == current page number
//&N == page numbers
footer.setRight("Page &P of &N");
//set page numbers in the footer
Footer footer = sheet.getFooter();
//&P == current page number
//&N == page numbers
footer.setRight("Page &P of &N");
Header firstHeader=((XSSFSheet)sheet).getFirstHeader();
//&F == workbook file name
firstHeader.setLeft("&F ......... first header");
for(int i=0;i<100;i=i+10){
sheet.createRow(i).createCell(0).setCellValue(123);
Header firstHeader = ((XSSFSheet) sheet).getFirstHeader();
//&F == workbook file name
firstHeader.setLeft("&F ......... first header");
for (int i = 0; i < 100; i = i + 10) {
sheet.createRow(i).createCell(0).setCellValue(123);
}
XSSFSheet sheet2 = (XSSFSheet) wb.createSheet("odd header-even footer");
Header oddHeader = sheet2.getOddHeader();
//&B == bold
//&E == double underline
//&D == date
oddHeader.setCenter("&B &E oddHeader &D ");
Footer evenFooter = sheet2.getEvenFooter();
evenFooter.setRight("even footer &P");
sheet2.createRow(10).createCell(0).setCellValue("Second sheet with an oddHeader and an evenFooter");
for (int i = 0; i < 200; i = i + 10) {
sheet2.createRow(i).createCell(0).setCellValue(123);
}
XSSFSheet sheet3 = (XSSFSheet) wb.createSheet("odd header- odd footer");
sheet3.createRow(10).createCell(0).setCellValue("Third sheet with oddHeader and oddFooter");
Header oddH = sheet3.getOddHeader();
//&C == centered
oddH.setCenter("centered oddHeader");
oddH.setLeft("left ");
oddH.setRight("right ");
Footer oddF = sheet3.getOddFooter();
oddF.setLeft("Page &P");
oddF.setRight("Pages &N ");
try (FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx")) {
wb.write(fileOut);
}
}
XSSFSheet sheet2 = (XSSFSheet)wb.createSheet("odd header-even footer");
Header oddHeader=sheet2.getOddHeader();
//&B == bold
//&E == double underline
//&D == date
oddHeader.setCenter("&B &E oddHeader &D ");
Footer evenFooter=sheet2.getEvenFooter();
evenFooter.setRight("even footer &P");
sheet2.createRow(10).createCell(0).setCellValue("Second sheet with an oddHeader and an evenFooter");
for(int i=0;i<200;i=i+10){
sheet2.createRow(i).createCell(0).setCellValue(123);
}
XSSFSheet sheet3 = (XSSFSheet)wb.createSheet("odd header- odd footer");
sheet3.createRow(10).createCell(0).setCellValue("Third sheet with oddHeader and oddFooter");
Header oddH=sheet3.getOddHeader();
//&C == centered
oddH.setCenter("centered oddHeader");
oddH.setLeft("left ");
oddH.setRight("right ");
Footer oddF=sheet3.getOddFooter();
oddF.setLeft("Page &P");
oddF.setRight("Pages &N ");
FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -35,64 +35,62 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class HyperlinkExample {
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
//cell style for hyperlinks
//by default hyperlinks are blue and underlined
CellStyle hlink_style = wb.createCellStyle();
Font hlink_font = wb.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
//cell style for hyperlinks
//by default hyperlinks are blue and underlined
CellStyle hlink_style = wb.createCellStyle();
Font hlink_font = wb.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
Cell cell;
Sheet sheet = wb.createSheet("Hyperlinks");
//URL
cell = sheet.createRow(0).createCell(0);
cell.setCellValue("URL Link");
Cell cell;
Sheet sheet = wb.createSheet("Hyperlinks");
//URL
cell = sheet.createRow(0).createCell(0);
cell.setCellValue("URL Link");
Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL);
link.setAddress("http://poi.apache.org/");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL);
link.setAddress("http://poi.apache.org/");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//link to a file in the current directory
cell = sheet.createRow(1).createCell(0);
cell.setCellValue("File Link");
link = createHelper.createHyperlink(HyperlinkType.FILE);
link.setAddress("link1.xls");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//link to a file in the current directory
cell = sheet.createRow(1).createCell(0);
cell.setCellValue("File Link");
link = createHelper.createHyperlink(HyperlinkType.FILE);
link.setAddress("link1.xls");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//e-mail link
cell = sheet.createRow(2).createCell(0);
cell.setCellValue("Email Link");
link = createHelper.createHyperlink(HyperlinkType.EMAIL);
//note, if subject contains white spaces, make sure they are url-encoded
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//e-mail link
cell = sheet.createRow(2).createCell(0);
cell.setCellValue("Email Link");
link = createHelper.createHyperlink(HyperlinkType.EMAIL);
//note, if subject contains white spaces, make sure they are url-encoded
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
//link to a place in this workbook
//link to a place in this workbook
//create a target sheet and cell
Sheet sheet2 = wb.createSheet("Target Sheet");
sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
//create a target sheet and cell
Sheet sheet2 = wb.createSheet("Target Sheet");
sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
cell = sheet.createRow(3).createCell(0);
cell.setCellValue("Worksheet Link");
Hyperlink link2 = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
link2.setAddress("'Target Sheet'!A1");
cell.setHyperlink(link2);
cell.setCellStyle(hlink_style);
cell = sheet.createRow(3).createCell(0);
cell.setCellValue("Worksheet Link");
Hyperlink link2 = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
link2.setAddress("'Target Sheet'!A1");
cell.setHyperlink(link2);
cell.setCellStyle(hlink_style);
FileOutputStream out = new FileOutputStream("hyperinks.xlsx");
wb.write(out);
out.close();
wb.close();
try (FileOutputStream out = new FileOutputStream("hyperinks.xlsx")) {
wb.write(out);
}
}
}
}

View File

@ -32,17 +32,17 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class IterateCells {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(new FileInputStream(args[0]));
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
System.out.println(wb.getSheetName(i));
for (Row row : sheet) {
System.out.println("rownum: " + row.getRowNum());
for (Cell cell : row) {
System.out.println(cell);
try (Workbook wb = new XSSFWorkbook(new FileInputStream(args[0]))) {
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
System.out.println(wb.getSheetName(i));
for (Row row : sheet) {
System.out.println("rownum: " + row.getRowNum());
for (Cell cell : row) {
System.out.println(cell);
}
}
}
}
wb.close();
}
}

View File

@ -44,50 +44,50 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class LineChart {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("linechart");
final int NUM_OF_ROWS = 3;
final int NUM_OF_COLUMNS = 10;
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("linechart");
final int NUM_OF_ROWS = 3;
final int NUM_OF_COLUMNS = 10;
// Create a row and put some cells in it. Rows are 0 based.
Row row;
Cell cell;
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
row = sheet.createRow((short) rowIndex);
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
cell = row.createCell((short) colIndex);
cell.setCellValue(colIndex * (rowIndex + 1));
// Create a row and put some cells in it. Rows are 0 based.
Row row;
Cell cell;
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
row = sheet.createRow((short) rowIndex);
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
cell = row.createCell((short) colIndex);
cell.setCellValue(colIndex * (rowIndex + 1));
}
}
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.TOP_RIGHT);
LineChartData data = chart.getChartDataFactory().createLineChartData();
// Use a category axis for the bottom axis.
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
data.addSeries(xs, ys1);
data.addSeries(xs, ys2);
chart.plot(data, bottomAxis, leftAxis);
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) {
wb.write(fileOut);
}
}
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.TOP_RIGHT);
LineChartData data = chart.getChartDataFactory().createLineChartData();
// Use a category axis for the bottom axis.
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
data.addSeries(xs, ys1);
data.addSeries(xs, ys2);
chart.plot(data, bottomAxis, leftAxis);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -33,19 +33,19 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class MergingCells {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue(new XSSFRichTextString("This is a test of merging"));
Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue(new XSSFRichTextString("This is a test of merging"));
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -32,28 +32,28 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class NewLinesInCells {
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet();
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(2);
Cell cell = row.createCell(2);
cell.setCellValue("Use \n with word wrap on to create a new line");
Row row = sheet.createRow(2);
Cell cell = row.createCell(2);
cell.setCellValue("Use \n with word wrap on to create a new line");
//to enable newlines you need set a cell styles with wrap=true
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);
//to enable newlines you need set a cell styles with wrap=true
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);
//increase row height to accomodate two lines of text
row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
//increase row height to accomodate two lines of text
row.setHeightInPoints((2 * sheet.getDefaultRowHeightInPoints()));
//adjust column width to fit the content
sheet.autoSizeColumn(2);
//adjust column width to fit the content
sheet.autoSizeColumn(2);
FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -35,50 +35,44 @@ public class Outlining {
private void groupRowColumn() throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet1 = wb.createSheet("new sheet");
sheet1.groupRow( 5, 14 );
sheet1.groupRow( 7, 14 );
sheet1.groupRow( 16, 19 );
sheet1.groupRow(5, 14);
sheet1.groupRow(7, 14);
sheet1.groupRow(16, 19);
sheet1.groupColumn( (short)4, (short)7 );
sheet1.groupColumn( (short)9, (short)12 );
sheet1.groupColumn( (short)10, (short)11 );
sheet1.groupColumn((short) 4, (short) 7);
sheet1.groupColumn((short) 9, (short) 12);
sheet1.groupColumn((short) 10, (short) 11);
OutputStream fileOut = new FileOutputStream("outlining.xlsx");
try {
wb.write(fileOut);
} finally {
fileOut.close();
wb.close();
try (OutputStream fileOut = new FileOutputStream("outlining.xlsx")) {
wb.write(fileOut);
}
}
}
private void collapseExpandRowColumn() throws IOException {
Workbook wb2 = new XSSFWorkbook();
Sheet sheet2 = wb2.createSheet("new sheet");
sheet2.groupRow( 5, 14 );
sheet2.groupRow( 7, 14 );
sheet2.groupRow( 16, 19 );
try (Workbook wb2 = new XSSFWorkbook()) {
Sheet sheet2 = wb2.createSheet("new sheet");
sheet2.groupRow(5, 14);
sheet2.groupRow(7, 14);
sheet2.groupRow(16, 19);
sheet2.groupColumn( (short)4, (short)7 );
sheet2.groupColumn( (short)9, (short)12 );
sheet2.groupColumn( (short)10, (short)11 );
sheet2.groupColumn((short) 4, (short) 7);
sheet2.groupColumn((short) 9, (short) 12);
sheet2.groupColumn((short) 10, (short) 11);
sheet2.setRowGroupCollapsed( 7, true );
//sheet1.setRowGroupCollapsed(7,false);
sheet2.setRowGroupCollapsed(7, true);
//sheet1.setRowGroupCollapsed(7,false);
sheet2.setColumnGroupCollapsed( (short)4, true );
sheet2.setColumnGroupCollapsed( (short)4, false );
sheet2.setColumnGroupCollapsed((short) 4, true);
sheet2.setColumnGroupCollapsed((short) 4, false);
OutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx");
try {
wb2.write(fileOut);
} finally {
fileOut.close();
wb2.close();
try (OutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx")) {
wb2.write(fileOut);
}
}
}
}

View File

@ -46,49 +46,49 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ScatterChart {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet 1");
final int NUM_OF_ROWS = 3;
final int NUM_OF_COLUMNS = 10;
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("Sheet 1");
final int NUM_OF_ROWS = 3;
final int NUM_OF_COLUMNS = 10;
// Create a row and put some cells in it. Rows are 0 based.
Row row;
Cell cell;
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
row = sheet.createRow((short) rowIndex);
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
cell = row.createCell((short) colIndex);
cell.setCellValue(colIndex * (rowIndex + 1));
// Create a row and put some cells in it. Rows are 0 based.
Row row;
Cell cell;
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
row = sheet.createRow((short) rowIndex);
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
cell = row.createCell((short) colIndex);
cell.setCellValue(colIndex * (rowIndex + 1));
}
}
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.TOP_RIGHT);
ScatterChartData data = chart.getChartDataFactory().createScatterChartData();
ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
data.addSerie(xs, ys1);
data.addSerie(xs, ys2);
chart.plot(data, bottomAxis, leftAxis);
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx")) {
wb.write(fileOut);
}
}
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.TOP_RIGHT);
ScatterChartData data = chart.getChartDataFactory().createScatterChartData();
ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
data.addSerie(xs, ys1);
data.addSerie(xs, ys2);
chart.plot(data, bottomAxis, leftAxis);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

View File

@ -26,21 +26,20 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public abstract class SelectedSheet {
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
wb.createSheet("row sheet");
wb.createSheet("another sheet");
Sheet sheet3 = wb.createSheet(" sheet 3 ");
sheet3.setSelected(true);
wb.setActiveSheet(2);
wb.createSheet("row sheet");
wb.createSheet("another sheet");
Sheet sheet3 = wb.createSheet(" sheet 3 ");
sheet3.setSelected(true);
wb.setActiveSheet(2);
// Create various cells and rows for spreadsheet.
// Create various cells and rows for spreadsheet.
FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -31,32 +31,30 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ShiftRows {
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
Row row1 = sheet.createRow(1);
row1.createCell(0).setCellValue(1);
Row row1 = sheet.createRow(1);
row1.createCell(0).setCellValue(1);
Row row2 = sheet.createRow(4);
row2.createCell(1).setCellValue(2);
Row row2 = sheet.createRow(4);
row2.createCell(1).setCellValue(2);
Row row3 = sheet.createRow(5);
row3.createCell(2).setCellValue(3);
Row row3 = sheet.createRow(5);
row3.createCell(2).setCellValue(3);
Row row4 = sheet.createRow(6);
row4.createCell(3).setCellValue(4);
Row row4 = sheet.createRow(6);
row4.createCell(3).setCellValue(4);
Row row5 = sheet.createRow(9);
row5.createCell(4).setCellValue(5);
Row row5 = sheet.createRow(9);
row5.createCell(4).setCellValue(5);
// Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
sheet.shiftRows(5, 10, -4);
// Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
sheet.shiftRows(5, 10, -4);
FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -29,24 +29,24 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class SplitAndFreezePanes {
public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
Sheet sheet3 = wb.createSheet("third sheet");
Sheet sheet4 = wb.createSheet("fourth sheet");
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
Sheet sheet3 = wb.createSheet("third sheet");
Sheet sheet4 = wb.createSheet("fourth sheet");
// Freeze just one row
sheet1.createFreezePane(0, 1, 0, 1);
// Freeze just one column
sheet2.createFreezePane(1, 0, 1, 0);
// Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
sheet3.createFreezePane(2, 2);
// Create a split with the lower left side being the active quadrant
sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
// Freeze just one row
sheet1.createFreezePane(0, 1, 0, 1);
// Freeze just one column
sheet2.createFreezePane(1, 0, 1, 0);
// Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
sheet3.createFreezePane(2, 2);
// Create a split with the lower left side being the active quadrant
sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -29,37 +29,34 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WorkbookProperties {
public static void main(String[]args) throws IOException {
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
workbook.createSheet("Workbook Properties");
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.createSheet("Workbook Properties");
POIXMLProperties props = workbook.getProperties();
POIXMLProperties props = workbook.getProperties();
/**
/*
* Extended properties are a predefined set of metadata properties
* that are specifically applicable to Office Open XML documents.
* Extended properties consist of 24 simple properties and 3 complex properties stored in the
* part targeted by the relationship of type
*/
POIXMLProperties.ExtendedProperties ext = props.getExtendedProperties();
ext.getUnderlyingProperties().setCompany("Apache Software Foundation");
ext.getUnderlyingProperties().setTemplate("XSSF");
POIXMLProperties.ExtendedProperties ext = props.getExtendedProperties();
ext.getUnderlyingProperties().setCompany("Apache Software Foundation");
ext.getUnderlyingProperties().setTemplate("XSSF");
/**
/*
* Custom properties enable users to define custom metadata properties.
*/
POIXMLProperties.CustomProperties cust = props.getCustomProperties();
cust.addProperty("Author", "John Smith");
cust.addProperty("Year", 2009);
cust.addProperty("Price", 45.50);
cust.addProperty("Available", true);
FileOutputStream out = new FileOutputStream("workbook.xlsx");
workbook.write(out);
out.close();
workbook.close();
POIXMLProperties.CustomProperties cust = props.getCustomProperties();
cust.addProperty("Author", "John Smith");
cust.addProperty("Year", 2009);
cust.addProperty("Price", 45.50);
cust.addProperty("Available", true);
try (FileOutputStream out = new FileOutputStream("workbook.xlsx")) {
workbook.write(out);
}
}
}
}

View File

@ -34,32 +34,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class WorkingWithBorders {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("borders");
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("borders");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short) 1);
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short) 1);
// Create a cell and put a value in it.
Cell cell = row.createCell((short) 1);
cell.setCellValue(4);
// Create a cell and put a value in it.
Cell cell = row.createCell((short) 1);
cell.setCellValue(4);
// Style the cell with borders all around.
CellStyle style = wb.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(style);
// Style the cell with borders all around.
CellStyle style = wb.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(style);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -33,75 +33,75 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/
public class WorkingWithFonts {
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("Fonts");
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("Fonts");
Font font0 = wb.createFont();
font0.setColor(IndexedColors.BROWN.getIndex());
CellStyle style0 = wb.createCellStyle();
style0.setFont(font0);
Font font0 = wb.createFont();
font0.setColor(IndexedColors.BROWN.getIndex());
CellStyle style0 = wb.createCellStyle();
style0.setFont(font0);
Font font1 = wb.createFont();
font1.setFontHeightInPoints((short)14);
font1.setFontName("Courier New");
font1.setColor(IndexedColors.RED.getIndex());
CellStyle style1 = wb.createCellStyle();
style1.setFont(font1);
Font font1 = wb.createFont();
font1.setFontHeightInPoints((short) 14);
font1.setFontName("Courier New");
font1.setColor(IndexedColors.RED.getIndex());
CellStyle style1 = wb.createCellStyle();
style1.setFont(font1);
Font font2 = wb.createFont();
font2.setFontHeightInPoints((short)16);
font2.setFontName("Arial");
font2.setColor(IndexedColors.GREEN.getIndex());
CellStyle style2 = wb.createCellStyle();
style2.setFont(font2);
Font font2 = wb.createFont();
font2.setFontHeightInPoints((short) 16);
font2.setFontName("Arial");
font2.setColor(IndexedColors.GREEN.getIndex());
CellStyle style2 = wb.createCellStyle();
style2.setFont(font2);
Font font3 = wb.createFont();
font3.setFontHeightInPoints((short)18);
font3.setFontName("Times New Roman");
font3.setColor(IndexedColors.LAVENDER.getIndex());
CellStyle style3 = wb.createCellStyle();
style3.setFont(font3);
Font font3 = wb.createFont();
font3.setFontHeightInPoints((short) 18);
font3.setFontName("Times New Roman");
font3.setColor(IndexedColors.LAVENDER.getIndex());
CellStyle style3 = wb.createCellStyle();
style3.setFont(font3);
Font font4 = wb.createFont();
font4.setFontHeightInPoints((short)18);
font4.setFontName("Wingdings");
font4.setColor(IndexedColors.GOLD.getIndex());
CellStyle style4 = wb.createCellStyle();
style4.setFont(font4);
Font font4 = wb.createFont();
font4.setFontHeightInPoints((short) 18);
font4.setFontName("Wingdings");
font4.setColor(IndexedColors.GOLD.getIndex());
CellStyle style4 = wb.createCellStyle();
style4.setFont(font4);
Font font5 = wb.createFont();
font5.setFontName("Symbol");
CellStyle style5 = wb.createCellStyle();
style5.setFont(font5);
Font font5 = wb.createFont();
font5.setFontName("Symbol");
CellStyle style5 = wb.createCellStyle();
style5.setFont(font5);
Cell cell0 = sheet.createRow(0).createCell(1);
cell0.setCellValue("Default");
cell0.setCellStyle(style0);
Cell cell0 = sheet.createRow(0).createCell(1);
cell0.setCellValue("Default");
cell0.setCellStyle(style0);
Cell cell1 = sheet.createRow(1).createCell(1);
cell1.setCellValue("Courier");
cell1.setCellStyle(style1);
Cell cell1 = sheet.createRow(1).createCell(1);
cell1.setCellValue("Courier");
cell1.setCellStyle(style1);
Cell cell2 = sheet.createRow(2).createCell(1);
cell2.setCellValue("Arial");
cell2.setCellStyle(style2);
Cell cell2 = sheet.createRow(2).createCell(1);
cell2.setCellValue("Arial");
cell2.setCellStyle(style2);
Cell cell3 = sheet.createRow(3).createCell(1);
cell3.setCellValue("Times New Roman");
cell3.setCellStyle(style3);
Cell cell3 = sheet.createRow(3).createCell(1);
cell3.setCellValue("Times New Roman");
cell3.setCellStyle(style3);
Cell cell4 = sheet.createRow(4).createCell(1);
cell4.setCellValue("Wingdings");
cell4.setCellStyle(style4);
Cell cell4 = sheet.createRow(4).createCell(1);
cell4.setCellValue("Wingdings");
cell4.setCellStyle(style4);
Cell cell5 = sheet.createRow(5).createCell(1);
cell5.setCellValue("Symbol");
cell5.setCellStyle(style5);
Cell cell5 = sheet.createRow(5).createCell(1);
cell5.setCellValue("Symbol");
cell5.setCellStyle(style5);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -30,9 +30,9 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WorkingWithPageSetup {
public static void main(String[]args) throws Exception {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
/**
/*
* It's possible to set up repeating rows and columns in your printouts by using the setRepeatingRowsAndColumns() function in the Workbook object.
*
* This function Contains 5 parameters:
@ -42,42 +42,41 @@ public class WorkingWithPageSetup {
* The fourth and fifth parameters specify the range for the rows to repeat.
* To stop the columns from repeating pass in -1 as the start and end rows.
*/
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
// Set the columns to repeat from column 0 to 2 on the first sheet
Row row1 = sheet1.createRow(0);
row1.createCell(0).setCellValue(1);
row1.createCell(1).setCellValue(2);
row1.createCell(2).setCellValue(3);
Row row2 = sheet1.createRow(1);
row2.createCell(1).setCellValue(4);
row2.createCell(2).setCellValue(5);
// Set the columns to repeat from column 0 to 2 on the first sheet
Row row1 = sheet1.createRow(0);
row1.createCell(0).setCellValue(1);
row1.createCell(1).setCellValue(2);
row1.createCell(2).setCellValue(3);
Row row2 = sheet1.createRow(1);
row2.createCell(1).setCellValue(4);
row2.createCell(2).setCellValue(5);
Row row3 = sheet2.createRow(1);
row3.createCell(0).setCellValue(2.1);
row3.createCell(4).setCellValue(2.2);
row3.createCell(5).setCellValue(2.3);
Row row4 = sheet2.createRow(2);
row4.createCell(4).setCellValue(2.4);
row4.createCell(5).setCellValue(2.5);
Row row3 = sheet2.createRow(1);
row3.createCell(0).setCellValue(2.1);
row3.createCell(4).setCellValue(2.2);
row3.createCell(5).setCellValue(2.3);
Row row4 = sheet2.createRow(2);
row4.createCell(4).setCellValue(2.4);
row4.createCell(5).setCellValue(2.5);
// Set the columns to repeat from column 0 to 2 on the first sheet
sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
// Set the the repeating rows and columns on the second sheet.
CellRangeAddress cra = CellRangeAddress.valueOf("E2:F3");
sheet2.setRepeatingColumns(cra);
sheet2.setRepeatingRows(cra);
// Set the columns to repeat from column 0 to 2 on the first sheet
sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
// Set the the repeating rows and columns on the second sheet.
CellRangeAddress cra = CellRangeAddress.valueOf("E2:F3");
sheet2.setRepeatingColumns(cra);
sheet2.setRepeatingRows(cra);
//set the print area for the first sheet
wb.setPrintArea(0, 1, 2, 0, 3);
//set the print area for the first sheet
wb.setPrintArea(0, 1, 2, 0, 3);
FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
try (FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx")) {
wb.write(fileOut);
}
}
}
}

View File

@ -39,45 +39,38 @@ public class WorkingWithPictures {
public static void main(String[] args) throws IOException {
//create a new workbook
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
try {
try (Workbook wb = new XSSFWorkbook()) {
CreationHelper helper = wb.getCreationHelper();
//add a picture in this workbook.
InputStream is = new FileInputStream(args[0]);
byte[] bytes = IOUtils.toByteArray(is);
is.close();
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
//create sheet
Sheet sheet = wb.createSheet();
//create drawing
Drawing<?> drawing = sheet.createDrawingPatriarch();
//add a picture shape
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(1);
Picture pict = drawing.createPicture(anchor, pictureIdx);
//auto-size picture
pict.resize(2);
//save workbook
String file = "picture.xls";
if(wb instanceof XSSFWorkbook)
{
if (wb instanceof XSSFWorkbook) {
file += "x"; // NOSONAR
}
OutputStream fileOut = new FileOutputStream(file);
try {
try (OutputStream fileOut = new FileOutputStream(file)) {
wb.write(fileOut);
} finally {
fileOut.close();
}
} finally {
wb.close();
}
}
}

View File

@ -28,41 +28,34 @@ import java.io.OutputStream;
public class WorkingWithRichText {
public static void main(String[] args) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
try {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(2);
XSSFCell cell = row.createCell(1);
XSSFRichTextString rt = new XSSFRichTextString("The quick brown fox");
XSSFFont font1 = wb.createFont();
font1.setBold(true);
font1.setColor(new XSSFColor(new java.awt.Color(255, 0, 0)));
rt.applyFont(0, 10, font1);
XSSFFont font2 = wb.createFont();
font2.setItalic(true);
font2.setUnderline(XSSFFont.U_DOUBLE);
font2.setColor(new XSSFColor(new java.awt.Color(0, 255, 0)));
rt.applyFont(10, 19, font2);
XSSFFont font3 = wb.createFont();
font3.setColor(new XSSFColor(new java.awt.Color(0, 0, 255)));
rt.append(" Jumped over the lazy dog", font3);
cell.setCellValue(rt);
// Write the output to a file
OutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx");
try {
try (OutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx")) {
wb.write(fileOut);
} finally {
fileOut.close();
}
} finally {
wb.close();
}
}
}

View File

@ -31,26 +31,26 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
public class BetterHeaderFooterExample {
public static void main(String[] args) throws IOException {
XWPFDocument doc = new XWPFDocument();
try (XWPFDocument doc = new XWPFDocument()) {
XWPFParagraph p = doc.createParagraph();
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
r.setText("Some Text");
r.setBold(true);
r = p.createRun();
r.setText("Goodbye");
XWPFRun r = p.createRun();
r.setText("Some Text");
r.setBold(true);
r = p.createRun();
r.setText("Goodbye");
// create header/footer functions insert an empty paragraph
XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT);
head.createParagraph().createRun().setText("header");
XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT);
foot.createParagraph().createRun().setText("footer");
OutputStream os = new FileOutputStream(new File("header2.docx"));
doc.write(os);
os.close();
doc.close();
// create header/footer functions insert an empty paragraph
XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT);
head.createParagraph().createRun().setText("header");
XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT);
foot.createParagraph().createRun().setText("footer");
try (OutputStream os = new FileOutputStream(new File("header2.docx"))) {
doc.write(os);
}
}
}
}

View File

@ -41,65 +41,65 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblLayoutType;
public class HeaderFooterTable {
public static void main(String[] args) throws IOException {
XWPFDocument doc = new XWPFDocument();
// Create a header with a 1 row, 3 column table
// changes made for issue 57366 allow a new header or footer
// to be created empty. This is a change. You will have to add
// either a paragraph or a table to the header or footer for
// the document to be considered valid.
XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
XWPFTable tbl = hdr.createTable(1, 3);
// Set the padding around text in the cells to 1/10th of an inch
int pad = (int) (.1 * 1440);
tbl.setCellMargins(pad, pad, pad, pad);
try (XWPFDocument doc = new XWPFDocument()) {
// Set table width to 6.5 inches in 1440ths of a point
tbl.setWidth((int)(6.5 * 1440));
// Can not yet set table or cell width properly, tables default to
// autofit layout, and this requires fixed layout
CTTbl ctTbl = tbl.getCTTbl();
CTTblPr ctTblPr = ctTbl.addNewTblPr();
CTTblLayoutType layoutType = ctTblPr.addNewTblLayout();
layoutType.setType(STTblLayoutType.FIXED);
// Create a header with a 1 row, 3 column table
// changes made for issue 57366 allow a new header or footer
// to be created empty. This is a change. You will have to add
// either a paragraph or a table to the header or footer for
// the document to be considered valid.
XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
XWPFTable tbl = hdr.createTable(1, 3);
// Now set up a grid for the table, cells will fit into the grid
// Each cell width is 3120 in 1440ths of an inch, or 1/3rd of 6.5"
BigInteger w = new BigInteger("3120");
CTTblGrid grid = ctTbl.addNewTblGrid();
for (int i = 0; i < 3; i++) {
CTTblGridCol gridCol = grid.addNewGridCol();
gridCol.setW(w);
// Set the padding around text in the cells to 1/10th of an inch
int pad = (int) (.1 * 1440);
tbl.setCellMargins(pad, pad, pad, pad);
// Set table width to 6.5 inches in 1440ths of a point
tbl.setWidth((int) (6.5 * 1440));
// Can not yet set table or cell width properly, tables default to
// autofit layout, and this requires fixed layout
CTTbl ctTbl = tbl.getCTTbl();
CTTblPr ctTblPr = ctTbl.addNewTblPr();
CTTblLayoutType layoutType = ctTblPr.addNewTblLayout();
layoutType.setType(STTblLayoutType.FIXED);
// Now set up a grid for the table, cells will fit into the grid
// Each cell width is 3120 in 1440ths of an inch, or 1/3rd of 6.5"
BigInteger w = new BigInteger("3120");
CTTblGrid grid = ctTbl.addNewTblGrid();
for (int i = 0; i < 3; i++) {
CTTblGridCol gridCol = grid.addNewGridCol();
gridCol.setW(w);
}
// Add paragraphs to the cells
XWPFTableRow row = tbl.getRow(0);
XWPFTableCell cell = row.getCell(0);
XWPFParagraph p = cell.getParagraphArray(0);
XWPFRun r = p.createRun();
r.setText("header left cell");
cell = row.getCell(1);
p = cell.getParagraphArray(0);
r = p.createRun();
r.setText("header center cell");
cell = row.getCell(2);
p = cell.getParagraphArray(0);
r = p.createRun();
r.setText("header right cell");
// Create a footer with a Paragraph
XWPFFooter ftr = doc.createFooter(HeaderFooterType.DEFAULT);
p = ftr.createParagraph();
r = p.createRun();
r.setText("footer text");
try (OutputStream os = new FileOutputStream(new File("headertable.docx"))) {
doc.write(os);
}
}
// Add paragraphs to the cells
XWPFTableRow row = tbl.getRow(0);
XWPFTableCell cell = row.getCell(0);
XWPFParagraph p = cell.getParagraphArray(0);
XWPFRun r = p.createRun();
r.setText("header left cell");
cell = row.getCell(1);
p = cell.getParagraphArray(0);
r = p.createRun();
r.setText("header center cell");
cell = row.getCell(2);
p = cell.getParagraphArray(0);
r = p.createRun();
r.setText("header right cell");
// Create a footer with a Paragraph
XWPFFooter ftr = doc.createFooter(HeaderFooterType.DEFAULT);
p = ftr.createParagraph();
r = p.createRun();
r.setText("footer text");
OutputStream os = new FileOutputStream(new File("headertable.docx"));
doc.write(os);
doc.close();
}
}

View File

@ -36,95 +36,95 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
public class SimpleDocument {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument();
try (XWPFDocument doc = new XWPFDocument()) {
XWPFParagraph p1 = doc.createParagraph();
p1.setAlignment(ParagraphAlignment.CENTER);
p1.setBorderBottom(Borders.DOUBLE);
p1.setBorderTop(Borders.DOUBLE);
XWPFParagraph p1 = doc.createParagraph();
p1.setAlignment(ParagraphAlignment.CENTER);
p1.setBorderBottom(Borders.DOUBLE);
p1.setBorderTop(Borders.DOUBLE);
p1.setBorderRight(Borders.DOUBLE);
p1.setBorderLeft(Borders.DOUBLE);
p1.setBorderBetween(Borders.SINGLE);
p1.setBorderRight(Borders.DOUBLE);
p1.setBorderLeft(Borders.DOUBLE);
p1.setBorderBetween(Borders.SINGLE);
p1.setVerticalAlignment(TextAlignment.TOP);
p1.setVerticalAlignment(TextAlignment.TOP);
XWPFRun r1 = p1.createRun();
r1.setBold(true);
r1.setText("The quick brown fox");
r1.setBold(true);
r1.setFontFamily("Courier");
r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
r1.setTextPosition(100);
XWPFRun r1 = p1.createRun();
r1.setBold(true);
r1.setText("The quick brown fox");
r1.setBold(true);
r1.setFontFamily("Courier");
r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
r1.setTextPosition(100);
XWPFParagraph p2 = doc.createParagraph();
p2.setAlignment(ParagraphAlignment.RIGHT);
XWPFParagraph p2 = doc.createParagraph();
p2.setAlignment(ParagraphAlignment.RIGHT);
//BORDERS
p2.setBorderBottom(Borders.DOUBLE);
p2.setBorderTop(Borders.DOUBLE);
p2.setBorderRight(Borders.DOUBLE);
p2.setBorderLeft(Borders.DOUBLE);
p2.setBorderBetween(Borders.SINGLE);
//BORDERS
p2.setBorderBottom(Borders.DOUBLE);
p2.setBorderTop(Borders.DOUBLE);
p2.setBorderRight(Borders.DOUBLE);
p2.setBorderLeft(Borders.DOUBLE);
p2.setBorderBetween(Borders.SINGLE);
XWPFRun r2 = p2.createRun();
r2.setText("jumped over the lazy dog");
r2.setStrikeThrough(true);
r2.setFontSize(20);
XWPFRun r2 = p2.createRun();
r2.setText("jumped over the lazy dog");
r2.setStrikeThrough(true);
r2.setFontSize(20);
XWPFRun r3 = p2.createRun();
r3.setText("and went away");
r3.setStrikeThrough(true);
r3.setFontSize(20);
r3.setSubscript(VerticalAlign.SUPERSCRIPT);
XWPFRun r3 = p2.createRun();
r3.setText("and went away");
r3.setStrikeThrough(true);
r3.setFontSize(20);
r3.setSubscript(VerticalAlign.SUPERSCRIPT);
XWPFParagraph p3 = doc.createParagraph();
p3.setWordWrapped(true);
p3.setPageBreak(true);
//p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
p3.setAlignment(ParagraphAlignment.BOTH);
p3.setSpacingBetween(15, LineSpacingRule.EXACT);
XWPFParagraph p3 = doc.createParagraph();
p3.setWordWrapped(true);
p3.setPageBreak(true);
p3.setIndentationFirstLine(600);
//p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
p3.setAlignment(ParagraphAlignment.BOTH);
p3.setSpacingBetween(15, LineSpacingRule.EXACT);
XWPFRun r4 = p3.createRun();
r4.setTextPosition(20);
r4.setText("To be, or not to be: that is the question: "
+ "Whether 'tis nobler in the mind to suffer "
+ "The slings and arrows of outrageous fortune, "
+ "Or to take arms against a sea of troubles, "
+ "And by opposing end them? To die: to sleep; ");
r4.addBreak(BreakType.PAGE);
r4.setText("No more; and by a sleep to say we end "
+ "The heart-ache and the thousand natural shocks "
+ "That flesh is heir to, 'tis a consummation "
+ "Devoutly to be wish'd. To die, to sleep; "
+ "To sleep: perchance to dream: ay, there's the rub; "
+ ".......");
r4.setItalic(true);
p3.setIndentationFirstLine(600);
XWPFRun r4 = p3.createRun();
r4.setTextPosition(20);
r4.setText("To be, or not to be: that is the question: "
+ "Whether 'tis nobler in the mind to suffer "
+ "The slings and arrows of outrageous fortune, "
+ "Or to take arms against a sea of troubles, "
+ "And by opposing end them? To die: to sleep; ");
r4.addBreak(BreakType.PAGE);
r4.setText("No more; and by a sleep to say we end "
+ "The heart-ache and the thousand natural shocks "
+ "That flesh is heir to, 'tis a consummation "
+ "Devoutly to be wish'd. To die, to sleep; "
+ "To sleep: perchance to dream: ay, there's the rub; "
+ ".......");
r4.setItalic(true);
//This would imply that this break shall be treated as a simple line break, and break the line after that word:
XWPFRun r5 = p3.createRun();
r5.setTextPosition(-10);
r5.setText("For in that sleep of death what dreams may come");
r5.addCarriageReturn();
r5.setText("When we have shuffled off this mortal coil,"
+ "Must give us pause: there's the respect"
+ "That makes calamity of so long life;");
r5.addBreak();
r5.setText("For who would bear the whips and scorns of time,"
+ "The oppressor's wrong, the proud man's contumely,");
r5.addBreak(BreakClear.ALL);
r5.setText("The pangs of despised love, the law's delay,"
+ "The insolence of office and the spurns" + ".......");
XWPFRun r5 = p3.createRun();
r5.setTextPosition(-10);
r5.setText("For in that sleep of death what dreams may come");
r5.addCarriageReturn();
r5.setText("When we have shuffled off this mortal coil,"
+ "Must give us pause: there's the respect"
+ "That makes calamity of so long life;");
r5.addBreak();
r5.setText("For who would bear the whips and scorns of time,"
+ "The oppressor's wrong, the proud man's contumely,");
FileOutputStream out = new FileOutputStream("simple.docx");
doc.write(out);
out.close();
doc.close();
r5.addBreak(BreakClear.ALL);
r5.setText("The pangs of despised love, the law's delay,"
+ "The insolence of office and the spurns" + ".......");
try (FileOutputStream out = new FileOutputStream("simple.docx")) {
doc.write(out);
}
}
}
}

View File

@ -35,42 +35,36 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
*/
public class SimpleDocumentWithHeader {
private static XWPFParagraph[] pars;
public static void main(String[] args) throws IOException {
try (XWPFDocument doc = new XWPFDocument()) {
public static void main(String[] args) {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
r.setText("Some Text");
r.setBold(true);
r = p.createRun();
r.setText("Goodbye");
XWPFRun r = p.createRun();
r.setText("Some Text");
r.setBold(true);
r = p.createRun();
r.setText("Goodbye");
CTP ctP = CTP.Factory.newInstance();
CTText t = ctP.addNewR().addNewT();
t.setStringValue("header");
XWPFParagraph[] pars = new XWPFParagraph[1];
p = new XWPFParagraph(ctP, doc);
pars[0] = p;
CTP ctP = CTP.Factory.newInstance();
CTText t = ctP.addNewR().addNewT();
t.setStringValue("header");
pars = new XWPFParagraph[1];
p = new XWPFParagraph(ctP, doc);
pars[0] = p;
XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
ctP = CTP.Factory.newInstance();
t = ctP.addNewR().addNewT();
t.setStringValue("My Footer");
pars[0] = new XWPFParagraph(ctP, doc);
hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
try {
OutputStream os = new FileOutputStream(new File("header.docx"));
doc.write(os);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ctP = CTP.Factory.newInstance();
t = ctP.addNewR().addNewT();
t.setStringValue("My Footer");
pars[0] = new XWPFParagraph(ctP, doc);
hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
try (OutputStream os = new FileOutputStream(new File("header.docx"))) {
doc.write(os);
}
}
}
}

View File

@ -35,41 +35,41 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
public class SimpleImages {
public static void main(String[] args) throws IOException, InvalidFormatException {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();
try (XWPFDocument doc = new XWPFDocument()) {
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
XWPFRun r = p.createRun();
for(String imgFile : args) {
int format;
for (String imgFile : args) {
int format;
if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
else {
System.err.println("Unsupported picture: " + imgFile +
". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
continue;
if (imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
else if (imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
else if (imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
else if (imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
else if (imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
else if (imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
else if (imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
else if (imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
else if (imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
else if (imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
else {
System.err.println("Unsupported picture: " + imgFile +
". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
continue;
}
r.setText(imgFile);
r.addBreak();
r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
r.addBreak(BreakType.PAGE);
}
r.setText(imgFile);
r.addBreak();
r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
r.addBreak(BreakType.PAGE);
try (FileOutputStream out = new FileOutputStream("images.docx")) {
doc.write(out);
}
}
FileOutputStream out = new FileOutputStream("images.docx");
doc.write(out);
out.close();
doc.close();
}

View File

@ -69,9 +69,7 @@ public class SimpleTable {
}
public static void createSimpleTable() throws Exception {
XWPFDocument doc = new XWPFDocument();
try {
try (XWPFDocument doc = new XWPFDocument()) {
XWPFTable table = doc.createTable(3, 3);
table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");
@ -93,14 +91,9 @@ public class SimpleTable {
table.getRow(2).getCell(2).setText("only text");
OutputStream out = new FileOutputStream("simpleTable.docx");
try {
try (OutputStream out = new FileOutputStream("simpleTable.docx")) {
doc.write(out);
} finally {
out.close();
}
} finally {
doc.close();
}
}
@ -115,14 +108,11 @@ public class SimpleTable {
* I make no claims that this is the "right" way to do it, but it worked
* for me. Given the scarcity of XWPF examples, I thought this may prove
* instructive and give you ideas for your own solutions.
* @throws Exception
*/
public static void createStyledTable() throws Exception {
// Create a new document from scratch
XWPFDocument doc = new XWPFDocument();
try {
try (XWPFDocument doc = new XWPFDocument()) {
// -- OR --
// open an existing empty document with styles already defined
//XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
@ -201,14 +191,9 @@ public class SimpleTable {
} // for row
// write the file
OutputStream out = new FileOutputStream("styledTable.docx");
try {
try (OutputStream out = new FileOutputStream("styledTable.docx")) {
doc.write(out);
} finally {
out.close();
}
} finally {
doc.close();
}
}
}