mirror of https://github.com/apache/poi.git
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:
parent
4ac6800974
commit
ad5232f8f8
|
@ -69,7 +69,7 @@ public class OOXMLPasswordsTry implements Closeable {
|
||||||
|
|
||||||
// Try each password in turn, reporting progress
|
// Try each password in turn, reporting progress
|
||||||
String valid = null;
|
String valid = null;
|
||||||
String password = null;
|
String password;
|
||||||
while ((password = r.readLine()) != null) {
|
while ((password = r.readLine()) != null) {
|
||||||
if (isValid(password)) {
|
if (isValid(password)) {
|
||||||
valid = password;
|
valid = password;
|
||||||
|
|
|
@ -123,9 +123,9 @@ public class CopyCompare
|
||||||
final CopyFile cf = new CopyFile(copyFileName);
|
final CopyFile cf = new CopyFile(copyFileName);
|
||||||
r.registerListener(cf);
|
r.registerListener(cf);
|
||||||
r.setNotifyEmptyDirectories(true);
|
r.setNotifyEmptyDirectories(true);
|
||||||
FileInputStream fis = new FileInputStream(originalFileName);
|
try (FileInputStream fis = new FileInputStream(originalFileName)) {
|
||||||
r.read(fis);
|
r.read(fis);
|
||||||
fis.close();
|
}
|
||||||
|
|
||||||
/* Write the new POIFS to disk. */
|
/* Write the new POIFS to disk. */
|
||||||
cf.close();
|
cf.close();
|
||||||
|
@ -183,7 +183,7 @@ public class CopyCompare
|
||||||
for (final Entry e1 : d1) {
|
for (final Entry e1 : d1) {
|
||||||
final String n1 = e1.getName();
|
final String n1 = e1.getName();
|
||||||
if (!d2.hasEntry(n1)) {
|
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;
|
equal = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -194,8 +194,7 @@ public class CopyCompare
|
||||||
} else if (e1.isDocumentEntry() && e2.isDocumentEntry()) {
|
} else if (e1.isDocumentEntry() && e2.isDocumentEntry()) {
|
||||||
equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg);
|
equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg);
|
||||||
} else {
|
} else {
|
||||||
msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " +
|
msg.append("One of \"").append(e1).append("\" and \"").append(e2).append("\" is a ").append("document while the other one is a directory.\n");
|
||||||
"document while the other one is a directory.\n");
|
|
||||||
equal = false;
|
equal = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -208,8 +207,7 @@ public class CopyCompare
|
||||||
try {
|
try {
|
||||||
e1 = d1.getEntry(n2);
|
e1 = d1.getEntry(n2);
|
||||||
} catch (FileNotFoundException ex) {
|
} catch (FileNotFoundException ex) {
|
||||||
msg.append("Document \"" + e2 + "\" exitsts, document \"" +
|
msg.append("Document \"").append(e2).append("\" exitsts, document \"").append(e1).append("\" does not.\n");
|
||||||
e1 + "\" does not.\n");
|
|
||||||
equal = false;
|
equal = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -243,11 +241,9 @@ public class CopyCompare
|
||||||
throws NoPropertySetStreamException, MarkUnsupportedException,
|
throws NoPropertySetStreamException, MarkUnsupportedException,
|
||||||
UnsupportedEncodingException, IOException
|
UnsupportedEncodingException, IOException
|
||||||
{
|
{
|
||||||
final DocumentInputStream dis1 = new DocumentInputStream(d1);
|
try (DocumentInputStream dis1 = new DocumentInputStream(d1); DocumentInputStream dis2 = new DocumentInputStream(d2)) {
|
||||||
final DocumentInputStream dis2 = new DocumentInputStream(d2);
|
|
||||||
try {
|
|
||||||
if (PropertySet.isPropertySetStream(dis1) &&
|
if (PropertySet.isPropertySetStream(dis1) &&
|
||||||
PropertySet.isPropertySetStream(dis2)) {
|
PropertySet.isPropertySetStream(dis2)) {
|
||||||
final PropertySet ps1 = PropertySetFactory.create(dis1);
|
final PropertySet ps1 = PropertySetFactory.create(dis1);
|
||||||
final PropertySet ps2 = PropertySetFactory.create(dis2);
|
final PropertySet ps2 = PropertySetFactory.create(dis2);
|
||||||
if (!ps1.equals(ps2)) {
|
if (!ps1.equals(ps2)) {
|
||||||
|
@ -265,9 +261,6 @@ public class CopyCompare
|
||||||
}
|
}
|
||||||
} while (i1 > -1);
|
} while (i1 > -1);
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
dis2.close();
|
|
||||||
dis1.close();
|
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -339,11 +332,7 @@ public class CopyCompare
|
||||||
* copy it unmodified to the destination POIFS. */
|
* copy it unmodified to the destination POIFS. */
|
||||||
copy(poiFs, path, name, stream);
|
copy(poiFs, path, name, stream);
|
||||||
}
|
}
|
||||||
} catch (MarkUnsupportedException ex) {
|
} catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) {
|
||||||
t = ex;
|
|
||||||
} catch (IOException ex) {
|
|
||||||
t = ex;
|
|
||||||
} catch (WritingNotSupportedException ex) {
|
|
||||||
t = ex;
|
t = ex;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -57,7 +57,7 @@ public class ReadTitle
|
||||||
@Override
|
@Override
|
||||||
public void processPOIFSReaderEvent(final POIFSReaderEvent event)
|
public void processPOIFSReaderEvent(final POIFSReaderEvent event)
|
||||||
{
|
{
|
||||||
SummaryInformation si = null;
|
SummaryInformation si;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
si = (SummaryInformation)
|
si = (SummaryInformation)
|
||||||
|
|
|
@ -187,11 +187,7 @@ public class WriteAuthorAndTitle
|
||||||
* copy it unmodified to the destination POIFS. */
|
* copy it unmodified to the destination POIFS. */
|
||||||
copy(poiFs, event.getPath(), event.getName(), stream);
|
copy(poiFs, event.getPath(), event.getName(), stream);
|
||||||
}
|
}
|
||||||
} catch (MarkUnsupportedException ex) {
|
} catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) {
|
||||||
t = ex;
|
|
||||||
} catch (IOException ex) {
|
|
||||||
t = ex;
|
|
||||||
} catch (WritingNotSupportedException ex) {
|
|
||||||
t = ex;
|
t = ex;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -79,23 +79,21 @@ public class WriteTitle
|
||||||
ms.setProperty(p);
|
ms.setProperty(p);
|
||||||
|
|
||||||
/* Create the POI file system the property set is to be written to. */
|
/* 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
|
/* Create the summary information property set in the POI file
|
||||||
* handed over to the POIFS.createDocument() method as an input stream
|
* system. It is given the default name most (if not all) summary
|
||||||
* which produces the bytes making out the property set stream. */
|
* information property sets have. */
|
||||||
final InputStream is = mps.toInputStream();
|
poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);
|
||||||
|
|
||||||
/* Create the summary information property set in the POI file
|
/* Write the whole POI file system to a disk file. */
|
||||||
* system. It is given the default name most (if not all) summary
|
try (FileOutputStream fos = new FileOutputStream(fileName)) {
|
||||||
* information property sets have. */
|
poiFs.writeFilesystem(fos);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -51,28 +51,28 @@ import org.apache.poi.sl.usermodel.VerticalAlignment;
|
||||||
public final class ApacheconEU08 {
|
public final class ApacheconEU08 {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
SlideShow<?,?> ppt = new HSLFSlideShow();
|
try (SlideShow<?,?> ppt = new HSLFSlideShow()) {
|
||||||
// SlideShow<?,?> ppt = new XMLSlideShow();
|
// SlideShow<?,?> ppt = new XMLSlideShow();
|
||||||
ppt.setPageSize(new Dimension(720, 540));
|
ppt.setPageSize(new Dimension(720, 540));
|
||||||
|
|
||||||
slide1(ppt);
|
slide1(ppt);
|
||||||
slide2(ppt);
|
slide2(ppt);
|
||||||
slide3(ppt);
|
slide3(ppt);
|
||||||
slide4(ppt);
|
slide4(ppt);
|
||||||
slide5(ppt);
|
slide5(ppt);
|
||||||
slide6(ppt);
|
slide6(ppt);
|
||||||
slide7(ppt);
|
slide7(ppt);
|
||||||
slide8(ppt);
|
slide8(ppt);
|
||||||
slide9(ppt);
|
slide9(ppt);
|
||||||
slide10(ppt);
|
slide10(ppt);
|
||||||
slide11(ppt);
|
slide11(ppt);
|
||||||
slide12(ppt);
|
slide12(ppt);
|
||||||
|
|
||||||
String ext = ppt.getClass().getName().contains("HSLF") ? "ppt" : "pptx";
|
String ext = ppt.getClass().getName().contains("HSLF") ? "ppt" : "pptx";
|
||||||
FileOutputStream out = new FileOutputStream("apachecon_eu_08."+ext);
|
try (FileOutputStream out = new FileOutputStream("apachecon_eu_08." + ext)) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
ppt.close();
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void slide1(SlideShow<?,?> ppt) throws IOException {
|
public static void slide1(SlideShow<?,?> ppt) throws IOException {
|
||||||
|
|
|
@ -32,11 +32,9 @@ import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
|
||||||
public final class BulletsDemo {
|
public final class BulletsDemo {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
|
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
|
||||||
HSLFSlideShow ppt = new HSLFSlideShow();
|
|
||||||
try {
|
|
||||||
HSLFSlide slide = ppt.createSlide();
|
HSLFSlide slide = ppt.createSlide();
|
||||||
|
|
||||||
HSLFTextBox shape = new HSLFTextBox();
|
HSLFTextBox shape = new HSLFTextBox();
|
||||||
HSLFTextParagraph rt = shape.getTextParagraphs().get(0);
|
HSLFTextParagraph rt = shape.getTextParagraphs().get(0);
|
||||||
rt.getTextRuns().get(0).setFontSize(42d);
|
rt.getTextRuns().get(0).setFontSize(42d);
|
||||||
|
@ -46,19 +44,17 @@ public final class BulletsDemo {
|
||||||
rt.setBulletChar('\u263A'); //bullet character
|
rt.setBulletChar('\u263A'); //bullet character
|
||||||
shape.setText(
|
shape.setText(
|
||||||
"January\r" +
|
"January\r" +
|
||||||
"February\r" +
|
"February\r" +
|
||||||
"March\r" +
|
"March\r" +
|
||||||
"April");
|
"April");
|
||||||
slide.addShape(shape);
|
slide.addShape(shape);
|
||||||
|
|
||||||
shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide
|
shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide
|
||||||
slide.addShape(shape);
|
slide.addShape(shape);
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("bullets.ppt");
|
try (FileOutputStream out = new FileOutputStream("bullets.ppt")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,35 +32,31 @@ import org.apache.poi.hslf.usermodel.HSLFTextBox;
|
||||||
public abstract class CreateHyperlink {
|
public abstract class CreateHyperlink {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSLFSlideShow ppt = new HSLFSlideShow();
|
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
HSLFSlide slideA = ppt.createSlide();
|
HSLFSlide slideA = ppt.createSlide();
|
||||||
ppt.createSlide();
|
ppt.createSlide();
|
||||||
HSLFSlide slideC = ppt.createSlide();
|
HSLFSlide slideC = ppt.createSlide();
|
||||||
|
|
||||||
// link to a URL
|
// link to a URL
|
||||||
HSLFTextBox textBox1 = slideA.createTextBox();
|
HSLFTextBox textBox1 = slideA.createTextBox();
|
||||||
textBox1.setText("Apache POI");
|
textBox1.setText("Apache POI");
|
||||||
textBox1.setAnchor(new Rectangle(100, 100, 200, 50));
|
textBox1.setAnchor(new Rectangle(100, 100, 200, 50));
|
||||||
|
|
||||||
HSLFHyperlink link1 = textBox1.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
|
HSLFHyperlink link1 = textBox1.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
|
||||||
link1.linkToUrl("http://www.apache.org");
|
link1.linkToUrl("http://www.apache.org");
|
||||||
link1.setLabel(textBox1.getText());
|
link1.setLabel(textBox1.getText());
|
||||||
|
|
||||||
// link to another slide
|
// link to another slide
|
||||||
HSLFTextBox textBox2 = slideA.createTextBox();
|
HSLFTextBox textBox2 = slideA.createTextBox();
|
||||||
textBox2.setText("Go to slide #3");
|
textBox2.setText("Go to slide #3");
|
||||||
textBox2.setAnchor(new Rectangle(100, 300, 200, 50));
|
textBox2.setAnchor(new Rectangle(100, 300, 200, 50));
|
||||||
|
|
||||||
HSLFHyperlink link2 = textBox2.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
|
HSLFHyperlink link2 = textBox2.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink();
|
||||||
link2.linkToSlide(slideC);
|
link2.linkToSlide(slideC);
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("hyperlink.ppt");
|
try (FileOutputStream out = new FileOutputStream("hyperlink.ppt")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -52,10 +52,10 @@ public final class DataExtraction {
|
||||||
|
|
||||||
//extract all sound files embedded in this presentation
|
//extract all sound files embedded in this presentation
|
||||||
HSLFSoundData[] sound = ppt.getSoundData();
|
HSLFSoundData[] sound = ppt.getSoundData();
|
||||||
for (int i = 0; i < sound.length; i++) {
|
for (HSLFSoundData aSound : sound) {
|
||||||
String type = sound[i].getSoundType(); //*.wav
|
String type = aSound.getSoundType(); //*.wav
|
||||||
String name = sound[i].getSoundName(); //typically file name
|
String name = aSound.getSoundName(); //typically file name
|
||||||
byte[] data = sound[i].getData(); //raw bytes
|
byte[] data = aSound.getData(); //raw bytes
|
||||||
|
|
||||||
//save the sound on disk
|
//save the sound on disk
|
||||||
FileOutputStream out = new FileOutputStream(name + type);
|
FileOutputStream out = new FileOutputStream(name + type);
|
||||||
|
|
|
@ -39,36 +39,34 @@ public final class Graphics2DDemo {
|
||||||
* A simple bar chart demo
|
* A simple bar chart demo
|
||||||
*/
|
*/
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
HSLFSlideShow ppt = new HSLFSlideShow();
|
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
//bar chart data. The first value is the bar color, the second is the width
|
//bar chart data. The first value is the bar color, the second is the width
|
||||||
Object[] def = new Object[]{
|
Object[] def = new Object[]{
|
||||||
Color.yellow, 40,
|
Color.yellow, 40,
|
||||||
Color.green, 60,
|
Color.green, 60,
|
||||||
Color.gray, 30,
|
Color.gray, 30,
|
||||||
Color.red, 80,
|
Color.red, 80,
|
||||||
};
|
};
|
||||||
|
|
||||||
HSLFSlide slide = ppt.createSlide();
|
HSLFSlide slide = ppt.createSlide();
|
||||||
|
|
||||||
HSLFGroupShape group = new HSLFGroupShape();
|
HSLFGroupShape group = new HSLFGroupShape();
|
||||||
//define position of the drawing in the slide
|
//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.setAnchor(bounds);
|
||||||
group.setInteriorAnchor(new java.awt.Rectangle(0, 0, 100, 100));
|
group.setInteriorAnchor(new Rectangle(0, 0, 100, 100));
|
||||||
slide.addShape(group);
|
slide.addShape(group);
|
||||||
Graphics2D graphics = new PPGraphics2D(group);
|
Graphics2D graphics = new PPGraphics2D(group);
|
||||||
|
|
||||||
//draw a simple bar graph
|
//draw a simple bar graph
|
||||||
int x = 10, y = 10;
|
int x = 10, y = 10;
|
||||||
graphics.setFont(new Font("Arial", Font.BOLD, 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);
|
graphics.setColor(Color.black);
|
||||||
int width = ((Integer)def[i+1]).intValue();
|
int width = ((Integer) def[i + 1]).intValue();
|
||||||
graphics.drawString("Q" + idx, x-5, y+10);
|
graphics.drawString("Q" + idx, x - 5, y + 10);
|
||||||
graphics.drawString(width + "%", x + width+3, y + 10);
|
graphics.drawString(width + "%", x + width + 3, y + 10);
|
||||||
graphics.setColor((Color)def[i]);
|
graphics.setColor((Color) def[i]);
|
||||||
graphics.fill(new Rectangle(x, y, width, 10));
|
graphics.fill(new Rectangle(x, y, width, 10));
|
||||||
y += 15;
|
y += 15;
|
||||||
}
|
}
|
||||||
|
@ -76,12 +74,10 @@ public final class Graphics2DDemo {
|
||||||
graphics.setFont(new Font("Arial", Font.BOLD, 14));
|
graphics.setFont(new Font("Arial", Font.BOLD, 14));
|
||||||
graphics.draw(group.getInteriorAnchor());
|
graphics.draw(group.getInteriorAnchor());
|
||||||
graphics.drawString("Performance", x + 30, y + 10);
|
graphics.drawString("Performance", x + 30, y + 10);
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("hslf-graphics.ppt");
|
try (FileOutputStream out = new FileOutputStream("hslf-graphics.ppt")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,25 +27,21 @@ import org.apache.poi.hslf.usermodel.HSLFSlideShow;
|
||||||
*/
|
*/
|
||||||
public abstract class HeadersFootersDemo {
|
public abstract class HeadersFootersDemo {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSLFSlideShow ppt = new HSLFSlideShow();
|
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
HeadersFooters slideHeaders = ppt.getSlideHeadersFooters();
|
HeadersFooters slideHeaders = ppt.getSlideHeadersFooters();
|
||||||
slideHeaders.setFootersText("Created by POI-HSLF");
|
slideHeaders.setFootersText("Created by POI-HSLF");
|
||||||
slideHeaders.setSlideNumberVisible(true);
|
slideHeaders.setSlideNumberVisible(true);
|
||||||
slideHeaders.setDateTimeText("custom date time");
|
slideHeaders.setDateTimeText("custom date time");
|
||||||
|
|
||||||
HeadersFooters notesHeaders = ppt.getNotesHeadersFooters();
|
HeadersFooters notesHeaders = ppt.getNotesHeadersFooters();
|
||||||
notesHeaders.setFootersText("My notes footers");
|
notesHeaders.setFootersText("My notes footers");
|
||||||
notesHeaders.setHeaderText("My notes header");
|
notesHeaders.setHeaderText("My notes header");
|
||||||
|
|
||||||
ppt.createSlide();
|
ppt.createSlide();
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("headers_footers.ppt");
|
try (FileOutputStream out = new FileOutputStream("headers_footers.ppt")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -37,8 +37,8 @@ import org.apache.poi.hslf.usermodel.HSLFTextRun;
|
||||||
public final class Hyperlinks {
|
public final class Hyperlinks {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
for (int i = 0; i < args.length; i++) {
|
for (String arg : args) {
|
||||||
FileInputStream is = new FileInputStream(args[i]);
|
FileInputStream is = new FileInputStream(arg);
|
||||||
HSLFSlideShow ppt = new HSLFSlideShow(is);
|
HSLFSlideShow ppt = new HSLFSlideShow(is);
|
||||||
is.close();
|
is.close();
|
||||||
|
|
||||||
|
@ -64,7 +64,7 @@ public final class Hyperlinks {
|
||||||
System.out.println("- reading hyperlinks from the slide's shapes");
|
System.out.println("- reading hyperlinks from the slide's shapes");
|
||||||
for (HSLFShape sh : slide.getShapes()) {
|
for (HSLFShape sh : slide.getShapes()) {
|
||||||
if (sh instanceof HSLFSimpleShape) {
|
if (sh instanceof HSLFSimpleShape) {
|
||||||
HSLFHyperlink link = ((HSLFSimpleShape)sh).getHyperlink();
|
HSLFHyperlink link = ((HSLFSimpleShape) sh).getHyperlink();
|
||||||
if (link != null) {
|
if (link != null) {
|
||||||
System.out.println(toStr(link, null));
|
System.out.println(toStr(link, null));
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,23 +30,23 @@ import org.apache.poi.hslf.usermodel.HSLFSoundData;
|
||||||
*/
|
*/
|
||||||
public class SoundFinder {
|
public class SoundFinder {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
FileInputStream fis = new FileInputStream(args[0]);
|
try (FileInputStream fis = new FileInputStream(args[0])) {
|
||||||
HSLFSlideShow ppt = new HSLFSlideShow(fis);
|
try (HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
|
||||||
HSLFSoundData[] sounds = ppt.getSoundData();
|
HSLFSoundData[] sounds = ppt.getSoundData();
|
||||||
|
|
||||||
for (HSLFSlide slide : ppt.getSlides()) {
|
for (HSLFSlide slide : ppt.getSlides()) {
|
||||||
for (HSLFShape shape : slide.getShapes()) {
|
for (HSLFShape shape : slide.getShapes()) {
|
||||||
int soundRef = getSoundReference(shape);
|
int soundRef = getSoundReference(shape);
|
||||||
if(soundRef == -1) continue;
|
if (soundRef == -1) continue;
|
||||||
|
|
||||||
|
|
||||||
System.out.println("Slide["+slide.getSlideNumber()+"], shape["+shape.getShapeId()+"], soundRef: "+soundRef);
|
System.out.println("Slide[" + slide.getSlideNumber() + "], shape[" + shape.getShapeId() + "], soundRef: " + soundRef);
|
||||||
System.out.println(" " + sounds[soundRef].getSoundName());
|
System.out.println(" " + sounds[soundRef].getSoundName());
|
||||||
System.out.println(" " + sounds[soundRef].getSoundType());
|
System.out.println(" " + sounds[soundRef].getSoundType());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ppt.close();
|
|
||||||
fis.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -54,18 +54,14 @@ public final class TableDemo {
|
||||||
|
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
HSLFSlideShow ppt = new HSLFSlideShow();
|
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
HSLFSlide slide = ppt.createSlide();
|
HSLFSlide slide = ppt.createSlide();
|
||||||
create1stTable(slide);
|
create1stTable(slide);
|
||||||
create2ndTable(slide);
|
create2ndTable(slide);
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("hslf-table.ppt");
|
try (FileOutputStream out = new FileOutputStream("hslf-table.ppt")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -157,12 +157,12 @@ public class Msg2txt {
|
||||||
if(args.length <= 0) {
|
if(args.length <= 0) {
|
||||||
System.err.println("No files names provided");
|
System.err.println("No files names provided");
|
||||||
} else {
|
} else {
|
||||||
for(int i = 0; i < args.length; i++) {
|
for (String arg : args) {
|
||||||
try {
|
try {
|
||||||
Msg2txt processor = new Msg2txt(args[i]);
|
Msg2txt processor = new Msg2txt(arg);
|
||||||
processor.processMessage();
|
processor.processMessage();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Could not process "+args[i]+": "+e);
|
System.err.println("Could not process " + arg + ": " + e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -251,10 +251,10 @@ public class AddDimensionedImage {
|
||||||
String imageFile, double reqImageWidthMM, double reqImageHeightMM,
|
String imageFile, double reqImageWidthMM, double reqImageHeightMM,
|
||||||
int resizeBehaviour) throws FileNotFoundException, IOException,
|
int resizeBehaviour) throws FileNotFoundException, IOException,
|
||||||
IllegalArgumentException {
|
IllegalArgumentException {
|
||||||
HSSFClientAnchor anchor = null;
|
HSSFClientAnchor anchor;
|
||||||
HSSFPatriarch patriarch = null;
|
HSSFPatriarch patriarch;
|
||||||
ClientAnchorDetail rowClientAnchorDetail = null;
|
ClientAnchorDetail rowClientAnchorDetail;
|
||||||
ClientAnchorDetail colClientAnchorDetail = null;
|
ClientAnchorDetail colClientAnchorDetail;
|
||||||
|
|
||||||
// Validate the resizeBehaviour parameter.
|
// Validate the resizeBehaviour parameter.
|
||||||
if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&
|
if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&
|
||||||
|
@ -334,9 +334,9 @@ public class AddDimensionedImage {
|
||||||
private ClientAnchorDetail fitImageToColumns(HSSFSheet sheet, int colNumber,
|
private ClientAnchorDetail fitImageToColumns(HSSFSheet sheet, int colNumber,
|
||||||
double reqImageWidthMM, int resizeBehaviour) {
|
double reqImageWidthMM, int resizeBehaviour) {
|
||||||
|
|
||||||
double colWidthMM = 0.0D;
|
double colWidthMM;
|
||||||
double colCoordinatesPerMM = 0.0D;
|
double colCoordinatesPerMM;
|
||||||
int pictureWidthCoordinates = 0;
|
int pictureWidthCoordinates;
|
||||||
ClientAnchorDetail colClientAnchorDetail = null;
|
ClientAnchorDetail colClientAnchorDetail = null;
|
||||||
|
|
||||||
// Get the colum's width in millimetres
|
// Get the colum's width in millimetres
|
||||||
|
@ -417,21 +417,19 @@ public class AddDimensionedImage {
|
||||||
*/
|
*/
|
||||||
private ClientAnchorDetail fitImageToRows(HSSFSheet sheet, int rowNumber,
|
private ClientAnchorDetail fitImageToRows(HSSFSheet sheet, int rowNumber,
|
||||||
double reqImageHeightMM, int resizeBehaviour) {
|
double reqImageHeightMM, int resizeBehaviour) {
|
||||||
HSSFRow row = null;
|
double rowCoordinatesPerMM;
|
||||||
double rowHeightMM = 0.0D;
|
int pictureHeightCoordinates;
|
||||||
double rowCoordinatesPerMM = 0.0D;
|
|
||||||
int pictureHeightCoordinates = 0;
|
|
||||||
ClientAnchorDetail rowClientAnchorDetail = null;
|
ClientAnchorDetail rowClientAnchorDetail = null;
|
||||||
|
|
||||||
// Get the row and it's height
|
// Get the row and it's height
|
||||||
row = sheet.getRow(rowNumber);
|
HSSFRow row = sheet.getRow(rowNumber);
|
||||||
if(row == null) {
|
if(row == null) {
|
||||||
// Create row if it does not exist.
|
// Create row if it does not exist.
|
||||||
row = sheet.createRow(rowNumber);
|
row = sheet.createRow(rowNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the row's height in millimetres
|
// 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
|
// 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
|
// 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,
|
private ClientAnchorDetail calculateColumnLocation(HSSFSheet sheet,
|
||||||
int startingColumn,
|
int startingColumn,
|
||||||
double reqImageWidthMM) {
|
double reqImageWidthMM) {
|
||||||
ClientAnchorDetail anchorDetail = null;
|
ClientAnchorDetail anchorDetail;
|
||||||
double totalWidthMM = 0.0D;
|
double totalWidthMM = 0.0D;
|
||||||
double colWidthMM = 0.0D;
|
double colWidthMM = 0.0D;
|
||||||
double overlapMM = 0.0D;
|
double overlapMM;
|
||||||
double coordinatePositionsPerMM = 0.0D;
|
double coordinatePositionsPerMM;
|
||||||
int toColumn = startingColumn;
|
int toColumn = startingColumn;
|
||||||
int inset = 0;
|
int inset;
|
||||||
|
|
||||||
// Calculate how many columns the image will have to
|
// Calculate how many columns the image will have to
|
||||||
// span in order to be presented at the required size.
|
// span in order to be presented at the required size.
|
||||||
|
@ -593,14 +591,14 @@ public class AddDimensionedImage {
|
||||||
*/
|
*/
|
||||||
private ClientAnchorDetail calculateRowLocation(HSSFSheet sheet,
|
private ClientAnchorDetail calculateRowLocation(HSSFSheet sheet,
|
||||||
int startingRow, double reqImageHeightMM) {
|
int startingRow, double reqImageHeightMM) {
|
||||||
ClientAnchorDetail clientAnchorDetail = null;
|
ClientAnchorDetail clientAnchorDetail;
|
||||||
HSSFRow row = null;
|
HSSFRow row;
|
||||||
double rowHeightMM = 0.0D;
|
double rowHeightMM = 0.0D;
|
||||||
double totalRowHeightMM = 0.0D;
|
double totalRowHeightMM = 0.0D;
|
||||||
double overlapMM = 0.0D;
|
double overlapMM;
|
||||||
double rowCoordinatesPerMM = 0.0D;
|
double rowCoordinatesPerMM;
|
||||||
int toRow = startingRow;
|
int toRow = startingRow;
|
||||||
int inset = 0;
|
int inset;
|
||||||
|
|
||||||
// Step through the rows in the sheet and accumulate a total of their
|
// Step through the rows in the sheet and accumulate a total of their
|
||||||
// heights.
|
// heights.
|
||||||
|
@ -672,10 +670,10 @@ public class AddDimensionedImage {
|
||||||
* interrupted.
|
* interrupted.
|
||||||
*/
|
*/
|
||||||
private byte[] imageToBytes(String imageFilename) throws IOException {
|
private byte[] imageToBytes(String imageFilename) throws IOException {
|
||||||
File imageFile = null;
|
File imageFile;
|
||||||
FileInputStream fis = null;
|
FileInputStream fis = null;
|
||||||
ByteArrayOutputStream bos = null;
|
ByteArrayOutputStream bos;
|
||||||
int read = 0;
|
int read;
|
||||||
try {
|
try {
|
||||||
imageFile = new File(imageFilename);
|
imageFile = new File(imageFilename);
|
||||||
fis = new FileInputStream(imageFile);
|
fis = new FileInputStream(imageFile);
|
||||||
|
@ -718,10 +716,10 @@ public class AddDimensionedImage {
|
||||||
* @param args the command line arguments
|
* @param args the command line arguments
|
||||||
*/
|
*/
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
String imageFile = null;
|
String imageFile;
|
||||||
String outputFile = null;
|
String outputFile;
|
||||||
FileOutputStream fos = null;
|
FileOutputStream fos = null;
|
||||||
HSSFSheet sheet = null;
|
HSSFSheet sheet;
|
||||||
try {
|
try {
|
||||||
if(args.length < 2){
|
if(args.length < 2){
|
||||||
System.err.println("Usage: AddDimensionedImage imageFile outputFile");
|
System.err.println("Usage: AddDimensionedImage imageFile outputFile");
|
||||||
|
@ -730,25 +728,15 @@ public class AddDimensionedImage {
|
||||||
imageFile = args[0];
|
imageFile = args[0];
|
||||||
outputFile = args[1];
|
outputFile = args[1];
|
||||||
|
|
||||||
HSSFWorkbook workbook = new HSSFWorkbook();
|
try (HSSFWorkbook workbook = new HSSFWorkbook()) {
|
||||||
try {
|
|
||||||
sheet = workbook.createSheet("Picture Test");
|
sheet = workbook.createSheet("Picture Test");
|
||||||
new AddDimensionedImage().addImageToSheet("A1", sheet,
|
new AddDimensionedImage().addImageToSheet("A1", sheet,
|
||||||
imageFile, 125, 125,
|
imageFile, 125, 125,
|
||||||
AddDimensionedImage.EXPAND_ROW_AND_COLUMN);
|
AddDimensionedImage.EXPAND_ROW_AND_COLUMN);
|
||||||
fos = new FileOutputStream(outputFile);
|
fos = new FileOutputStream(outputFile);
|
||||||
workbook.write(fos);
|
workbook.write(fos);
|
||||||
} finally {
|
|
||||||
workbook.close();
|
|
||||||
}
|
}
|
||||||
}
|
} catch(IOException ioEx) {
|
||||||
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) {
|
|
||||||
System.out.println("Caught an: " + ioEx.getClass().getName());
|
System.out.println("Caught an: " + ioEx.getClass().getName());
|
||||||
System.out.println("Message: " + ioEx.getMessage());
|
System.out.println("Message: " + ioEx.getMessage());
|
||||||
System.out.println("Stacktrace follows...........");
|
System.out.println("Stacktrace follows...........");
|
||||||
|
|
|
@ -36,23 +36,22 @@ import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||||
*/
|
*/
|
||||||
public class Alignment {
|
public class Alignment {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
HSSFRow row = sheet.createRow(2);
|
HSSFRow row = sheet.createRow(2);
|
||||||
createCell(wb, row, 0, HorizontalAlignment.CENTER);
|
createCell(wb, row, 0, HorizontalAlignment.CENTER);
|
||||||
createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION);
|
createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION);
|
||||||
createCell(wb, row, 2, HorizontalAlignment.FILL);
|
createCell(wb, row, 2, HorizontalAlignment.FILL);
|
||||||
createCell(wb, row, 3, HorizontalAlignment.GENERAL);
|
createCell(wb, row, 3, HorizontalAlignment.GENERAL);
|
||||||
createCell(wb, row, 4, HorizontalAlignment.JUSTIFY);
|
createCell(wb, row, 4, HorizontalAlignment.JUSTIFY);
|
||||||
createCell(wb, row, 5, HorizontalAlignment.LEFT);
|
createCell(wb, row, 5, HorizontalAlignment.LEFT);
|
||||||
createCell(wb, row, 6, HorizontalAlignment.RIGHT);
|
createCell(wb, row, 6, HorizontalAlignment.RIGHT);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -39,8 +39,7 @@ public class BigExample {
|
||||||
int rownum;
|
int rownum;
|
||||||
|
|
||||||
// create a new workbook
|
// create a new workbook
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
try {
|
|
||||||
// create a new sheet
|
// create a new sheet
|
||||||
HSSFSheet s = wb.createSheet();
|
HSSFSheet s = wb.createSheet();
|
||||||
// declare a row object reference
|
// declare a row object reference
|
||||||
|
@ -54,7 +53,7 @@ public class BigExample {
|
||||||
// create 2 fonts objects
|
// create 2 fonts objects
|
||||||
HSSFFont f = wb.createFont();
|
HSSFFont f = wb.createFont();
|
||||||
HSSFFont f2 = wb.createFont();
|
HSSFFont f2 = wb.createFont();
|
||||||
|
|
||||||
//set font 1 to 12 point type
|
//set font 1 to 12 point type
|
||||||
f.setFontHeightInPoints((short) 12);
|
f.setFontHeightInPoints((short) 12);
|
||||||
//make it red
|
//make it red
|
||||||
|
@ -62,118 +61,110 @@ public class BigExample {
|
||||||
// make it bold
|
// make it bold
|
||||||
//arial is the default font
|
//arial is the default font
|
||||||
f.setBold(true);
|
f.setBold(true);
|
||||||
|
|
||||||
//set font 2 to 10 point type
|
//set font 2 to 10 point type
|
||||||
f2.setFontHeightInPoints((short) 10);
|
f2.setFontHeightInPoints((short) 10);
|
||||||
//make it the color at palette index 0xf (white)
|
//make it the color at palette index 0xf (white)
|
||||||
f2.setColor(HSSFColorPredefined.WHITE.getIndex());
|
f2.setColor(HSSFColorPredefined.WHITE.getIndex());
|
||||||
//make it bold
|
//make it bold
|
||||||
f2.setBold(true);
|
f2.setBold(true);
|
||||||
|
|
||||||
//set cell stlye
|
//set cell stlye
|
||||||
cs.setFont(f);
|
cs.setFont(f);
|
||||||
//set the cell format see HSSFDataFromat for a full list
|
//set the cell format see HSSFDataFromat for a full list
|
||||||
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
|
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
|
||||||
|
|
||||||
//set a thin border
|
//set a thin border
|
||||||
cs2.setBorderBottom(BorderStyle.THIN);
|
cs2.setBorderBottom(BorderStyle.THIN);
|
||||||
//fill w fg fill color
|
//fill w fg fill color
|
||||||
cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||||
// set foreground fill to red
|
// set foreground fill to red
|
||||||
cs2.setFillForegroundColor(HSSFColorPredefined.RED.getIndex());
|
cs2.setFillForegroundColor(HSSFColorPredefined.RED.getIndex());
|
||||||
|
|
||||||
// set the font
|
// set the font
|
||||||
cs2.setFont(f2);
|
cs2.setFont(f2);
|
||||||
|
|
||||||
// set the sheet name to HSSF Test
|
// set the sheet name to HSSF Test
|
||||||
wb.setSheetName(0, "HSSF Test");
|
wb.setSheetName(0, "HSSF Test");
|
||||||
// create a sheet with 300 rows (0-299)
|
// create a sheet with 300 rows (0-299)
|
||||||
for (rownum = 0; rownum < 300; rownum++)
|
for (rownum = 0; rownum < 300; rownum++) {
|
||||||
{
|
|
||||||
// create a row
|
// create a row
|
||||||
r = s.createRow(rownum);
|
r = s.createRow(rownum);
|
||||||
// on every other row
|
// on every other row
|
||||||
if ((rownum % 2) == 0)
|
if ((rownum % 2) == 0) {
|
||||||
{
|
|
||||||
// make the row height bigger (in twips - 1/20 of a point)
|
// make the row height bigger (in twips - 1/20 of a point)
|
||||||
r.setHeight((short) 0x249);
|
r.setHeight((short) 0x249);
|
||||||
}
|
}
|
||||||
|
|
||||||
//r.setRowNum(( short ) rownum);
|
//r.setRowNum(( short ) rownum);
|
||||||
// create 50 cells (0-49) (the += 2 becomes apparent later
|
// 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
|
// create a numeric cell
|
||||||
c = r.createCell(cellnum);
|
c = r.createCell(cellnum);
|
||||||
// do some goofy math to demonstrate decimals
|
// do some goofy math to demonstrate decimals
|
||||||
c.setCellValue(rownum * 10000 + cellnum
|
c.setCellValue(rownum * 10000 + cellnum
|
||||||
+ (((double) rownum / 1000)
|
+ (((double) rownum / 1000)
|
||||||
+ ((double) cellnum / 10000)));
|
+ ((double) cellnum / 10000)));
|
||||||
|
|
||||||
// on every other row
|
// on every other row
|
||||||
if ((rownum % 2) == 0)
|
if ((rownum % 2) == 0) {
|
||||||
{
|
|
||||||
// set this cell to the first cell style we defined
|
// set this cell to the first cell style we defined
|
||||||
c.setCellStyle(cs);
|
c.setCellStyle(cs);
|
||||||
}
|
}
|
||||||
|
|
||||||
// create a string cell (see why += 2 in the
|
// create a string cell (see why += 2 in the
|
||||||
c = r.createCell(cellnum + 1);
|
c = r.createCell(cellnum + 1);
|
||||||
|
|
||||||
// set the cell's string value to "TEST"
|
// set the cell's string value to "TEST"
|
||||||
c.setCellValue("TEST");
|
c.setCellValue("TEST");
|
||||||
// make this column a bit wider
|
// 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
|
// on every other row
|
||||||
if ((rownum % 2) == 0)
|
if ((rownum % 2) == 0) {
|
||||||
{
|
|
||||||
// set this to the white on red cell style
|
// set this to the white on red cell style
|
||||||
// we defined above
|
// we defined above
|
||||||
c.setCellStyle(cs2);
|
c.setCellStyle(cs2);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//draw a thick black border on the row at the bottom using BLANKS
|
//draw a thick black border on the row at the bottom using BLANKS
|
||||||
// advance 2 rows
|
// advance 2 rows
|
||||||
rownum++;
|
rownum++;
|
||||||
rownum++;
|
rownum++;
|
||||||
|
|
||||||
r = s.createRow(rownum);
|
r = s.createRow(rownum);
|
||||||
|
|
||||||
// define the third style to be the default
|
// define the third style to be the default
|
||||||
// except with a thick black border at the bottom
|
// except with a thick black border at the bottom
|
||||||
cs3.setBorderBottom(BorderStyle.THICK);
|
cs3.setBorderBottom(BorderStyle.THICK);
|
||||||
|
|
||||||
//create 50 cells
|
//create 50 cells
|
||||||
for (int cellnum =0; cellnum < 50; cellnum++) {
|
for (int cellnum = 0; cellnum < 50; cellnum++) {
|
||||||
//create a blank type cell (no value)
|
//create a blank type cell (no value)
|
||||||
c = r.createCell(cellnum);
|
c = r.createCell(cellnum);
|
||||||
// set it to the thick black border style
|
// set it to the thick black border style
|
||||||
c.setCellStyle(cs3);
|
c.setCellStyle(cs3);
|
||||||
}
|
}
|
||||||
|
|
||||||
//end draw thick black border
|
//end draw thick black border
|
||||||
|
|
||||||
|
|
||||||
// demonstrate adding/naming and deleting a sheet
|
// demonstrate adding/naming and deleting a sheet
|
||||||
// create a sheet, set its title then delete it
|
// create a sheet, set its title then delete it
|
||||||
wb.createSheet();
|
wb.createSheet();
|
||||||
wb.setSheetName(1, "DeletedSheet");
|
wb.setSheetName(1, "DeletedSheet");
|
||||||
wb.removeSheetAt(1);
|
wb.removeSheetAt(1);
|
||||||
//end deleted sheet
|
//end deleted sheet
|
||||||
|
|
||||||
// create a new file
|
// create a new file
|
||||||
FileOutputStream out = new FileOutputStream("workbook.xls");
|
try (FileOutputStream out = new FileOutputStream("workbook.xls")) {
|
||||||
|
// write the workbook to the output stream
|
||||||
// write the workbook to the output stream
|
// close our file (don't blow out our file handles
|
||||||
// close our file (don't blow out our file handles
|
wb.write(out);
|
||||||
wb.write(out);
|
}
|
||||||
out.close();
|
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,8 +33,7 @@ import org.apache.poi.ss.usermodel.BorderStyle;
|
||||||
*/
|
*/
|
||||||
public class Borders {
|
public class Borders {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
try {
|
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
|
@ -57,11 +56,9 @@ public class Borders {
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -39,68 +39,64 @@ import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
|
||||||
public class CellComments {
|
public class CellComments {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
|
||||||
try {
|
|
||||||
HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF");
|
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.
|
// Create the drawing patriarch. This is the top level container for all shapes including cell comments.
|
||||||
HSSFPatriarch patr = sheet.createDrawingPatriarch();
|
HSSFPatriarch patr = sheet.createDrawingPatriarch();
|
||||||
|
|
||||||
//create a cell in row 3
|
//create a cell in row 3
|
||||||
HSSFCell cell1 = sheet.createRow(3).createCell(1);
|
HSSFCell cell1 = sheet.createRow(3).createCell(1);
|
||||||
cell1.setCellValue(new HSSFRichTextString("Hello, World"));
|
cell1.setCellValue(new HSSFRichTextString("Hello, World"));
|
||||||
|
|
||||||
//anchor defines size and position of the comment in worksheet
|
//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));
|
HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
|
||||||
|
|
||||||
// set text in the comment
|
// set text in the comment
|
||||||
comment1.setString(new HSSFRichTextString("We can set comments in POI"));
|
comment1.setString(new HSSFRichTextString("We can set comments in POI"));
|
||||||
|
|
||||||
//set comment author.
|
//set comment author.
|
||||||
//you can see it in the status bar when moving mouse over the commented cell
|
//you can see it in the status bar when moving mouse over the commented cell
|
||||||
comment1.setAuthor("Apache Software Foundation");
|
comment1.setAuthor("Apache Software Foundation");
|
||||||
|
|
||||||
// The first way to assign comment to a cell is via HSSFCell.setCellComment method
|
// The first way to assign comment to a cell is via HSSFCell.setCellComment method
|
||||||
cell1.setCellComment(comment1);
|
cell1.setCellComment(comment1);
|
||||||
|
|
||||||
//create another cell in row 6
|
//create another cell in row 6
|
||||||
HSSFCell cell2 = sheet.createRow(6).createCell(1);
|
HSSFCell cell2 = sheet.createRow(6).createCell(1);
|
||||||
cell2.setCellValue(36.6);
|
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
|
//modify background color of the comment
|
||||||
comment2.setFillColor(204, 236, 255);
|
comment2.setFillColor(204, 236, 255);
|
||||||
|
|
||||||
HSSFRichTextString string = new HSSFRichTextString("Normal body temperature");
|
HSSFRichTextString string = new HSSFRichTextString("Normal body temperature");
|
||||||
|
|
||||||
//apply custom font to the text in the comment
|
//apply custom font to the text in the comment
|
||||||
HSSFFont font = wb.createFont();
|
HSSFFont font = wb.createFont();
|
||||||
font.setFontName("Arial");
|
font.setFontName("Arial");
|
||||||
font.setFontHeightInPoints((short)10);
|
font.setFontHeightInPoints((short) 10);
|
||||||
font.setBold(true);
|
font.setBold(true);
|
||||||
font.setColor(HSSFColorPredefined.RED.getIndex());
|
font.setColor(HSSFColorPredefined.RED.getIndex());
|
||||||
string.applyFont(font);
|
string.applyFont(font);
|
||||||
|
|
||||||
comment2.setString(string);
|
comment2.setString(string);
|
||||||
comment2.setVisible(true); //by default comments are hidden. This one is always visible.
|
comment2.setVisible(true); //by default comments are hidden. This one is always visible.
|
||||||
|
|
||||||
comment2.setAuthor("Bill Gates");
|
comment2.setAuthor("Bill Gates");
|
||||||
|
|
||||||
/**
|
/*
|
||||||
* The second way to assign comment to a cell is to implicitly specify its row and column.
|
* 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.
|
* Note, it is possible to set row and column of a non-existing cell.
|
||||||
* It works, the comment is visible.
|
* It works, the comment is visible.
|
||||||
*/
|
*/
|
||||||
comment2.setRow(6);
|
comment2.setRow(6);
|
||||||
comment2.setColumn(1);
|
comment2.setColumn(1);
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("poi_comment.xls");
|
try (FileOutputStream out = new FileOutputStream("poi_comment.xls")) {
|
||||||
wb.write(out);
|
wb.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,8 +28,7 @@ import org.apache.poi.ss.usermodel.CellType;
|
||||||
|
|
||||||
public class CellTypes {
|
public class CellTypes {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
try {
|
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
HSSFRow row = sheet.createRow(2);
|
HSSFRow row = sheet.createRow(2);
|
||||||
row.createCell(0).setCellValue(1.1);
|
row.createCell(0).setCellValue(1.1);
|
||||||
|
@ -37,13 +36,11 @@ public class CellTypes {
|
||||||
row.createCell(2).setCellValue("a string");
|
row.createCell(2).setCellValue("a string");
|
||||||
row.createCell(3).setCellValue(true);
|
row.createCell(3).setCellValue(true);
|
||||||
row.createCell(4).setCellType(CellType.ERROR);
|
row.createCell(4).setCellType(CellType.ERROR);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,25 +32,24 @@ import java.io.IOException;
|
||||||
*/
|
*/
|
||||||
public class CreateCells {
|
public class CreateCells {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
HSSFRow row = sheet.createRow(0);
|
HSSFRow row = sheet.createRow(0);
|
||||||
// Create a cell and put a value in it.
|
// Create a cell and put a value in it.
|
||||||
HSSFCell cell = row.createCell(0);
|
HSSFCell cell = row.createCell(0);
|
||||||
cell.setCellValue(1);
|
cell.setCellValue(1);
|
||||||
|
|
||||||
// Or do it on one line.
|
// Or do it on one line.
|
||||||
row.createCell(1).setCellValue(1.2);
|
row.createCell(1).setCellValue(1.2);
|
||||||
row.createCell(2).setCellValue("This is a string");
|
row.createCell(2).setCellValue("This is a string");
|
||||||
row.createCell(3).setCellValue(true);
|
row.createCell(3).setCellValue(true);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,29 +35,28 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class CreateDateCells {
|
public class CreateDateCells {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
HSSFRow row = sheet.createRow(0);
|
HSSFRow row = sheet.createRow(0);
|
||||||
|
|
||||||
// Create a cell and put a date value in it. The first cell is not styled as a 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);
|
HSSFCell cell = row.createCell(0);
|
||||||
cell.setCellValue(new Date());
|
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
|
// 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.
|
// otherwise you can end up modifying the built in style and effecting not only this cell but other cells.
|
||||||
HSSFCellStyle cellStyle = wb.createCellStyle();
|
HSSFCellStyle cellStyle = wb.createCellStyle();
|
||||||
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
|
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
|
||||||
cell = row.createCell(1);
|
cell = row.createCell(1);
|
||||||
cell.setCellValue(new Date());
|
cell.setCellValue(new Date());
|
||||||
cell.setCellStyle(cellStyle);
|
cell.setCellStyle(cellStyle);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,34 +34,34 @@ public class EmbeddedObjects {
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));
|
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));
|
||||||
HSSFWorkbook workbook = new HSSFWorkbook(fs);
|
try (HSSFWorkbook workbook = new HSSFWorkbook(fs)) {
|
||||||
for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
|
for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
|
||||||
//the OLE2 Class Name of the object
|
//the OLE2 Class Name of the object
|
||||||
String oleName = obj.getOLE2ClassName();
|
String oleName = obj.getOLE2ClassName();
|
||||||
DirectoryNode dn = (obj.hasDirectoryEntry()) ? (DirectoryNode) obj.getDirectory() : null;
|
DirectoryNode dn = (obj.hasDirectoryEntry()) ? (DirectoryNode) obj.getDirectory() : null;
|
||||||
Closeable document = null;
|
Closeable document = null;
|
||||||
if (oleName.equals("Worksheet")) {
|
if (oleName.equals("Worksheet")) {
|
||||||
document = new HSSFWorkbook(dn, fs, false);
|
document = new HSSFWorkbook(dn, fs, false);
|
||||||
} else if (oleName.equals("Document")) {
|
} else if (oleName.equals("Document")) {
|
||||||
document = new HWPFDocument(dn);
|
document = new HWPFDocument(dn);
|
||||||
} else if (oleName.equals("Presentation")) {
|
} else if (oleName.equals("Presentation")) {
|
||||||
document = new HSLFSlideShow(dn);
|
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();
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
// There is no DirectoryEntry
|
if (dn != null) {
|
||||||
// Recover the object's data from the HSSFObjectData instance.
|
// The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
|
||||||
byte[] objectData = obj.getObjectData();
|
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,9 +31,7 @@ import java.io.InputStream;
|
||||||
/**
|
/**
|
||||||
* This example shows how to use the event API for reading a file.
|
* This example shows how to use the event API for reading a file.
|
||||||
*/
|
*/
|
||||||
public class EventExample
|
public class EventExample implements HSSFListener {
|
||||||
implements HSSFListener
|
|
||||||
{
|
|
||||||
private SSTRecord sstrec;
|
private SSTRecord sstrec;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -97,24 +95,22 @@ public class EventExample
|
||||||
{
|
{
|
||||||
// create a new file input stream with the input file specified
|
// create a new file input stream with the input file specified
|
||||||
// at the command line
|
// at the command line
|
||||||
FileInputStream fin = new FileInputStream(args[0]);
|
try (FileInputStream fin = new FileInputStream(args[0])) {
|
||||||
// create a new org.apache.poi.poifs.filesystem.Filesystem
|
// create a new org.apache.poi.poifs.filesystem.Filesystem
|
||||||
POIFSFileSystem poifs = new POIFSFileSystem(fin);
|
try (POIFSFileSystem poifs = new POIFSFileSystem(fin)) {
|
||||||
// get the Workbook (excel part) stream in a InputStream
|
// get the Workbook (excel part) stream in a InputStream
|
||||||
InputStream din = poifs.createDocumentInputStream("Workbook");
|
try (InputStream din = poifs.createDocumentInputStream("Workbook")) {
|
||||||
// construct out HSSFRequest object
|
// construct out HSSFRequest object
|
||||||
HSSFRequest req = new HSSFRequest();
|
HSSFRequest req = new HSSFRequest();
|
||||||
// lazy listen for ALL records with the listener shown above
|
// lazy listen for ALL records with the listener shown above
|
||||||
req.addListenerForAllRecords(new EventExample());
|
req.addListenerForAllRecords(new EventExample());
|
||||||
// create our event factory
|
// create our event factory
|
||||||
HSSFEventFactory factory = new HSSFEventFactory();
|
HSSFEventFactory factory = new HSSFEventFactory();
|
||||||
// process our events based on the document input stream
|
// process our events based on the document input stream
|
||||||
factory.processEvents(req, din);
|
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();
|
|
||||||
System.out.println("done.");
|
System.out.println("done.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,33 +33,32 @@ import org.apache.poi.ss.usermodel.FillPatternType;
|
||||||
*/
|
*/
|
||||||
public class FrillsAndFills {
|
public class FrillsAndFills {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
HSSFRow row = sheet.createRow(1);
|
HSSFRow row = sheet.createRow(1);
|
||||||
|
|
||||||
// Aqua background
|
// Aqua background
|
||||||
HSSFCellStyle style = wb.createCellStyle();
|
HSSFCellStyle style = wb.createCellStyle();
|
||||||
style.setFillBackgroundColor(HSSFColorPredefined.AQUA.getIndex());
|
style.setFillBackgroundColor(HSSFColorPredefined.AQUA.getIndex());
|
||||||
style.setFillPattern(FillPatternType.BIG_SPOTS);
|
style.setFillPattern(FillPatternType.BIG_SPOTS);
|
||||||
HSSFCell cell = row.createCell(1);
|
HSSFCell cell = row.createCell(1);
|
||||||
cell.setCellValue("X");
|
cell.setCellValue("X");
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
// Orange "foreground", foreground being the fill foreground not the font color.
|
// Orange "foreground", foreground being the fill foreground not the font color.
|
||||||
style = wb.createCellStyle();
|
style = wb.createCellStyle();
|
||||||
style.setFillForegroundColor(HSSFColorPredefined.ORANGE.getIndex());
|
style.setFillForegroundColor(HSSFColorPredefined.ORANGE.getIndex());
|
||||||
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||||
cell = row.createCell(2);
|
cell = row.createCell(2);
|
||||||
cell.setCellValue("X");
|
cell.setCellValue("X");
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -47,12 +47,9 @@ public final class HSSFReadWrite {
|
||||||
* creates an {@link HSSFWorkbook} with the specified OS filename.
|
* creates an {@link HSSFWorkbook} with the specified OS filename.
|
||||||
*/
|
*/
|
||||||
private static HSSFWorkbook readFile(String filename) throws IOException {
|
private static HSSFWorkbook readFile(String filename) throws IOException {
|
||||||
FileInputStream fis = new FileInputStream(filename);
|
try (FileInputStream fis = new FileInputStream(filename)) {
|
||||||
try {
|
return new HSSFWorkbook(fis); // NOSONAR - should not be closed here
|
||||||
return new HSSFWorkbook(fis); // NOSONAR - should not be closed here
|
}
|
||||||
} finally {
|
|
||||||
fis.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -60,8 +57,7 @@ public final class HSSFReadWrite {
|
||||||
* rows/cells.
|
* rows/cells.
|
||||||
*/
|
*/
|
||||||
private static void testCreateSampleSheet(String outputFilename) throws IOException {
|
private static void testCreateSampleSheet(String outputFilename) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
try {
|
|
||||||
HSSFSheet s = wb.createSheet();
|
HSSFSheet s = wb.createSheet();
|
||||||
HSSFCellStyle cs = wb.createCellStyle();
|
HSSFCellStyle cs = wb.createCellStyle();
|
||||||
HSSFCellStyle cs2 = wb.createCellStyle();
|
HSSFCellStyle cs2 = wb.createCellStyle();
|
||||||
|
@ -125,14 +121,9 @@ public final class HSSFReadWrite {
|
||||||
wb.removeSheetAt(1);
|
wb.removeSheetAt(1);
|
||||||
|
|
||||||
// end deleted sheet
|
// end deleted sheet
|
||||||
FileOutputStream out = new FileOutputStream(outputFilename);
|
try (FileOutputStream out = new FileOutputStream(outputFilename)) {
|
||||||
try {
|
|
||||||
wb.write(out);
|
wb.write(out);
|
||||||
} finally {
|
|
||||||
out.close();
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -166,9 +157,7 @@ public final class HSSFReadWrite {
|
||||||
try {
|
try {
|
||||||
if (args.length < 2) {
|
if (args.length < 2) {
|
||||||
|
|
||||||
HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
|
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
|
||||||
|
|
||||||
try {
|
|
||||||
System.out.println("Data dump:\n");
|
System.out.println("Data dump:\n");
|
||||||
|
|
||||||
for (int k = 0; k < wb.getNumberOfSheets(); k++) {
|
for (int k = 0; k < wb.getNumberOfSheets(); k++) {
|
||||||
|
@ -187,7 +176,7 @@ public final class HSSFReadWrite {
|
||||||
HSSFCell cell = row.getCell(c);
|
HSSFCell cell = row.getCell(c);
|
||||||
String value;
|
String value;
|
||||||
|
|
||||||
if(cell != null) {
|
if (cell != null) {
|
||||||
switch (cell.getCellType()) {
|
switch (cell.getCellType()) {
|
||||||
|
|
||||||
case FORMULA:
|
case FORMULA:
|
||||||
|
@ -223,8 +212,6 @@ public final class HSSFReadWrite {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
} else if (args.length == 2) {
|
} else if (args.length == 2) {
|
||||||
if (args[1].toLowerCase(Locale.ROOT).equals("write")) {
|
if (args[1].toLowerCase(Locale.ROOT).equals("write")) {
|
||||||
|
@ -236,23 +223,16 @@ public final class HSSFReadWrite {
|
||||||
+ " ms generation time");
|
+ " ms generation time");
|
||||||
} else {
|
} else {
|
||||||
System.out.println("readwrite test");
|
System.out.println("readwrite test");
|
||||||
HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
|
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
|
||||||
try {
|
try (FileOutputStream stream = new FileOutputStream(args[1])) {
|
||||||
FileOutputStream stream = new FileOutputStream(args[1]);
|
|
||||||
try {
|
|
||||||
wb.write(stream);
|
wb.write(stream);
|
||||||
} finally {
|
|
||||||
stream.close();
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (args.length == 3 && args[2].equalsIgnoreCase("modify1")) {
|
} 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!!"
|
// delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"
|
||||||
|
|
||||||
HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
|
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
|
||||||
try {
|
|
||||||
HSSFSheet sheet = wb.getSheetAt(0);
|
HSSFSheet sheet = wb.getSheetAt(0);
|
||||||
|
|
||||||
for (int k = 0; k < 25; k++) {
|
for (int k = 0; k < 25; k++) {
|
||||||
|
@ -269,14 +249,9 @@ public final class HSSFReadWrite {
|
||||||
HSSFCell cell = row.getCell(3);
|
HSSFCell cell = row.getCell(3);
|
||||||
cell.setCellValue("MODIFIED CELL!!!!!");
|
cell.setCellValue("MODIFIED CELL!!!!!");
|
||||||
|
|
||||||
FileOutputStream stream = new FileOutputStream(args[1]);
|
try (FileOutputStream stream = new FileOutputStream(args[1])) {
|
||||||
try {
|
|
||||||
wb.write(stream);
|
wb.write(stream);
|
||||||
} finally {
|
|
||||||
stream.close();
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|
|
@ -31,17 +31,17 @@ import org.apache.poi.ss.usermodel.CellType;
|
||||||
*/
|
*/
|
||||||
public class HyperlinkFormula {
|
public class HyperlinkFormula {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
HSSFRow row = sheet.createRow(0);
|
HSSFRow row = sheet.createRow(0);
|
||||||
|
|
||||||
HSSFCell cell = row.createCell(0);
|
HSSFCell cell = row.createCell(0);
|
||||||
cell.setCellType(CellType.FORMULA);
|
cell.setCellType(CellType.FORMULA);
|
||||||
cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")");
|
cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")");
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,61 +37,61 @@ import org.apache.poi.ss.usermodel.Font;
|
||||||
public class Hyperlinks {
|
public class Hyperlinks {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFCreationHelper helper = wb.getCreationHelper();
|
HSSFCreationHelper helper = wb.getCreationHelper();
|
||||||
|
|
||||||
//cell style for hyperlinks
|
//cell style for hyperlinks
|
||||||
//by default hyperlinks are blue and underlined
|
//by default hyperlinks are blue and underlined
|
||||||
HSSFCellStyle hlink_style = wb.createCellStyle();
|
HSSFCellStyle hlink_style = wb.createCellStyle();
|
||||||
HSSFFont hlink_font = wb.createFont();
|
HSSFFont hlink_font = wb.createFont();
|
||||||
hlink_font.setUnderline(Font.U_SINGLE);
|
hlink_font.setUnderline(Font.U_SINGLE);
|
||||||
hlink_font.setColor(HSSFColorPredefined.BLUE.getIndex());
|
hlink_font.setColor(HSSFColorPredefined.BLUE.getIndex());
|
||||||
hlink_style.setFont(hlink_font);
|
hlink_style.setFont(hlink_font);
|
||||||
|
|
||||||
HSSFCell cell;
|
HSSFCell cell;
|
||||||
HSSFSheet sheet = wb.createSheet("Hyperlinks");
|
HSSFSheet sheet = wb.createSheet("Hyperlinks");
|
||||||
|
|
||||||
//URL
|
//URL
|
||||||
cell = sheet.createRow(0).createCell(0);
|
cell = sheet.createRow(0).createCell(0);
|
||||||
cell.setCellValue("URL Link");
|
cell.setCellValue("URL Link");
|
||||||
HSSFHyperlink link = helper.createHyperlink(HyperlinkType.URL);
|
HSSFHyperlink link = helper.createHyperlink(HyperlinkType.URL);
|
||||||
link.setAddress("http://poi.apache.org/");
|
link.setAddress("http://poi.apache.org/");
|
||||||
cell.setHyperlink(link);
|
cell.setHyperlink(link);
|
||||||
cell.setCellStyle(hlink_style);
|
cell.setCellStyle(hlink_style);
|
||||||
|
|
||||||
//link to a file in the current directory
|
//link to a file in the current directory
|
||||||
cell = sheet.createRow(1).createCell(0);
|
cell = sheet.createRow(1).createCell(0);
|
||||||
cell.setCellValue("File Link");
|
cell.setCellValue("File Link");
|
||||||
link = helper.createHyperlink(HyperlinkType.FILE);
|
link = helper.createHyperlink(HyperlinkType.FILE);
|
||||||
link.setAddress("link1.xls");
|
link.setAddress("link1.xls");
|
||||||
cell.setHyperlink(link);
|
cell.setHyperlink(link);
|
||||||
cell.setCellStyle(hlink_style);
|
cell.setCellStyle(hlink_style);
|
||||||
|
|
||||||
//e-mail link
|
//e-mail link
|
||||||
cell = sheet.createRow(2).createCell(0);
|
cell = sheet.createRow(2).createCell(0);
|
||||||
cell.setCellValue("Email Link");
|
cell.setCellValue("Email Link");
|
||||||
link = helper.createHyperlink(HyperlinkType.EMAIL);
|
link = helper.createHyperlink(HyperlinkType.EMAIL);
|
||||||
//note, if subject contains white spaces, make sure they are url-encoded
|
//note, if subject contains white spaces, make sure they are url-encoded
|
||||||
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
|
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
|
||||||
cell.setHyperlink(link);
|
cell.setHyperlink(link);
|
||||||
cell.setCellStyle(hlink_style);
|
cell.setCellStyle(hlink_style);
|
||||||
|
|
||||||
//link to a place in this workbook
|
//link to a place in this workbook
|
||||||
|
|
||||||
//create a target sheet and cell
|
//create a target sheet and cell
|
||||||
HSSFSheet sheet2 = wb.createSheet("Target Sheet");
|
HSSFSheet sheet2 = wb.createSheet("Target Sheet");
|
||||||
sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
|
sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
|
||||||
|
|
||||||
cell = sheet.createRow(3).createCell(0);
|
cell = sheet.createRow(3).createCell(0);
|
||||||
cell.setCellValue("Worksheet Link");
|
cell.setCellValue("Worksheet Link");
|
||||||
link = helper.createHyperlink(HyperlinkType.DOCUMENT);
|
link = helper.createHyperlink(HyperlinkType.DOCUMENT);
|
||||||
link.setAddress("'Target Sheet'!A1");
|
link.setAddress("'Target Sheet'!A1");
|
||||||
cell.setHyperlink(link);
|
cell.setHyperlink(link);
|
||||||
cell.setCellStyle(hlink_style);
|
cell.setCellStyle(hlink_style);
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("hssf-links.xls");
|
try (FileOutputStream out = new FileOutputStream("hssf-links.xls")) {
|
||||||
wb.write(out);
|
wb.write(out);
|
||||||
out.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -67,8 +67,7 @@ public class InCellLists {
|
||||||
* the Excel spreadsheet file this code will create.
|
* the Excel spreadsheet file this code will create.
|
||||||
*/
|
*/
|
||||||
public void demonstrateMethodCalls(String outputFilename) throws IOException {
|
public void demonstrateMethodCalls(String outputFilename) throws IOException {
|
||||||
HSSFWorkbook workbook = new HSSFWorkbook();
|
try (HSSFWorkbook workbook = new HSSFWorkbook()) {
|
||||||
try {
|
|
||||||
HSSFSheet sheet = workbook.createSheet("In Cell Lists");
|
HSSFSheet sheet = workbook.createSheet("In Cell Lists");
|
||||||
HSSFRow row = sheet.createRow(0);
|
HSSFRow row = sheet.createRow(0);
|
||||||
|
|
||||||
|
@ -89,7 +88,7 @@ public class InCellLists {
|
||||||
this.listInCell(workbook, listItems, cell);
|
this.listInCell(workbook, listItems, cell);
|
||||||
// The row height and cell width are set here to ensure that the
|
// The row height and cell width are set here to ensure that the
|
||||||
// list may be seen.
|
// list may be seen.
|
||||||
row.setHeight((short)1100);
|
row.setHeight((short) 1100);
|
||||||
sheet.setColumnWidth(0, 9500);
|
sheet.setColumnWidth(0, 9500);
|
||||||
|
|
||||||
// Create a cell at A3 and insert a numbered list into that cell.
|
// 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 Five.");
|
||||||
listItems.add("List Item Six.");
|
listItems.add("List Item Six.");
|
||||||
this.numberedListInCell(workbook, listItems, cell, 1, 2);
|
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.
|
// 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
|
// 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 Nine.");
|
||||||
listItems.add("List Item Ten.");
|
listItems.add("List Item Ten.");
|
||||||
this.bulletedListInCell(workbook, listItems, cell);
|
this.bulletedListInCell(workbook, listItems, cell);
|
||||||
row.setHeight((short)2550);
|
row.setHeight((short) 2550);
|
||||||
|
|
||||||
// Insert a plain, multi-level list into cell A5. Note that
|
// Insert a plain, multi-level list into cell A5. Note that
|
||||||
// the major difference here is that the list items are passed as
|
// 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.");
|
listItems.add("ML List Item Four - Sub Item Three.");
|
||||||
multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems));
|
multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems));
|
||||||
this.multiLevelListInCell(workbook, multiLevelListItems, cell);
|
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
|
// Insert a numbered multi-level list into cell A6. Note that the
|
||||||
// same ArrayList as constructed for the above plain multi-level
|
// same ArrayList as constructed for the above plain multi-level
|
||||||
|
@ -151,8 +150,8 @@ public class InCellLists {
|
||||||
row = sheet.createRow(5);
|
row = sheet.createRow(5);
|
||||||
cell = row.createCell(0);
|
cell = row.createCell(0);
|
||||||
this.multiLevelNumberedListInCell(workbook, multiLevelListItems,
|
this.multiLevelNumberedListInCell(workbook, multiLevelListItems,
|
||||||
cell, 1, 1, 1, 2);
|
cell, 1, 1, 1, 2);
|
||||||
row.setHeight((short)2800);
|
row.setHeight((short) 2800);
|
||||||
|
|
||||||
// Insert a numbered multi-level list into cell A7. Note that the
|
// Insert a numbered multi-level list into cell A7. Note that the
|
||||||
// same ArrayList as constructed for the plain multi-level list
|
// same ArrayList as constructed for the plain multi-level list
|
||||||
|
@ -160,31 +159,18 @@ public class InCellLists {
|
||||||
row = sheet.createRow(6);
|
row = sheet.createRow(6);
|
||||||
cell = row.createCell(0);
|
cell = row.createCell(0);
|
||||||
this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell);
|
this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell);
|
||||||
row.setHeight((short)2800);
|
row.setHeight((short) 2800);
|
||||||
|
|
||||||
// Save the completed workbook
|
// Save the completed workbook
|
||||||
FileOutputStream fos = new FileOutputStream(new File(outputFilename));
|
try (FileOutputStream fos = new FileOutputStream(new File(outputFilename))) {
|
||||||
try {
|
|
||||||
workbook.write(fos);
|
workbook.write(fos);
|
||||||
} finally {
|
|
||||||
fos.close();
|
|
||||||
}
|
}
|
||||||
}
|
} catch (IOException ioEx) {
|
||||||
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) {
|
|
||||||
System.out.println("Caught a: " + ioEx.getClass().getName());
|
System.out.println("Caught a: " + ioEx.getClass().getName());
|
||||||
System.out.println("Message: " + ioEx.getMessage());
|
System.out.println("Message: " + ioEx.getMessage());
|
||||||
System.out.println("Stacktrace follows...........");
|
System.out.println("Stacktrace follows...........");
|
||||||
ioEx.printStackTrace(System.out);
|
ioEx.printStackTrace(System.out);
|
||||||
}
|
}
|
||||||
finally {
|
|
||||||
workbook.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -31,19 +31,19 @@ import org.apache.poi.ss.util.CellRangeAddress;
|
||||||
*/
|
*/
|
||||||
public class MergedCells {
|
public class MergedCells {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
|
|
||||||
HSSFRow row = sheet.createRow(1);
|
HSSFRow row = sheet.createRow(1);
|
||||||
HSSFCell cell = row.createCell(1);
|
HSSFCell cell = row.createCell(1);
|
||||||
cell.setCellValue("This is a test of merging");
|
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
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,31 +33,27 @@ import org.apache.poi.ss.usermodel.CellType;
|
||||||
*/
|
*/
|
||||||
public class NewLinesInCells {
|
public class NewLinesInCells {
|
||||||
public static void main( String[] args ) throws IOException {
|
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();
|
HSSFCellStyle cs = wb.createCellStyle();
|
||||||
HSSFSheet s = wb.createSheet();
|
|
||||||
HSSFRow r = null;
|
|
||||||
HSSFCell c = null;
|
|
||||||
HSSFCellStyle cs = wb.createCellStyle();
|
|
||||||
HSSFFont f2 = wb.createFont();
|
|
||||||
|
|
||||||
cs = wb.createCellStyle();
|
cs.setFont(f2);
|
||||||
|
// Word Wrap MUST be turned on
|
||||||
|
cs.setWrapText(true);
|
||||||
|
|
||||||
cs.setFont(f2);
|
HSSFRow r = s.createRow(2);
|
||||||
// Word Wrap MUST be turned on
|
r.setHeight((short) 0x349);
|
||||||
cs.setWrapText(true);
|
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);
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
r.setHeight((short) 0x349);
|
wb.write(fileOut);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,16 +28,17 @@ import org.apache.poi.ss.util.WorkbookUtil;
|
||||||
*/
|
*/
|
||||||
public abstract class NewSheet {
|
public abstract class NewSheet {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
wb.createSheet("new sheet");
|
wb.createSheet("new sheet");
|
||||||
// create with default name
|
// create with default name
|
||||||
wb.createSheet();
|
wb.createSheet();
|
||||||
final String name = "second sheet";
|
final String name = "second sheet";
|
||||||
// setting sheet name later
|
// setting sheet name later
|
||||||
wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name));
|
wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name));
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
|
||||||
wb.write(fileOut);
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
fileOut.close();
|
wb.write(fileOut);
|
||||||
wb.close();
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,10 +29,10 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class NewWorkbook {
|
public class NewWorkbook {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,24 +30,25 @@ import java.io.*;
|
||||||
public class OfficeDrawing {
|
public class OfficeDrawing {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
// Create the workbook and sheets.
|
// Create the workbook and sheets.
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet1 = wb.createSheet("new sheet");
|
HSSFSheet sheet1 = wb.createSheet("new sheet");
|
||||||
HSSFSheet sheet2 = wb.createSheet("second sheet");
|
HSSFSheet sheet2 = wb.createSheet("second sheet");
|
||||||
HSSFSheet sheet3 = wb.createSheet("third sheet");
|
HSSFSheet sheet3 = wb.createSheet("third sheet");
|
||||||
HSSFSheet sheet4 = wb.createSheet("fourth sheet");
|
HSSFSheet sheet4 = wb.createSheet("fourth sheet");
|
||||||
HSSFSheet sheet5 = wb.createSheet("fifth sheet");
|
HSSFSheet sheet5 = wb.createSheet("fifth sheet");
|
||||||
|
|
||||||
// Draw stuff in them
|
// Draw stuff in them
|
||||||
drawSheet1( sheet1 );
|
drawSheet1(sheet1);
|
||||||
drawSheet2( sheet2 );
|
drawSheet2(sheet2);
|
||||||
drawSheet3( sheet3 );
|
drawSheet3(sheet3);
|
||||||
drawSheet4( sheet4, wb );
|
drawSheet4(sheet4, wb);
|
||||||
drawSheet5( sheet5, wb );
|
drawSheet5(sheet5, wb);
|
||||||
|
|
||||||
// Write the file out.
|
// Write the file out.
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void drawSheet1( HSSFSheet sheet1 )
|
private static void drawSheet1( HSSFSheet sheet1 )
|
||||||
|
|
|
@ -32,51 +32,51 @@ public class OfficeDrawingWithGraphics {
|
||||||
public static void main( String[] args ) throws IOException {
|
public static void main( String[] args ) throws IOException {
|
||||||
// Create a workbook with one sheet and size the first three somewhat
|
// Create a workbook with one sheet and size the first three somewhat
|
||||||
// larger so we can fit the chemical structure diagram in.
|
// larger so we can fit the chemical structure diagram in.
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet = wb.createSheet( "my drawing" );
|
HSSFSheet sheet = wb.createSheet("my drawing");
|
||||||
sheet.setColumnWidth(1, 256 * 27);
|
sheet.setColumnWidth(1, 256 * 27);
|
||||||
HSSFRow row1 = sheet.createRow(0);
|
HSSFRow row1 = sheet.createRow(0);
|
||||||
row1.setHeightInPoints(10 * 15f);
|
row1.setHeightInPoints(10 * 15f);
|
||||||
HSSFRow row2 = sheet.createRow(1);
|
HSSFRow row2 = sheet.createRow(1);
|
||||||
row2.setHeightInPoints(5 * 15f);
|
row2.setHeightInPoints(5 * 15f);
|
||||||
HSSFRow row3 = sheet.createRow(2);
|
HSSFRow row3 = sheet.createRow(2);
|
||||||
row3.setHeightInPoints(10 * 15f);
|
row3.setHeightInPoints(10 * 15f);
|
||||||
|
|
||||||
// Add some cells so we can test that the anchoring works when we
|
// Add some cells so we can test that the anchoring works when we
|
||||||
// sort them.
|
// sort them.
|
||||||
row1.createCell(0).setCellValue("C");
|
row1.createCell(0).setCellValue("C");
|
||||||
row2.createCell(0).setCellValue("A");
|
row2.createCell(0).setCellValue("A");
|
||||||
row3.createCell(0).setCellValue("B");
|
row3.createCell(0).setCellValue("B");
|
||||||
|
|
||||||
// Create the top level drawing patriarch.
|
// Create the top level drawing patriarch.
|
||||||
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
|
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
|
||||||
|
|
||||||
HSSFClientAnchor a;
|
HSSFClientAnchor a;
|
||||||
HSSFShapeGroup group;
|
HSSFShapeGroup group;
|
||||||
EscherGraphics g;
|
EscherGraphics g;
|
||||||
EscherGraphics2d g2d;
|
EscherGraphics2d g2d;
|
||||||
// Anchor entirely within one cell.
|
// Anchor entirely within one cell.
|
||||||
a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 );
|
a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 1, 0, (short) 1, 0);
|
||||||
group = patriarch.createGroup( a );
|
group = patriarch.createGroup(a);
|
||||||
group.setCoordinates( 0, 0, 320, 276 );
|
group.setCoordinates(0, 0, 320, 276);
|
||||||
float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
|
float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
|
||||||
g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel );
|
g = new EscherGraphics(group, wb, Color.black, verticalPointsPerPixel);
|
||||||
g2d = new EscherGraphics2d( g );
|
g2d = new EscherGraphics2d(g);
|
||||||
drawStar( g2d );
|
drawStar(g2d);
|
||||||
|
|
||||||
a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 1, (short) 1, 1 );
|
a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 1, 1, (short) 1, 1);
|
||||||
group = patriarch.createGroup( a );
|
group = patriarch.createGroup(a);
|
||||||
group.setCoordinates( 0, 0, 640, 276 );
|
group.setCoordinates(0, 0, 640, 276);
|
||||||
verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
|
verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1());
|
||||||
// verticalPixelsPerPoint = (float)Math.abs(group.getY2() - group.getY1()) / a.getAnchorHeightInPoints(sheet);
|
// verticalPixelsPerPoint = (float)Math.abs(group.getY2() - group.getY1()) / a.getAnchorHeightInPoints(sheet);
|
||||||
g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel );
|
g = new EscherGraphics(group, wb, Color.black, verticalPointsPerPixel);
|
||||||
g2d = new EscherGraphics2d( g );
|
g2d = new EscherGraphics2d(g);
|
||||||
drawStar( g2d );
|
drawStar(g2d);
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("workbook.xls");
|
|
||||||
wb.write(out);
|
|
||||||
out.close();
|
|
||||||
|
|
||||||
|
try (FileOutputStream out = new FileOutputStream("workbook.xls")) {
|
||||||
|
wb.write(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void drawStar( EscherGraphics2d g2d )
|
private static void drawStar( EscherGraphics2d g2d )
|
||||||
|
|
|
@ -37,14 +37,11 @@ public class Outlines implements Closeable {
|
||||||
throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||||
POILogger LOGGER = POILogFactory.getLogger(Outlines.class);
|
POILogger LOGGER = POILogFactory.getLogger(Outlines.class);
|
||||||
for (int i=1; i<=13; i++) {
|
for (int i=1; i<=13; i++) {
|
||||||
Outlines o = new Outlines();
|
try (Outlines o = new Outlines()) {
|
||||||
try {
|
String log = (String) Outlines.class.getDeclaredMethod("test" + i).invoke(o);
|
||||||
String log = (String)Outlines.class.getDeclaredMethod("test"+i).invoke(o);
|
String filename = "outline" + i + ".xls";
|
||||||
String filename = "outline"+i+".xls";
|
|
||||||
o.writeOut(filename);
|
o.writeOut(filename);
|
||||||
LOGGER.log(POILogger.INFO, filename+" written. "+log);
|
LOGGER.log(POILogger.INFO, filename + " written. " + log);
|
||||||
} finally {
|
|
||||||
o.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -53,11 +50,8 @@ public class Outlines implements Closeable {
|
||||||
private final HSSFSheet sheet1 = wb.createSheet("new sheet");
|
private final HSSFSheet sheet1 = wb.createSheet("new sheet");
|
||||||
|
|
||||||
public void writeOut(String filename) throws IOException {
|
public void writeOut(String filename) throws IOException {
|
||||||
FileOutputStream fileOut = new FileOutputStream(filename);
|
try (FileOutputStream fileOut = new FileOutputStream(filename)) {
|
||||||
try {
|
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
} finally {
|
|
||||||
fileOut.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -36,12 +36,7 @@ import org.apache.poi.ss.usermodel.CellType;
|
||||||
*/
|
*/
|
||||||
public class ReadWriteWorkbook {
|
public class ReadWriteWorkbook {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
FileInputStream fileIn = null;
|
try (FileInputStream fileIn = new FileInputStream("workbook.xls")) {
|
||||||
FileOutputStream fileOut = null;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
fileIn = new FileInputStream("workbook.xls");
|
|
||||||
POIFSFileSystem fs = new POIFSFileSystem(fileIn);
|
POIFSFileSystem fs = new POIFSFileSystem(fileIn);
|
||||||
HSSFWorkbook wb = new HSSFWorkbook(fs);
|
HSSFWorkbook wb = new HSSFWorkbook(fs);
|
||||||
HSSFSheet sheet = wb.getSheetAt(0);
|
HSSFSheet sheet = wb.getSheetAt(0);
|
||||||
|
@ -55,13 +50,9 @@ public class ReadWriteWorkbook {
|
||||||
cell.setCellValue("a test");
|
cell.setCellValue("a test");
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
fileOut = new FileOutputStream("workbookout.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbookout.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
} finally {
|
}
|
||||||
if (fileOut != null)
|
|
||||||
fileOut.close();
|
|
||||||
if (fileIn != null)
|
|
||||||
fileIn.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,35 +30,35 @@ import org.apache.poi.ss.util.CellRangeAddress;
|
||||||
|
|
||||||
public class RepeatingRowsAndColumns {
|
public class RepeatingRowsAndColumns {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet1 = wb.createSheet("first sheet");
|
HSSFSheet sheet1 = wb.createSheet("first sheet");
|
||||||
HSSFSheet sheet2 = wb.createSheet("second sheet");
|
HSSFSheet sheet2 = wb.createSheet("second sheet");
|
||||||
HSSFSheet sheet3 = wb.createSheet("third sheet");
|
HSSFSheet sheet3 = wb.createSheet("third sheet");
|
||||||
|
|
||||||
HSSFFont boldFont = wb.createFont();
|
HSSFFont boldFont = wb.createFont();
|
||||||
boldFont.setFontHeightInPoints((short)22);
|
boldFont.setFontHeightInPoints((short) 22);
|
||||||
boldFont.setBold(true);
|
boldFont.setBold(true);
|
||||||
|
|
||||||
HSSFCellStyle boldStyle = wb.createCellStyle();
|
HSSFCellStyle boldStyle = wb.createCellStyle();
|
||||||
boldStyle.setFont(boldFont);
|
boldStyle.setFont(boldFont);
|
||||||
|
|
||||||
HSSFRow row = sheet1.createRow(1);
|
HSSFRow row = sheet1.createRow(1);
|
||||||
HSSFCell cell = row.createCell(0);
|
HSSFCell cell = row.createCell(0);
|
||||||
cell.setCellValue("This quick brown fox");
|
cell.setCellValue("This quick brown fox");
|
||||||
cell.setCellStyle(boldStyle);
|
cell.setCellStyle(boldStyle);
|
||||||
|
|
||||||
// Set the columns to repeat from column 0 to 2 on the first sheet
|
// Set the columns to repeat from column 0 to 2 on the first sheet
|
||||||
sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
|
sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
|
||||||
// Set the rows to repeat from row 0 to 2 on the second sheet.
|
// Set the rows to repeat from row 0 to 2 on the second sheet.
|
||||||
sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:3"));
|
sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:3"));
|
||||||
// Set the the repeating rows and columns on the third sheet.
|
// Set the the repeating rows and columns on the third sheet.
|
||||||
CellRangeAddress cra = CellRangeAddress.valueOf("D1:E2");
|
CellRangeAddress cra = CellRangeAddress.valueOf("D1:E2");
|
||||||
sheet3.setRepeatingColumns(cra);
|
sheet3.setRepeatingColumns(cra);
|
||||||
sheet3.setRepeatingRows(cra);
|
sheet3.setRepeatingRows(cra);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,24 +28,24 @@ import org.apache.poi.ss.usermodel.Sheet;
|
||||||
|
|
||||||
public class SplitAndFreezePanes {
|
public class SplitAndFreezePanes {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet1 = wb.createSheet("new sheet");
|
HSSFSheet sheet1 = wb.createSheet("new sheet");
|
||||||
HSSFSheet sheet2 = wb.createSheet("second sheet");
|
HSSFSheet sheet2 = wb.createSheet("second sheet");
|
||||||
HSSFSheet sheet3 = wb.createSheet("third sheet");
|
HSSFSheet sheet3 = wb.createSheet("third sheet");
|
||||||
HSSFSheet sheet4 = wb.createSheet("fourth sheet");
|
HSSFSheet sheet4 = wb.createSheet("fourth sheet");
|
||||||
|
|
||||||
// Freeze just one row
|
// Freeze just one row
|
||||||
sheet1.createFreezePane( 0, 1, 0, 1 );
|
sheet1.createFreezePane(0, 1, 0, 1);
|
||||||
// Freeze just one column
|
// Freeze just one column
|
||||||
sheet2.createFreezePane( 1, 0, 1, 0 );
|
sheet2.createFreezePane(1, 0, 1, 0);
|
||||||
// Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
|
// Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
|
||||||
sheet3.createFreezePane( 2, 2 );
|
sheet3.createFreezePane(2, 2);
|
||||||
// Create a split with the lower left side being the active quadrant
|
// Create a split with the lower left side being the active quadrant
|
||||||
sheet4.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
|
sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,32 +32,32 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class WorkingWithFonts {
|
public class WorkingWithFonts {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
HSSFRow row = sheet.createRow(1);
|
HSSFRow row = sheet.createRow(1);
|
||||||
|
|
||||||
// Create a new font and alter it.
|
// Create a new font and alter it.
|
||||||
HSSFFont font = wb.createFont();
|
HSSFFont font = wb.createFont();
|
||||||
font.setFontHeightInPoints((short)24);
|
font.setFontHeightInPoints((short) 24);
|
||||||
font.setFontName("Courier New");
|
font.setFontName("Courier New");
|
||||||
font.setItalic(true);
|
font.setItalic(true);
|
||||||
font.setStrikeout(true);
|
font.setStrikeout(true);
|
||||||
|
|
||||||
// Fonts are set into a style so create a new one to use.
|
// Fonts are set into a style so create a new one to use.
|
||||||
HSSFCellStyle style = wb.createCellStyle();
|
HSSFCellStyle style = wb.createCellStyle();
|
||||||
style.setFont(font);
|
style.setFont(font);
|
||||||
|
|
||||||
// Create a cell and put a value in it.
|
// Create a cell and put a value in it.
|
||||||
HSSFCell cell = row.createCell(1);
|
HSSFCell cell = row.createCell(1);
|
||||||
cell.setCellValue("This is a test of fonts");
|
cell.setCellValue("This is a test of fonts");
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,15 +32,14 @@ import java.io.FileOutputStream;
|
||||||
*/
|
*/
|
||||||
public class ZoomSheet
|
public class ZoomSheet
|
||||||
{
|
{
|
||||||
public static void main(String[] args)
|
public static void main(String[] args) throws IOException {
|
||||||
throws IOException
|
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||||
{
|
HSSFSheet sheet1 = wb.createSheet("new sheet");
|
||||||
HSSFWorkbook wb = new HSSFWorkbook();
|
sheet1.setZoom(75); // 75 percent magnification
|
||||||
HSSFSheet sheet1 = wb.createSheet("new sheet");
|
|
||||||
sheet1.setZoom(75); // 75 percent magnification
|
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||||
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
|
wb.write(fileOut);
|
||||||
wb.write(fileOut);
|
}
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -216,13 +216,9 @@ public final class Word2Forrest
|
||||||
|
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
InputStream is = new FileInputStream(args[0]);
|
try (InputStream is = new FileInputStream(args[0]);
|
||||||
OutputStream out = new FileOutputStream("test.xml");
|
OutputStream out = new FileOutputStream("test.xml")) {
|
||||||
try {
|
new Word2Forrest(new HWPFDocument(is), out);
|
||||||
new Word2Forrest(new HWPFDocument(is), out);
|
}
|
||||||
} finally {
|
|
||||||
out.close();
|
|
||||||
is.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,30 +29,29 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class AligningCells {
|
public class AligningCells {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
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();
|
Sheet sheet = wb.createSheet();
|
||||||
Row row = sheet.createRow(2);
|
Row row = sheet.createRow(2);
|
||||||
row.setHeightInPoints(30);
|
row.setHeightInPoints(30);
|
||||||
for (int i = 0; i < 8; i++) {
|
for (int i = 0; i < 8; i++) {
|
||||||
//column width is set in units of 1/256th of a character width
|
//column width is set in units of 1/256th of a character width
|
||||||
sheet.setColumnWidth(i, 256 * 15);
|
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -51,97 +51,97 @@ public class CalendarDemo {
|
||||||
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
Calendar calendar = Calendar.getInstance();
|
||||||
boolean xlsx = true;
|
boolean xlsx = true;
|
||||||
for (int i = 0; i < args.length; i++) {
|
for (String arg : args) {
|
||||||
if(args[i].charAt(0) == '-'){
|
if (arg.charAt(0) == '-') {
|
||||||
xlsx = args[i].equals("-xlsx");
|
xlsx = arg.equals("-xlsx");
|
||||||
} else {
|
} else {
|
||||||
calendar.set(Calendar.YEAR, Integer.parseInt(args[i]));
|
calendar.set(Calendar.YEAR, Integer.parseInt(arg));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
int year = calendar.get(Calendar.YEAR);
|
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++) {
|
for (int month = 0; month < 12; month++) {
|
||||||
calendar.set(Calendar.MONTH, month);
|
calendar.set(Calendar.MONTH, month);
|
||||||
calendar.set(Calendar.DAY_OF_MONTH, 1);
|
calendar.set(Calendar.DAY_OF_MONTH, 1);
|
||||||
//create a sheet for each month
|
//create a sheet for each month
|
||||||
Sheet sheet = wb.createSheet(months[month]);
|
Sheet sheet = wb.createSheet(months[month]);
|
||||||
|
|
||||||
//turn off gridlines
|
//turn off gridlines
|
||||||
sheet.setDisplayGridlines(false);
|
sheet.setDisplayGridlines(false);
|
||||||
sheet.setPrintGridlines(false);
|
sheet.setPrintGridlines(false);
|
||||||
sheet.setFitToPage(true);
|
sheet.setFitToPage(true);
|
||||||
sheet.setHorizontallyCenter(true);
|
sheet.setHorizontallyCenter(true);
|
||||||
PrintSetup printSetup = sheet.getPrintSetup();
|
PrintSetup printSetup = sheet.getPrintSetup();
|
||||||
printSetup.setLandscape(true);
|
printSetup.setLandscape(true);
|
||||||
|
|
||||||
//the following three statements are required only for HSSF
|
//the following three statements are required only for HSSF
|
||||||
sheet.setAutobreaks(true);
|
sheet.setAutobreaks(true);
|
||||||
printSetup.setFitHeight((short)1);
|
printSetup.setFitHeight((short) 1);
|
||||||
printSetup.setFitWidth((short)1);
|
printSetup.setFitWidth((short) 1);
|
||||||
|
|
||||||
//the header row: centered text in 48pt font
|
//the header row: centered text in 48pt font
|
||||||
Row headerRow = sheet.createRow(0);
|
Row headerRow = sheet.createRow(0);
|
||||||
headerRow.setHeightInPoints(80);
|
headerRow.setHeightInPoints(80);
|
||||||
Cell titleCell = headerRow.createCell(0);
|
Cell titleCell = headerRow.createCell(0);
|
||||||
titleCell.setCellValue(months[month] + " " + year);
|
titleCell.setCellValue(months[month] + " " + year);
|
||||||
titleCell.setCellStyle(styles.get("title"));
|
titleCell.setCellStyle(styles.get("title"));
|
||||||
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
|
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
|
||||||
|
|
||||||
//header with month titles
|
//header with month titles
|
||||||
Row monthRow = sheet.createRow(1);
|
Row monthRow = sheet.createRow(1);
|
||||||
for (int i = 0; i < days.length; i++) {
|
for (int i = 0; i < days.length; i++) {
|
||||||
//set column widths, the width is measured in units of 1/256th of a character width
|
//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, 5 * 256); //the column is 5 characters wide
|
||||||
sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 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));
|
sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1));
|
||||||
Cell monthCell = monthRow.createCell(i*2);
|
Cell monthCell = monthRow.createCell(i * 2);
|
||||||
monthCell.setCellValue(days[i]);
|
monthCell.setCellValue(days[i]);
|
||||||
monthCell.setCellStyle(styles.get("month"));
|
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;
|
// Write the output to a file
|
||||||
int rownum = 2;
|
String file = "calendar.xls";
|
||||||
for (int j = 0; j < 6; j++) {
|
if (wb instanceof XSSFWorkbook) file += "x";
|
||||||
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);
|
try (FileOutputStream out = new FileOutputStream(file)) {
|
||||||
if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
|
wb.write(out);
|
||||||
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
|
|
||||||
String file = "calendar.xls";
|
|
||||||
if(wb instanceof XSSFWorkbook) file += "x";
|
|
||||||
FileOutputStream out = new FileOutputStream(file);
|
|
||||||
wb.write(out);
|
|
||||||
out.close();
|
|
||||||
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -43,45 +43,44 @@ public class CellStyleDetails {
|
||||||
throw new IllegalArgumentException("Filename must be given");
|
throw new IllegalArgumentException("Filename must be given");
|
||||||
}
|
}
|
||||||
|
|
||||||
Workbook wb = WorkbookFactory.create(new File(args[0]));
|
try (Workbook wb = WorkbookFactory.create(new File(args[0]))) {
|
||||||
DataFormatter formatter = new DataFormatter();
|
DataFormatter formatter = new DataFormatter();
|
||||||
|
|
||||||
for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {
|
for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) {
|
||||||
Sheet sheet = wb.getSheetAt(sn);
|
Sheet sheet = wb.getSheetAt(sn);
|
||||||
System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());
|
System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());
|
||||||
|
|
||||||
for(Row row : sheet) {
|
for (Row row : sheet) {
|
||||||
System.out.println(" Row " + row.getRowNum());
|
System.out.println(" Row " + row.getRowNum());
|
||||||
|
|
||||||
for(Cell cell : row) {
|
for (Cell cell : row) {
|
||||||
CellReference ref = new CellReference(cell);
|
CellReference ref = new CellReference(cell);
|
||||||
System.out.print(" " + ref.formatAsString());
|
System.out.print(" " + ref.formatAsString());
|
||||||
System.out.print(" (" + cell.getColumnIndex() + ") ");
|
System.out.print(" (" + cell.getColumnIndex() + ") ");
|
||||||
|
|
||||||
CellStyle style = cell.getCellStyle();
|
CellStyle style = cell.getCellStyle();
|
||||||
System.out.print("Format=" + style.getDataFormatString() + " ");
|
System.out.print("Format=" + style.getDataFormatString() + " ");
|
||||||
System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
|
System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
|
||||||
System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");
|
System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");
|
||||||
|
|
||||||
Font font = wb.getFontAt( style.getFontIndex() );
|
Font font = wb.getFontAt(style.getFontIndex());
|
||||||
System.out.print("Font=" + font.getFontName() + " ");
|
System.out.print("Font=" + font.getFontName() + " ");
|
||||||
System.out.print("FontColor=");
|
System.out.print("FontColor=");
|
||||||
if(font instanceof HSSFFont) {
|
if (font instanceof HSSFFont) {
|
||||||
System.out.print( renderColor( ((HSSFFont)font).getHSSFColor((HSSFWorkbook)wb)) );
|
System.out.print(renderColor(((HSSFFont) font).getHSSFColor((HSSFWorkbook) wb)));
|
||||||
}
|
}
|
||||||
if(font instanceof XSSFFont) {
|
if (font instanceof XSSFFont) {
|
||||||
System.out.print( renderColor( ((XSSFFont)font).getXSSFColor()) );
|
System.out.print(renderColor(((XSSFFont) font).getXSSFColor()));
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println();
|
System.out.println();
|
||||||
System.out.println(" " + formatter.formatCellValue(cell));
|
System.out.println(" " + formatter.formatCellValue(cell));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println();
|
System.out.println();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String renderColor(Color color) {
|
private static String renderColor(Color color) {
|
||||||
|
|
|
@ -74,22 +74,20 @@ public class SettingExternalFunction {
|
||||||
|
|
||||||
public static void main( String[] args ) throws IOException {
|
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
|
// register the add-in
|
||||||
wb.addToolPack(new BloombergAddIn());
|
wb.addToolPack(new BloombergAddIn());
|
||||||
|
|
||||||
Sheet sheet = wb.createSheet();
|
Sheet sheet = wb.createSheet();
|
||||||
Row row = sheet.createRow(0);
|
Row row = sheet.createRow(0);
|
||||||
row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100");
|
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(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\") ");
|
row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") ");
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx");
|
try (FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx")) {
|
||||||
wb.write(out);
|
wb.write(out);
|
||||||
out.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,7 +17,6 @@
|
||||||
package org.apache.poi.ss.examples.formula;
|
package org.apache.poi.ss.examples.formula;
|
||||||
|
|
||||||
import java.io.File ;
|
import java.io.File ;
|
||||||
import java.io.FileInputStream ;
|
|
||||||
|
|
||||||
import org.apache.poi.ss.formula.functions.FreeRefFunction ;
|
import org.apache.poi.ss.formula.functions.FreeRefFunction ;
|
||||||
import org.apache.poi.ss.formula.udf.DefaultUDFFinder ;
|
import org.apache.poi.ss.formula.udf.DefaultUDFFinder ;
|
||||||
|
@ -50,33 +49,29 @@ public class UserDefinedFunctionExample {
|
||||||
System.out.println( "cell: " + args[1] ) ;
|
System.out.println( "cell: " + args[1] ) ;
|
||||||
|
|
||||||
File workbookFile = new File( args[0] ) ;
|
File workbookFile = new File( args[0] ) ;
|
||||||
|
|
||||||
Workbook workbook = WorkbookFactory.create(workbookFile, null, true);
|
|
||||||
|
|
||||||
try {
|
try (Workbook workbook = WorkbookFactory.create(workbookFile, null, true)) {
|
||||||
String[] functionNames = { "calculatePayment" } ;
|
String[] functionNames = {"calculatePayment"};
|
||||||
FreeRefFunction[] functionImpls = { new CalculateMortgage() } ;
|
FreeRefFunction[] functionImpls = {new CalculateMortgage()};
|
||||||
|
|
||||||
UDFFinder udfToolpack = new DefaultUDFFinder( functionNames, functionImpls ) ;
|
UDFFinder udfToolpack = new DefaultUDFFinder(functionNames, functionImpls);
|
||||||
|
|
||||||
// register the user-defined function in the workbook
|
// register the user-defined function in the workbook
|
||||||
workbook.addToolPack(udfToolpack);
|
workbook.addToolPack(udfToolpack);
|
||||||
|
|
||||||
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
|
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
|
||||||
|
|
||||||
CellReference cr = new CellReference( args[1] ) ;
|
CellReference cr = new CellReference(args[1]);
|
||||||
String sheetName = cr.getSheetName() ;
|
String sheetName = cr.getSheetName();
|
||||||
Sheet sheet = workbook.getSheet( sheetName ) ;
|
Sheet sheet = workbook.getSheet(sheetName);
|
||||||
int rowIdx = cr.getRow() ;
|
int rowIdx = cr.getRow();
|
||||||
int colIdx = cr.getCol() ;
|
int colIdx = cr.getCol();
|
||||||
Row row = sheet.getRow( rowIdx ) ;
|
Row row = sheet.getRow(rowIdx);
|
||||||
Cell cell = row.getCell( colIdx ) ;
|
Cell cell = row.getCell(colIdx);
|
||||||
|
|
||||||
CellValue value = evaluator.evaluate( cell ) ;
|
CellValue value = evaluator.evaluate(cell);
|
||||||
|
|
||||||
System.out.println("returns value: " + value ) ;
|
System.out.println("returns value: " + value);
|
||||||
} finally {
|
|
||||||
workbook.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -43,53 +43,52 @@ public final class DataExtraction {
|
||||||
}
|
}
|
||||||
|
|
||||||
FileInputStream is = new FileInputStream(args[0]);
|
FileInputStream is = new FileInputStream(args[0]);
|
||||||
XMLSlideShow ppt = new XMLSlideShow(is);
|
try (XMLSlideShow ppt = new XMLSlideShow(is)) {
|
||||||
is.close();
|
is.close();
|
||||||
|
|
||||||
// Get the document's embedded files.
|
// Get the document's embedded files.
|
||||||
for (PackagePart p : ppt.getAllEmbedds()) {
|
for (PackagePart p : ppt.getAllEmbedds()) {
|
||||||
String type = p.getContentType();
|
String type = p.getContentType();
|
||||||
// typically file name
|
// typically file name
|
||||||
String name = p.getPartName().getName();
|
String name = p.getPartName().getName();
|
||||||
out.println("Embedded file ("+type+"): "+name);
|
out.println("Embedded file (" + type + "): " + name);
|
||||||
|
|
||||||
InputStream pIs = p.getInputStream();
|
|
||||||
// make sense of the part data
|
|
||||||
pIs.close();
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the document's embedded files.
|
InputStream pIs = p.getInputStream();
|
||||||
for (XSLFPictureData data : ppt.getPictureData()) {
|
// make sense of the part data
|
||||||
String type = data.getContentType();
|
pIs.close();
|
||||||
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
|
// Get the document's embedded files.
|
||||||
Dimension pageSize = ppt.getPageSize();
|
for (XSLFPictureData data : ppt.getPictureData()) {
|
||||||
out.println("Pagesize: "+pageSize);
|
String type = data.getContentType();
|
||||||
|
String name = data.getFileName();
|
||||||
for(XSLFSlide slide : ppt.getSlides()) {
|
out.println("Picture (" + type + "): " + name);
|
||||||
for(XSLFShape shape : slide){
|
|
||||||
if(shape instanceof XSLFTextShape) {
|
InputStream pIs = data.getInputStream();
|
||||||
XSLFTextShape txShape = (XSLFTextShape)shape;
|
// make sense of the image data
|
||||||
out.println(txShape.getText());
|
pIs.close();
|
||||||
} else if (shape instanceof XSLFPictureShape){
|
}
|
||||||
XSLFPictureShape pShape = (XSLFPictureShape)shape;
|
|
||||||
XSLFPictureData pData = pShape.getPictureData();
|
// size of the canvas in points
|
||||||
out.println(pData.getFileName());
|
Dimension pageSize = ppt.getPageSize();
|
||||||
} else {
|
out.println("Pagesize: " + pageSize);
|
||||||
out.println("Process me: " + shape.getClass());
|
|
||||||
|
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,26 +28,22 @@ import java.io.FileOutputStream;
|
||||||
public final class MergePresentations {
|
public final class MergePresentations {
|
||||||
|
|
||||||
public static void main(String args[]) throws Exception {
|
public static void main(String args[]) throws Exception {
|
||||||
XMLSlideShow ppt = new XMLSlideShow();
|
try (XMLSlideShow ppt = new XMLSlideShow()) {
|
||||||
|
for (String arg : args) {
|
||||||
try {
|
|
||||||
for (String arg : args){
|
|
||||||
FileInputStream is = new FileInputStream(arg);
|
FileInputStream is = new FileInputStream(arg);
|
||||||
XMLSlideShow src = new XMLSlideShow(is);
|
XMLSlideShow src = new XMLSlideShow(is);
|
||||||
is.close();
|
is.close();
|
||||||
|
|
||||||
for(XSLFSlide srcSlide : src.getSlides()){
|
for (XSLFSlide srcSlide : src.getSlides()) {
|
||||||
ppt.createSlide().importContent(srcSlide);
|
ppt.createSlide().importContent(srcSlide);
|
||||||
}
|
}
|
||||||
|
|
||||||
src.close();
|
src.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("merged.pptx");
|
try (FileOutputStream out = new FileOutputStream("merged.pptx")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -62,104 +62,91 @@ public class PieChartDemo {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
BufferedReader modelReader = new BufferedReader(new FileReader(args[1]));
|
try (BufferedReader modelReader = new BufferedReader(new FileReader(args[1]))) {
|
||||||
XMLSlideShow pptx = null;
|
|
||||||
try {
|
|
||||||
String chartTitle = modelReader.readLine(); // first line is chart title
|
String chartTitle = modelReader.readLine(); // first line is chart title
|
||||||
|
|
||||||
pptx = new XMLSlideShow(new FileInputStream(args[0]));
|
try (XMLSlideShow pptx = new XMLSlideShow(new FileInputStream(args[0]))) {
|
||||||
XSLFSlide slide = pptx.getSlides().get(0);
|
XSLFSlide slide = pptx.getSlides().get(0);
|
||||||
|
|
||||||
// find chart in the slide
|
// find chart in the slide
|
||||||
XSLFChart chart = null;
|
XSLFChart chart = null;
|
||||||
for(POIXMLDocumentPart part : slide.getRelations()){
|
for (POIXMLDocumentPart part : slide.getRelations()) {
|
||||||
if(part instanceof XSLFChart){
|
if (part instanceof XSLFChart) {
|
||||||
chart = (XSLFChart) part;
|
chart = (XSLFChart) part;
|
||||||
break;
|
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,25 +29,24 @@ import java.io.IOException;
|
||||||
public class Tutorial1 {
|
public class Tutorial1 {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException{
|
public static void main(String[] args) throws IOException{
|
||||||
XMLSlideShow ppt = new XMLSlideShow();
|
try (XMLSlideShow ppt = new XMLSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
// XSLFSlide#createSlide() with no arguments creates a blank slide
|
// XSLFSlide#createSlide() with no arguments creates a blank slide
|
||||||
/*XSLFSlide blankSlide =*/ ppt.createSlide();
|
/*XSLFSlide blankSlide =*/
|
||||||
|
ppt.createSlide();
|
||||||
|
|
||||||
|
|
||||||
XSLFSlideMaster master = ppt.getSlideMasters().get(0);
|
XSLFSlideMaster master = ppt.getSlideMasters().get(0);
|
||||||
|
|
||||||
XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);
|
XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);
|
||||||
XSLFSlide slide1 = ppt.createSlide(layout1) ;
|
XSLFSlide slide1 = ppt.createSlide(layout1);
|
||||||
XSLFTextShape[] ph1 = slide1.getPlaceholders();
|
XSLFTextShape[] ph1 = slide1.getPlaceholders();
|
||||||
XSLFTextShape titlePlaceholder1 = ph1[0];
|
XSLFTextShape titlePlaceholder1 = ph1[0];
|
||||||
titlePlaceholder1.setText("This is a title");
|
titlePlaceholder1.setText("This is a title");
|
||||||
XSLFTextShape subtitlePlaceholder1 = ph1[1];
|
XSLFTextShape subtitlePlaceholder1 = ph1[1];
|
||||||
subtitlePlaceholder1.setText("this is a subtitle");
|
subtitlePlaceholder1.setText("this is a subtitle");
|
||||||
|
|
||||||
XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);
|
XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);
|
||||||
XSLFSlide slide2 = ppt.createSlide(layout2) ;
|
XSLFSlide slide2 = ppt.createSlide(layout2);
|
||||||
XSLFTextShape[] ph2 = slide2.getPlaceholders();
|
XSLFTextShape[] ph2 = slide2.getPlaceholders();
|
||||||
XSLFTextShape titlePlaceholder2 = ph2[0];
|
XSLFTextShape titlePlaceholder2 = ph2[0];
|
||||||
titlePlaceholder2.setText("This is a title");
|
titlePlaceholder2.setText("This is a title");
|
||||||
|
@ -63,12 +62,10 @@ public class Tutorial1 {
|
||||||
XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph();
|
XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph();
|
||||||
p3.setIndentLevel(2);
|
p3.setIndentLevel(2);
|
||||||
p3.addNewTextRun().setText("Level3 text");
|
p3.addNewTextRun().setText("Level3 text");
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("slides.pptx");
|
try (FileOutputStream out = new FileOutputStream("slides.pptx")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,21 +30,19 @@ import java.io.IOException;
|
||||||
public class Tutorial2 {
|
public class Tutorial2 {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException{
|
public static void main(String[] args) throws IOException{
|
||||||
XMLSlideShow ppt = new XMLSlideShow();
|
try (XMLSlideShow ppt = new XMLSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
XSLFSlide slide1 = ppt.createSlide();
|
XSLFSlide slide1 = ppt.createSlide();
|
||||||
XSLFTextBox shape1 = slide1.createTextBox();
|
XSLFTextBox shape1 = slide1.createTextBox();
|
||||||
// initial height of the text box is 100 pt but
|
// initial height of the text box is 100 pt but
|
||||||
Rectangle anchor = new Rectangle(10, 100, 300, 100);
|
Rectangle anchor = new Rectangle(10, 100, 300, 100);
|
||||||
shape1.setAnchor(anchor);
|
shape1.setAnchor(anchor);
|
||||||
|
|
||||||
XSLFTextParagraph p1 = shape1.addNewTextParagraph();
|
XSLFTextParagraph p1 = shape1.addNewTextParagraph();
|
||||||
XSLFTextRun r1 = p1.addNewTextRun();
|
XSLFTextRun r1 = p1.addNewTextRun();
|
||||||
r1.setText("Paragraph Formatting");
|
r1.setText("Paragraph Formatting");
|
||||||
r1.setFontSize(24d);
|
r1.setFontSize(24d);
|
||||||
r1.setFontColor(new Color(85, 142, 213));
|
r1.setFontColor(new Color(85, 142, 213));
|
||||||
|
|
||||||
XSLFTextParagraph p2 = shape1.addNewTextParagraph();
|
XSLFTextParagraph p2 = shape1.addNewTextParagraph();
|
||||||
// If spaceBefore >= 0, then space is a percentage of normal line height.
|
// 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
|
// If spaceBefore < 0, the absolute value of linespacing is the spacing in points
|
||||||
|
@ -53,14 +51,14 @@ public class Tutorial2 {
|
||||||
XSLFTextRun r2 = p2.addNewTextRun();
|
XSLFTextRun r2 = p2.addNewTextRun();
|
||||||
r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph.");
|
r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph.");
|
||||||
r2.setFontSize(16d);
|
r2.setFontSize(16d);
|
||||||
|
|
||||||
XSLFTextParagraph p3 = shape1.addNewTextParagraph();
|
XSLFTextParagraph p3 = shape1.addNewTextParagraph();
|
||||||
|
|
||||||
XSLFTextRun r3 = p3.addNewTextRun();
|
XSLFTextRun r3 = p3.addNewTextRun();
|
||||||
r3.setText("Run Formatting");
|
r3.setText("Run Formatting");
|
||||||
r3.setFontSize(24d);
|
r3.setFontSize(24d);
|
||||||
r3.setFontColor(new Color(85, 142, 213));
|
r3.setFontColor(new Color(85, 142, 213));
|
||||||
|
|
||||||
XSLFTextParagraph p4 = shape1.addNewTextParagraph();
|
XSLFTextParagraph p4 = shape1.addNewTextParagraph();
|
||||||
p4.setSpaceBefore(-20d); // 20 pt from the previous paragraph
|
p4.setSpaceBefore(-20d); // 20 pt from the previous paragraph
|
||||||
p4.setSpaceAfter(300d); // 3 lines after the paragraph
|
p4.setSpaceAfter(300d); // 3 lines after the paragraph
|
||||||
|
@ -68,18 +66,16 @@ public class Tutorial2 {
|
||||||
r4.setFontSize(16d);
|
r4.setFontSize(16d);
|
||||||
r4.setText(
|
r4.setText(
|
||||||
"Run level formatting is the most granular property level and allows " +
|
"Run level formatting is the most granular property level and allows " +
|
||||||
"for the specifying of all low level text properties. The text run is " +
|
"for the specifying of all low level text properties. The text run is " +
|
||||||
"what all paragraphs are derived from and thus specifying various " +
|
"what all paragraphs are derived from and thus specifying various " +
|
||||||
"properties per run will allow for a diversely formatted text paragraph.");
|
"properties per run will allow for a diversely formatted text paragraph.");
|
||||||
|
|
||||||
// resize the shape to fit text
|
// resize the shape to fit text
|
||||||
shape1.resizeToFitText();
|
shape1.resizeToFitText();
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("text.pptx");
|
try (FileOutputStream out = new FileOutputStream("text.pptx")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,21 +31,17 @@ import org.apache.poi.sl.usermodel.Placeholder;
|
||||||
public class Tutorial3 {
|
public class Tutorial3 {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException{
|
public static void main(String[] args) throws IOException{
|
||||||
XMLSlideShow ppt = new XMLSlideShow();
|
try (XMLSlideShow ppt = new XMLSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
XSLFSlide slide = ppt.createSlide();
|
XSLFSlide slide = ppt.createSlide();
|
||||||
|
|
||||||
XSLFTextShape titleShape = slide.createTextBox();
|
XSLFTextShape titleShape = slide.createTextBox();
|
||||||
titleShape.setPlaceholder(Placeholder.TITLE);
|
titleShape.setPlaceholder(Placeholder.TITLE);
|
||||||
titleShape.setText("This is a slide title");
|
titleShape.setText("This is a slide title");
|
||||||
titleShape.setAnchor(new Rectangle(50, 50, 400, 100));
|
titleShape.setAnchor(new Rectangle(50, 50, 400, 100));
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("title.pptx");
|
try (FileOutputStream out = new FileOutputStream("title.pptx")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,60 +33,56 @@ import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;
|
||||||
public class Tutorial4 {
|
public class Tutorial4 {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException{
|
public static void main(String[] args) throws IOException{
|
||||||
XMLSlideShow ppt = new XMLSlideShow();
|
try (XMLSlideShow ppt = new XMLSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
// XSLFSlide#createSlide() with no arguments creates a blank slide
|
// XSLFSlide#createSlide() with no arguments creates a blank slide
|
||||||
XSLFSlide slide = ppt.createSlide();
|
XSLFSlide slide = ppt.createSlide();
|
||||||
|
|
||||||
XSLFTable tbl = slide.createTable();
|
XSLFTable tbl = slide.createTable();
|
||||||
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
|
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
|
||||||
|
|
||||||
int numColumns = 3;
|
int numColumns = 3;
|
||||||
int numRows = 5;
|
int numRows = 5;
|
||||||
XSLFTableRow headerRow = tbl.addRow();
|
XSLFTableRow headerRow = tbl.addRow();
|
||||||
headerRow.setHeight(50);
|
headerRow.setHeight(50);
|
||||||
// header
|
// header
|
||||||
for(int i = 0; i < numColumns; i++) {
|
for (int i = 0; i < numColumns; i++) {
|
||||||
XSLFTableCell th = headerRow.addCell();
|
XSLFTableCell th = headerRow.addCell();
|
||||||
XSLFTextParagraph p = th.addNewTextParagraph();
|
XSLFTextParagraph p = th.addNewTextParagraph();
|
||||||
p.setTextAlign(TextAlign.CENTER);
|
p.setTextAlign(TextAlign.CENTER);
|
||||||
XSLFTextRun r = p.addNewTextRun();
|
XSLFTextRun r = p.addNewTextRun();
|
||||||
r.setText("Header " + (i+1));
|
r.setText("Header " + (i + 1));
|
||||||
r.setBold(true);
|
r.setBold(true);
|
||||||
r.setFontColor(Color.white);
|
r.setFontColor(Color.white);
|
||||||
th.setFillColor(new Color(79, 129, 189));
|
th.setFillColor(new Color(79, 129, 189));
|
||||||
th.setBorderWidth(BorderEdge.bottom, 2.0);
|
th.setBorderWidth(BorderEdge.bottom, 2.0);
|
||||||
th.setBorderColor(BorderEdge.bottom, Color.white);
|
th.setBorderColor(BorderEdge.bottom, Color.white);
|
||||||
|
|
||||||
tbl.setColumnWidth(i, 150); // all columns are equally sized
|
tbl.setColumnWidth(i, 150); // all columns are equally sized
|
||||||
}
|
}
|
||||||
|
|
||||||
// rows
|
// rows
|
||||||
|
|
||||||
for(int rownum = 0; rownum < numRows; rownum ++){
|
for (int rownum = 0; rownum < numRows; rownum++) {
|
||||||
XSLFTableRow tr = tbl.addRow();
|
XSLFTableRow tr = tbl.addRow();
|
||||||
tr.setHeight(50);
|
tr.setHeight(50);
|
||||||
// header
|
// header
|
||||||
for(int i = 0; i < numColumns; i++) {
|
for (int i = 0; i < numColumns; i++) {
|
||||||
XSLFTableCell cell = tr.addCell();
|
XSLFTableCell cell = tr.addCell();
|
||||||
XSLFTextParagraph p = cell.addNewTextParagraph();
|
XSLFTextParagraph p = cell.addNewTextParagraph();
|
||||||
XSLFTextRun r = p.addNewTextRun();
|
XSLFTextRun r = p.addNewTextRun();
|
||||||
|
|
||||||
r.setText("Cell " + (i+1));
|
r.setText("Cell " + (i + 1));
|
||||||
if(rownum % 2 == 0)
|
if (rownum % 2 == 0)
|
||||||
cell.setFillColor(new Color(208, 216, 232));
|
cell.setFillColor(new Color(208, 216, 232));
|
||||||
else
|
else
|
||||||
cell.setFillColor(new Color(233, 247, 244));
|
cell.setFillColor(new Color(233, 247, 244));
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("table.pptx");
|
try (FileOutputStream out = new FileOutputStream("table.pptx")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,21 +31,18 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType;
|
||||||
public class Tutorial5 {
|
public class Tutorial5 {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException{
|
public static void main(String[] args) throws IOException{
|
||||||
XMLSlideShow ppt = new XMLSlideShow();
|
try (XMLSlideShow ppt = new XMLSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
XSLFSlide slide = ppt.createSlide();
|
XSLFSlide slide = ppt.createSlide();
|
||||||
|
|
||||||
File img = new File(System.getProperty("POI.testdata.path", "test-data"), "slideshow/clock.jpg");
|
File img = new File(System.getProperty("POI.testdata.path", "test-data"), "slideshow/clock.jpg");
|
||||||
XSLFPictureData pictureData = ppt.addPicture(img, PictureType.PNG);
|
XSLFPictureData pictureData = ppt.addPicture(img, PictureType.PNG);
|
||||||
|
|
||||||
/*XSLFPictureShape shape =*/ slide.createPicture(pictureData);
|
/*XSLFPictureShape shape =*/
|
||||||
|
slide.createPicture(pictureData);
|
||||||
FileOutputStream out = new FileOutputStream("images.pptx");
|
|
||||||
ppt.write(out);
|
try (FileOutputStream out = new FileOutputStream("images.pptx")) {
|
||||||
out.close();
|
ppt.write(out);
|
||||||
} finally {
|
}
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,33 +29,28 @@ import java.io.IOException;
|
||||||
public class Tutorial6 {
|
public class Tutorial6 {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException{
|
public static void main(String[] args) throws IOException{
|
||||||
XMLSlideShow ppt = new XMLSlideShow();
|
try (XMLSlideShow ppt = new XMLSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
XSLFSlide slide1 = ppt.createSlide();
|
XSLFSlide slide1 = ppt.createSlide();
|
||||||
XSLFSlide slide2 = ppt.createSlide();
|
XSLFSlide slide2 = ppt.createSlide();
|
||||||
|
|
||||||
XSLFTextBox shape1 = slide1.createTextBox();
|
XSLFTextBox shape1 = slide1.createTextBox();
|
||||||
shape1.setAnchor(new Rectangle(50, 50, 200, 50));
|
shape1.setAnchor(new Rectangle(50, 50, 200, 50));
|
||||||
XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun();
|
XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun();
|
||||||
XSLFHyperlink link1 = r1.createHyperlink();
|
XSLFHyperlink link1 = r1.createHyperlink();
|
||||||
r1.setText("http://poi.apache.org"); // visible text
|
r1.setText("http://poi.apache.org"); // visible text
|
||||||
link1.setAddress("http://poi.apache.org"); // link address
|
link1.setAddress("http://poi.apache.org"); // link address
|
||||||
|
|
||||||
XSLFTextBox shape2 = slide1.createTextBox();
|
XSLFTextBox shape2 = slide1.createTextBox();
|
||||||
shape2.setAnchor(new Rectangle(300, 50, 200, 50));
|
shape2.setAnchor(new Rectangle(300, 50, 200, 50));
|
||||||
XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun();
|
XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun();
|
||||||
XSLFHyperlink link2 = r2.createHyperlink();
|
XSLFHyperlink link2 = r2.createHyperlink();
|
||||||
r2.setText("Go to the second slide"); // visible text
|
r2.setText("Go to the second slide"); // visible text
|
||||||
link2.linkToSlide(slide2); // link address
|
link2.linkToSlide(slide2); // link address
|
||||||
|
|
||||||
|
|
||||||
|
try (FileOutputStream out = new FileOutputStream("hyperlinks.pptx")) {
|
||||||
FileOutputStream out = new FileOutputStream("hyperlinks.pptx");
|
ppt.write(out);
|
||||||
ppt.write(out);
|
}
|
||||||
out.close();
|
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,19 +32,17 @@ import org.apache.poi.sl.usermodel.AutoNumberingScheme;
|
||||||
public class Tutorial7 {
|
public class Tutorial7 {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
XMLSlideShow ppt = new XMLSlideShow();
|
try (XMLSlideShow ppt = new XMLSlideShow()) {
|
||||||
|
|
||||||
try {
|
|
||||||
XSLFSlide slide = ppt.createSlide();
|
XSLFSlide slide = ppt.createSlide();
|
||||||
XSLFTextBox shape = slide.createTextBox();
|
XSLFTextBox shape = slide.createTextBox();
|
||||||
shape.setAnchor(new Rectangle(50, 50, 400, 200));
|
shape.setAnchor(new Rectangle(50, 50, 400, 200));
|
||||||
|
|
||||||
XSLFTextParagraph p1 = shape.addNewTextParagraph();
|
XSLFTextParagraph p1 = shape.addNewTextParagraph();
|
||||||
p1.setIndentLevel(0);
|
p1.setIndentLevel(0);
|
||||||
p1.setBullet(true);
|
p1.setBullet(true);
|
||||||
XSLFTextRun r1 = p1.addNewTextRun();
|
XSLFTextRun r1 = p1.addNewTextRun();
|
||||||
r1.setText("Bullet1");
|
r1.setText("Bullet1");
|
||||||
|
|
||||||
XSLFTextParagraph p2 = shape.addNewTextParagraph();
|
XSLFTextParagraph p2 = shape.addNewTextParagraph();
|
||||||
// indentation before text
|
// indentation before text
|
||||||
p2.setLeftMargin(60d);
|
p2.setLeftMargin(60d);
|
||||||
|
@ -58,33 +56,31 @@ public class Tutorial7 {
|
||||||
p2.setIndentLevel(1);
|
p2.setIndentLevel(1);
|
||||||
XSLFTextRun r2 = p2.addNewTextRun();
|
XSLFTextRun r2 = p2.addNewTextRun();
|
||||||
r2.setText("Bullet2");
|
r2.setText("Bullet2");
|
||||||
|
|
||||||
// the next three paragraphs form an auto-numbered list
|
// the next three paragraphs form an auto-numbered list
|
||||||
XSLFTextParagraph p3 = shape.addNewTextParagraph();
|
XSLFTextParagraph p3 = shape.addNewTextParagraph();
|
||||||
p3.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
|
p3.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
|
||||||
p3.setIndentLevel(2);
|
p3.setIndentLevel(2);
|
||||||
XSLFTextRun r3 = p3.addNewTextRun();
|
XSLFTextRun r3 = p3.addNewTextRun();
|
||||||
r3.setText("Numbered List Item - 1");
|
r3.setText("Numbered List Item - 1");
|
||||||
|
|
||||||
XSLFTextParagraph p4 = shape.addNewTextParagraph();
|
XSLFTextParagraph p4 = shape.addNewTextParagraph();
|
||||||
p4.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 2);
|
p4.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 2);
|
||||||
p4.setIndentLevel(2);
|
p4.setIndentLevel(2);
|
||||||
XSLFTextRun r4 = p4.addNewTextRun();
|
XSLFTextRun r4 = p4.addNewTextRun();
|
||||||
r4.setText("Numbered List Item - 2");
|
r4.setText("Numbered List Item - 2");
|
||||||
|
|
||||||
XSLFTextParagraph p5 = shape.addNewTextParagraph();
|
XSLFTextParagraph p5 = shape.addNewTextParagraph();
|
||||||
p5.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 3);
|
p5.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 3);
|
||||||
p5.setIndentLevel(2);
|
p5.setIndentLevel(2);
|
||||||
XSLFTextRun r5 = p5.addNewTextRun();
|
XSLFTextRun r5 = p5.addNewTextRun();
|
||||||
r5.setText("Numbered List Item - 3");
|
r5.setText("Numbered List Item - 3");
|
||||||
|
|
||||||
shape.resizeToFitText();
|
shape.resizeToFitText();
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("list.pptx");
|
try (FileOutputStream out = new FileOutputStream("list.pptx")) {
|
||||||
ppt.write(out);
|
ppt.write(out);
|
||||||
out.close();
|
}
|
||||||
} finally {
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -40,31 +40,30 @@ public class Step1 {
|
||||||
}
|
}
|
||||||
|
|
||||||
FileInputStream fis = new FileInputStream(args[0]);
|
FileInputStream fis = new FileInputStream(args[0]);
|
||||||
XMLSlideShow ppt = new XMLSlideShow(fis);
|
try (XMLSlideShow ppt = new XMLSlideShow(fis)) {
|
||||||
fis.close();
|
fis.close();
|
||||||
|
|
||||||
for(XSLFSlide slide : ppt.getSlides()){
|
for (XSLFSlide slide : ppt.getSlides()) {
|
||||||
System.out.println("Title: " + slide.getTitle());
|
System.out.println("Title: " + slide.getTitle());
|
||||||
|
|
||||||
for(XSLFShape shape : slide.getShapes()){
|
for (XSLFShape shape : slide.getShapes()) {
|
||||||
if(shape instanceof XSLFTextShape) {
|
if (shape instanceof XSLFTextShape) {
|
||||||
XSLFTextShape tsh = (XSLFTextShape)shape;
|
XSLFTextShape tsh = (XSLFTextShape) shape;
|
||||||
for(XSLFTextParagraph p : tsh){
|
for (XSLFTextParagraph p : tsh) {
|
||||||
System.out.println("Paragraph level: " + p.getIndentLevel());
|
System.out.println("Paragraph level: " + p.getIndentLevel());
|
||||||
for(XSLFTextRun r : p){
|
for (XSLFTextRun r : p) {
|
||||||
System.out.println(r.getRawText());
|
System.out.println(r.getRawText());
|
||||||
System.out.println(" bold: " + r.isBold());
|
System.out.println(" bold: " + r.isBold());
|
||||||
System.out.println(" italic: " + r.isItalic());
|
System.out.println(" italic: " + r.isItalic());
|
||||||
System.out.println(" underline: " + r.isUnderlined());
|
System.out.println(" underline: " + r.isUnderlined());
|
||||||
System.out.println(" font.family: " + r.getFontFamily());
|
System.out.println(" font.family: " + r.getFontFamily());
|
||||||
System.out.println(" font.size: " + r.getFontSize());
|
System.out.println(" font.size: " + r.getFontSize());
|
||||||
System.out.println(" font.color: " + r.getFontColor());
|
System.out.println(" font.color: " + r.getFontColor());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ppt.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,45 +33,45 @@ import java.io.FileOutputStream;
|
||||||
*/
|
*/
|
||||||
public class Step2 {
|
public class Step2 {
|
||||||
public static void main(String[] args) throws Exception{
|
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
|
// first see what slide layouts are available by default
|
||||||
System.out.println("Available slide layouts:");
|
System.out.println("Available slide layouts:");
|
||||||
for(XSLFSlideMaster master : ppt.getSlideMasters()){
|
for (XSLFSlideMaster master : ppt.getSlideMasters()) {
|
||||||
for(XSLFSlideLayout layout : master.getSlideLayouts()){
|
for (XSLFSlideLayout layout : master.getSlideLayouts()) {
|
||||||
System.out.println(layout.getType());
|
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -42,8 +42,7 @@ import org.xml.sax.helpers.XMLReaderFactory;
|
||||||
*/
|
*/
|
||||||
public class FromHowTo {
|
public class FromHowTo {
|
||||||
public void processFirstSheet(String filename) throws Exception {
|
public void processFirstSheet(String filename) throws Exception {
|
||||||
OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
|
try (OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ)) {
|
||||||
try {
|
|
||||||
XSSFReader r = new XSSFReader(pkg);
|
XSSFReader r = new XSSFReader(pkg);
|
||||||
SharedStringsTable sst = r.getSharedStringsTable();
|
SharedStringsTable sst = r.getSharedStringsTable();
|
||||||
|
|
||||||
|
@ -54,14 +53,11 @@ public class FromHowTo {
|
||||||
InputSource sheetSource = new InputSource(sheet2);
|
InputSource sheetSource = new InputSource(sheet2);
|
||||||
parser.parse(sheetSource);
|
parser.parse(sheetSource);
|
||||||
sheet2.close();
|
sheet2.close();
|
||||||
} finally {
|
|
||||||
pkg.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void processAllSheets(String filename) throws Exception {
|
public void processAllSheets(String filename) throws Exception {
|
||||||
OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
|
try (OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ)) {
|
||||||
try {
|
|
||||||
XSSFReader r = new XSSFReader(pkg);
|
XSSFReader r = new XSSFReader(pkg);
|
||||||
SharedStringsTable sst = r.getSharedStringsTable();
|
SharedStringsTable sst = r.getSharedStringsTable();
|
||||||
|
|
||||||
|
@ -76,8 +72,6 @@ public class FromHowTo {
|
||||||
sheet.close();
|
sheet.close();
|
||||||
System.out.println("");
|
System.out.println("");
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
pkg.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -31,26 +31,24 @@ public class Outlining {
|
||||||
}
|
}
|
||||||
|
|
||||||
private void collapseRow() throws IOException {
|
private void collapseRow() throws IOException {
|
||||||
SXSSFWorkbook wb2 = new SXSSFWorkbook(100);
|
try (SXSSFWorkbook wb2 = new SXSSFWorkbook(100)) {
|
||||||
SXSSFSheet sheet2 = wb2.createSheet("new sheet");
|
SXSSFSheet sheet2 = wb2.createSheet("new sheet");
|
||||||
|
|
||||||
int rowCount = 20;
|
int rowCount = 20;
|
||||||
for (int i = 0; i < rowCount; i++) {
|
for (int i = 0; i < rowCount; i++) {
|
||||||
sheet2.createRow(i);
|
sheet2.createRow(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
sheet2.groupRow(4, 9);
|
sheet2.groupRow(4, 9);
|
||||||
sheet2.groupRow(11, 19);
|
sheet2.groupRow(11, 19);
|
||||||
|
|
||||||
sheet2.setRowGroupCollapsed(4, true);
|
sheet2.setRowGroupCollapsed(4, true);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx")) {
|
||||||
try {
|
wb2.write(fileOut);
|
||||||
wb2.write(fileOut);
|
} finally {
|
||||||
} finally {
|
wb2.dispose();
|
||||||
fileOut.close();
|
}
|
||||||
wb2.dispose();
|
|
||||||
wb2.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -45,34 +45,33 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl;
|
||||||
public class AligningCells {
|
public class AligningCells {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
XSSFWorkbook wb = new XSSFWorkbook();
|
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||||
|
|
||||||
XSSFSheet sheet = wb.createSheet();
|
XSSFSheet sheet = wb.createSheet();
|
||||||
XSSFRow row = sheet.createRow(2);
|
XSSFRow row = sheet.createRow(2);
|
||||||
row.setHeightInPoints(30);
|
row.setHeightInPoints(30);
|
||||||
for (int i = 0; i < 8; i++) {
|
for (int i = 0; i < 8; i++) {
|
||||||
//column width is set in units of 1/256th of a character width
|
//column width is set in units of 1/256th of a character width
|
||||||
sheet.setColumnWidth(i, 256 * 15);
|
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -86,30 +86,29 @@ public class BigGridDemo {
|
||||||
// Step 1. Create a template file. Setup sheets and workbook-level objects such as
|
// Step 1. Create a template file. Setup sheets and workbook-level objects such as
|
||||||
// cell styles, number formats, etc.
|
// cell styles, number formats, etc.
|
||||||
|
|
||||||
XSSFWorkbook wb = new XSSFWorkbook();
|
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||||
XSSFSheet sheet = wb.createSheet("Big Grid");
|
XSSFSheet sheet = wb.createSheet("Big Grid");
|
||||||
|
|
||||||
Map<String, XSSFCellStyle> styles = createStyles(wb);
|
Map<String, XSSFCellStyle> styles = createStyles(wb);
|
||||||
//name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml
|
//name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml
|
||||||
String sheetRef = sheet.getPackagePart().getPartName().getName();
|
String sheetRef = sheet.getPackagePart().getPartName().getName();
|
||||||
|
|
||||||
//save the template
|
//save the template
|
||||||
FileOutputStream os = new FileOutputStream("template.xlsx");
|
FileOutputStream os = new FileOutputStream("template.xlsx");
|
||||||
wb.write(os);
|
wb.write(os);
|
||||||
os.close();
|
os.close();
|
||||||
|
|
||||||
//Step 2. Generate XML file.
|
//Step 2. Generate XML file.
|
||||||
File tmp = File.createTempFile("sheet", ".xml");
|
File tmp = File.createTempFile("sheet", ".xml");
|
||||||
Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING);
|
Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING);
|
||||||
generate(fw, styles);
|
generate(fw, styles);
|
||||||
fw.close();
|
fw.close();
|
||||||
|
|
||||||
//Step 3. Substitute the template entry with the generated data
|
//Step 3. Substitute the template entry with the generated data
|
||||||
FileOutputStream out = new FileOutputStream("big-grid.xlsx");
|
try (FileOutputStream out = new FileOutputStream("big-grid.xlsx")) {
|
||||||
substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out);
|
substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out);
|
||||||
out.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -194,28 +193,23 @@ public class BigGridDemo {
|
||||||
* @param out the stream to write the result to
|
* @param out the stream to write the result to
|
||||||
*/
|
*/
|
||||||
private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException {
|
private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException {
|
||||||
ZipFile zip = ZipHelper.openZipFile(zipfile);
|
try (ZipFile zip = ZipHelper.openZipFile(zipfile)) {
|
||||||
try {
|
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||||
ZipOutputStream zos = new ZipOutputStream(out);
|
Enumeration<? extends ZipEntry> en = zip.entries();
|
||||||
|
while (en.hasMoreElements()) {
|
||||||
Enumeration<? extends ZipEntry> en = zip.entries();
|
ZipEntry ze = en.nextElement();
|
||||||
while (en.hasMoreElements()) {
|
if (!ze.getName().equals(entry)) {
|
||||||
ZipEntry ze = en.nextElement();
|
zos.putNextEntry(new ZipEntry(ze.getName()));
|
||||||
if(!ze.getName().equals(entry)){
|
try (InputStream is = zip.getInputStream(ze)) {
|
||||||
zos.putNextEntry(new ZipEntry(ze.getName()));
|
copyStream(is, zos);
|
||||||
InputStream is = zip.getInputStream(ze);
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
zos.putNextEntry(new ZipEntry(entry));
|
||||||
|
try (InputStream is = new FileInputStream(tmpfile)) {
|
||||||
copyStream(is, zos);
|
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -55,80 +55,80 @@ public class CalendarDemo {
|
||||||
|
|
||||||
int year = calendar.get(Calendar.YEAR);
|
int year = calendar.get(Calendar.YEAR);
|
||||||
|
|
||||||
XSSFWorkbook wb = new XSSFWorkbook();
|
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||||
Map<String, XSSFCellStyle> styles = createStyles(wb);
|
Map<String, XSSFCellStyle> styles = createStyles(wb);
|
||||||
|
|
||||||
for (int month = 0; month < 12; month++) {
|
for (int month = 0; month < 12; month++) {
|
||||||
calendar.set(Calendar.MONTH, month);
|
calendar.set(Calendar.MONTH, month);
|
||||||
calendar.set(Calendar.DAY_OF_MONTH, 1);
|
calendar.set(Calendar.DAY_OF_MONTH, 1);
|
||||||
//create a sheet for each month
|
//create a sheet for each month
|
||||||
XSSFSheet sheet = wb.createSheet(months[month]);
|
XSSFSheet sheet = wb.createSheet(months[month]);
|
||||||
|
|
||||||
//turn off gridlines
|
//turn off gridlines
|
||||||
sheet.setDisplayGridlines(false);
|
sheet.setDisplayGridlines(false);
|
||||||
sheet.setPrintGridlines(false);
|
sheet.setPrintGridlines(false);
|
||||||
XSSFPrintSetup printSetup = sheet.getPrintSetup();
|
XSSFPrintSetup printSetup = sheet.getPrintSetup();
|
||||||
printSetup.setOrientation(PrintOrientation.LANDSCAPE);
|
printSetup.setOrientation(PrintOrientation.LANDSCAPE);
|
||||||
sheet.setFitToPage(true);
|
sheet.setFitToPage(true);
|
||||||
sheet.setHorizontallyCenter(true);
|
sheet.setHorizontallyCenter(true);
|
||||||
|
|
||||||
//the header row: centered text in 48pt font
|
//the header row: centered text in 48pt font
|
||||||
XSSFRow headerRow = sheet.createRow(0);
|
XSSFRow headerRow = sheet.createRow(0);
|
||||||
headerRow.setHeightInPoints(80);
|
headerRow.setHeightInPoints(80);
|
||||||
XSSFCell titleCell = headerRow.createCell(0);
|
XSSFCell titleCell = headerRow.createCell(0);
|
||||||
titleCell.setCellValue(months[month] + " " + year);
|
titleCell.setCellValue(months[month] + " " + year);
|
||||||
titleCell.setCellStyle(styles.get("title"));
|
titleCell.setCellStyle(styles.get("title"));
|
||||||
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
|
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));
|
||||||
|
|
||||||
//header with month titles
|
//header with month titles
|
||||||
XSSFRow monthRow = sheet.createRow(1);
|
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);
|
|
||||||
for (int i = 0; i < days.length; i++) {
|
for (int i = 0; i < days.length; i++) {
|
||||||
XSSFCell dayCell_1 = row.createCell(i*2);
|
//for compatibility with HSSF we have to set column width in units of 1/256th of a character width
|
||||||
XSSFCell dayCell_2 = row.createCell(i*2 + 1);
|
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
|
||||||
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
|
sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1));
|
||||||
if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
|
XSSFCell monthCell = monthRow.createCell(i * 2);
|
||||||
dayCell_1.setCellValue(day);
|
monthCell.setCellValue(days[i]);
|
||||||
calendar.set(Calendar.DAY_OF_MONTH, ++day);
|
monthCell.setCellStyle(styles.get("month"));
|
||||||
|
|
||||||
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
|
int cnt = 1, day = 1;
|
||||||
FileOutputStream out = new FileOutputStream("calendar-"+year+".xlsx");
|
int rownum = 2;
|
||||||
wb.write(out);
|
for (int j = 0; j < 6; j++) {
|
||||||
out.close();
|
XSSFRow row = sheet.createRow(rownum++);
|
||||||
|
row.setHeightInPoints(100);
|
||||||
wb.close();
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -44,47 +44,45 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class CellComments {
|
public class CellComments {
|
||||||
public static void main(String[] args) throws IOException {
|
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);
|
Cell cell1 = sheet.createRow(3).createCell(5);
|
||||||
cell1.setCellValue("F4");
|
cell1.setCellValue("F4");
|
||||||
|
|
||||||
Drawing<?> drawing = sheet.createDrawingPatriarch();
|
Drawing<?> drawing = sheet.createDrawingPatriarch();
|
||||||
|
|
||||||
ClientAnchor anchor = factory.createClientAnchor();
|
ClientAnchor anchor = factory.createClientAnchor();
|
||||||
|
|
||||||
Comment comment1 = drawing.createCellComment(anchor);
|
Comment comment1 = drawing.createCellComment(anchor);
|
||||||
RichTextString str1 = factory.createRichTextString("Hello, World!");
|
RichTextString str1 = factory.createRichTextString("Hello, World!");
|
||||||
comment1.setString(str1);
|
comment1.setString(str1);
|
||||||
comment1.setAuthor("Apache POI");
|
comment1.setAuthor("Apache POI");
|
||||||
cell1.setCellComment(comment1);
|
cell1.setCellComment(comment1);
|
||||||
|
|
||||||
Cell cell2 = sheet.createRow(2).createCell(2);
|
Cell cell2 = sheet.createRow(2).createCell(2);
|
||||||
cell2.setCellValue("C3");
|
cell2.setCellValue("C3");
|
||||||
|
|
||||||
Comment comment2 = drawing.createCellComment(anchor);
|
Comment comment2 = drawing.createCellComment(anchor);
|
||||||
RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
|
RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
|
||||||
//apply custom font to the text in the comment
|
//apply custom font to the text in the comment
|
||||||
Font font = wb.createFont();
|
Font font = wb.createFont();
|
||||||
font.setFontName("Arial");
|
font.setFontName("Arial");
|
||||||
font.setFontHeightInPoints((short)14);
|
font.setFontHeightInPoints((short) 14);
|
||||||
font.setBold(true);
|
font.setBold(true);
|
||||||
font.setColor(IndexedColors.RED.getIndex());
|
font.setColor(IndexedColors.RED.getIndex());
|
||||||
str2.applyFont(font);
|
str2.applyFont(font);
|
||||||
|
|
||||||
comment2.setString(str2);
|
comment2.setString(str2);
|
||||||
comment2.setAuthor("Apache POI");
|
comment2.setAuthor("Apache POI");
|
||||||
comment2.setAddress(new CellAddress("C3"));
|
comment2.setAddress(new CellAddress("C3"));
|
||||||
|
|
||||||
String fname = "comments.xlsx";
|
try (FileOutputStream out = new FileOutputStream("comments.xlsx")) {
|
||||||
FileOutputStream out = new FileOutputStream(fname);
|
wb.write(out);
|
||||||
wb.write(out);
|
}
|
||||||
out.close();
|
}
|
||||||
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -36,54 +36,53 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class CreateCell {
|
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 {
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
|
Row row = sheet.createRow((short) 0);
|
||||||
CreationHelper creationHelper = wb.getCreationHelper();
|
// Create a cell and put a value in it.
|
||||||
Sheet sheet = wb.createSheet("new sheet");
|
Cell cell = row.createCell((short) 0);
|
||||||
|
cell.setCellValue(1);
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
//numeric value
|
||||||
Row row = sheet.createRow((short)0);
|
row.createCell(1).setCellValue(1.2);
|
||||||
// Create a cell and put a value in it.
|
|
||||||
Cell cell = row.createCell((short)0);
|
|
||||||
cell.setCellValue(1);
|
|
||||||
|
|
||||||
//numeric value
|
//plain string value
|
||||||
row.createCell(1).setCellValue(1.2);
|
row.createCell(2).setCellValue("This is a string cell");
|
||||||
|
|
||||||
//plain string value
|
//rich text string
|
||||||
row.createCell(2).setCellValue("This is a string cell");
|
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
|
//boolean value
|
||||||
RichTextString str = creationHelper.createRichTextString("Apache");
|
row.createCell(4).setCellValue(true);
|
||||||
Font font = wb.createFont();
|
|
||||||
font.setItalic(true);
|
|
||||||
font.setUnderline(Font.U_SINGLE);
|
|
||||||
str.applyFont(font);
|
|
||||||
row.createCell(3).setCellValue(str);
|
|
||||||
|
|
||||||
//boolean value
|
//formula
|
||||||
row.createCell(4).setCellValue(true);
|
row.createCell(5).setCellFormula("SUM(A1:B1)");
|
||||||
|
|
||||||
//formula
|
//date
|
||||||
row.createCell(5).setCellFormula("SUM(A1:B1)");
|
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
|
//hyperlink
|
||||||
CellStyle style = wb.createCellStyle();
|
row.createCell(7).setCellFormula("SUM(A1:B1)");
|
||||||
style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
|
cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")");
|
||||||
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\")");
|
|
||||||
|
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,31 +34,31 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class CreatePivotTable {
|
public class CreatePivotTable {
|
||||||
|
|
||||||
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
|
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
|
||||||
XSSFWorkbook wb = new XSSFWorkbook();
|
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||||
XSSFSheet sheet = wb.createSheet();
|
XSSFSheet sheet = wb.createSheet();
|
||||||
|
|
||||||
//Create some data to build the pivot table on
|
//Create some data to build the pivot table on
|
||||||
setCellData(sheet);
|
setCellData(sheet);
|
||||||
|
|
||||||
AreaReference source = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
|
AreaReference source = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
|
||||||
CellReference position = new CellReference("H5");
|
CellReference position = new CellReference("H5");
|
||||||
// Create a pivot table on this sheet, with H5 as the top-left cell..
|
// 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
|
// The pivot table's data source is on the same sheet in A1:D4
|
||||||
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
|
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
|
||||||
//Configure the pivot table
|
//Configure the pivot table
|
||||||
//Use first column as row label
|
//Use first column as row label
|
||||||
pivotTable.addRowLabel(0);
|
pivotTable.addRowLabel(0);
|
||||||
//Sum up the second column
|
//Sum up the second column
|
||||||
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
|
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
|
||||||
//Set the third column as filter
|
//Set the third column as filter
|
||||||
pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
|
pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
|
||||||
//Add filter on forth column
|
//Add filter on forth column
|
||||||
pivotTable.addReportFilter(3);
|
pivotTable.addReportFilter(3);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void setCellData(XSSFSheet sheet){
|
public static void setCellData(XSSFSheet sheet){
|
||||||
|
|
|
@ -38,32 +38,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class CreatePivotTable2 {
|
public class CreatePivotTable2 {
|
||||||
|
|
||||||
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
|
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
|
||||||
XSSFWorkbook wb = new XSSFWorkbook();
|
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||||
XSSFSheet sheet = wb.createSheet();
|
XSSFSheet sheet = wb.createSheet();
|
||||||
|
|
||||||
//Create some data to build the pivot table on
|
//Create some data to build the pivot table on
|
||||||
setCellData(sheet);
|
setCellData(sheet);
|
||||||
|
|
||||||
AreaReference source = new AreaReference("A1:E7", SpreadsheetVersion.EXCEL2007);
|
AreaReference source = new AreaReference("A1:E7", SpreadsheetVersion.EXCEL2007);
|
||||||
CellReference position = new CellReference("H1");
|
CellReference position = new CellReference("H1");
|
||||||
// Create a pivot table on this sheet, with H1 as the top-left cell..
|
// 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
|
// The pivot table's data source is on the same sheet in A1:E7
|
||||||
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
|
XSSFPivotTable pivotTable = sheet.createPivotTable(source, position);
|
||||||
//Configure the pivot table
|
//Configure the pivot table
|
||||||
//Use first column as row label
|
//Use first column as row label
|
||||||
pivotTable.addRowLabel(0);
|
pivotTable.addRowLabel(0);
|
||||||
//Sum up the second column with column title and data format
|
//Sum up the second column with column title and data format
|
||||||
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1, "Values", "#,##0.00");
|
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1, "Values", "#,##0.00");
|
||||||
//Use third column (month) as columns (side by side)
|
//Use third column (month) as columns (side by side)
|
||||||
pivotTable.addColLabel(3, "DD.MM.YYYY");
|
pivotTable.addColLabel(3, "DD.MM.YYYY");
|
||||||
|
|
||||||
//Add filter on forth column
|
//Add filter on forth column
|
||||||
pivotTable.addReportFilter(4);
|
pivotTable.addReportFilter(4);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable2.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable2.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void setCellData(XSSFSheet sheet){
|
public static void setCellData(XSSFSheet sheet){
|
||||||
|
|
|
@ -36,58 +36,58 @@ public class CreateTable {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
|
|
||||||
Workbook wb = new XSSFWorkbook();
|
try (Workbook wb = new XSSFWorkbook()) {
|
||||||
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
|
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
|
||||||
|
|
||||||
// Create
|
// Create
|
||||||
XSSFTable table = sheet.createTable();
|
XSSFTable table = sheet.createTable();
|
||||||
table.setName("Test");
|
table.setName("Test");
|
||||||
table.setDisplayName("Test_Table");
|
table.setDisplayName("Test_Table");
|
||||||
|
|
||||||
// For now, create the initial style in a low-level way
|
// For now, create the initial style in a low-level way
|
||||||
table.getCTTable().addNewTableStyleInfo();
|
table.getCTTable().addNewTableStyleInfo();
|
||||||
table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
|
table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
|
||||||
|
|
||||||
// Style the table
|
// Style the table
|
||||||
XSSFTableStyleInfo style = (XSSFTableStyleInfo)table.getStyle();
|
XSSFTableStyleInfo style = (XSSFTableStyleInfo) table.getStyle();
|
||||||
style.setName("TableStyleMedium2");
|
style.setName("TableStyleMedium2");
|
||||||
style.setShowColumnStripes(false);
|
style.setShowColumnStripes(false);
|
||||||
style.setShowRowStripes(true);
|
style.setShowRowStripes(true);
|
||||||
style.setFirstColumn(false);
|
style.setFirstColumn(false);
|
||||||
style.setLastColumn(false);
|
style.setLastColumn(false);
|
||||||
style.setShowRowStripes(true);
|
style.setShowRowStripes(true);
|
||||||
style.setShowColumnStripes(true);
|
style.setShowColumnStripes(true);
|
||||||
|
|
||||||
// Set the values for the table
|
// Set the values for the table
|
||||||
XSSFRow row;
|
XSSFRow row;
|
||||||
XSSFCell cell;
|
XSSFCell cell;
|
||||||
for(int i=0; i<3; i++) {
|
for (int i = 0; i < 3; i++) {
|
||||||
// Create row
|
// Create row
|
||||||
row = sheet.createRow(i);
|
row = sheet.createRow(i);
|
||||||
for(int j=0; j<3; j++) {
|
for (int j = 0; j < 3; j++) {
|
||||||
// Create cell
|
// Create cell
|
||||||
cell = row.createCell(j);
|
cell = row.createCell(j);
|
||||||
if(i == 0) {
|
if (i == 0) {
|
||||||
cell.setCellValue("Column"+(j+1));
|
cell.setCellValue("Column" + (j + 1));
|
||||||
} else {
|
} else {
|
||||||
cell.setCellValue((i+1)*(j+1));
|
cell.setCellValue((i + 1) * (j + 1));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
// Create the columns
|
||||||
// Create the columns
|
table.addColumn();
|
||||||
table.addColumn();
|
table.addColumn();
|
||||||
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);
|
|
||||||
|
|
||||||
// Save
|
// Set which area the table should be placed in
|
||||||
FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx");
|
AreaReference reference = wb.getCreationHelper().createAreaReference(
|
||||||
wb.write(fileOut);
|
new CellReference(0, 0), new CellReference(2, 2));
|
||||||
fileOut.close();
|
table.setCellReferences(reference);
|
||||||
wb.close();
|
|
||||||
|
// Save
|
||||||
|
try (FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx")) {
|
||||||
|
wb.write(fileOut);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,34 +35,33 @@ public class CreateUserDefinedDataFormats {
|
||||||
|
|
||||||
|
|
||||||
public static void main(String[]args) throws IOException {
|
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("format sheet");
|
Sheet sheet = wb.createSheet("format sheet");
|
||||||
CellStyle style;
|
CellStyle style;
|
||||||
DataFormat format = wb.createDataFormat();
|
DataFormat format = wb.createDataFormat();
|
||||||
Row row;
|
Row row;
|
||||||
Cell cell;
|
Cell cell;
|
||||||
short rowNum = 0;
|
short rowNum = 0;
|
||||||
short colNum = 0;
|
short colNum = 0;
|
||||||
|
|
||||||
row = sheet.createRow(rowNum);
|
row = sheet.createRow(rowNum);
|
||||||
cell = row.createCell(colNum);
|
cell = row.createCell(colNum);
|
||||||
cell.setCellValue(11111.25);
|
cell.setCellValue(11111.25);
|
||||||
style = wb.createCellStyle();
|
style = wb.createCellStyle();
|
||||||
style.setDataFormat(format.getFormat("0.0"));
|
style.setDataFormat(format.getFormat("0.0"));
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
row = sheet.createRow(++rowNum);
|
row = sheet.createRow(++rowNum);
|
||||||
cell = row.createCell(colNum);
|
cell = row.createCell(colNum);
|
||||||
cell.setCellValue(11111.25);
|
cell.setCellValue(11111.25);
|
||||||
style = wb.createCellStyle();
|
style = wb.createCellStyle();
|
||||||
style.setDataFormat(format.getFormat("#,##0.0000"));
|
style.setDataFormat(format.getFormat("#,##0.0000"));
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,18 +29,16 @@ import java.io.ByteArrayOutputStream;
|
||||||
public class CustomXMLMapping {
|
public class CustomXMLMapping {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
OPCPackage pkg = OPCPackage.open(args[0]);
|
try (OPCPackage pkg = OPCPackage.open(args[0]);
|
||||||
XSSFWorkbook wb = new XSSFWorkbook(pkg);
|
XSSFWorkbook wb = new XSSFWorkbook(pkg)) {
|
||||||
|
for (XSSFMap map : wb.getCustomXMLMappings()) {
|
||||||
|
XSSFExportToXml exporter = new XSSFExportToXml(map);
|
||||||
|
|
||||||
for (XSSFMap map : wb.getCustomXMLMappings()) {
|
ByteArrayOutputStream os = new ByteArrayOutputStream();
|
||||||
XSSFExportToXml exporter = new XSSFExportToXml(map);
|
exporter.exportToXML(os, true);
|
||||||
|
String xml = os.toString("UTF-8");
|
||||||
ByteArrayOutputStream os = new ByteArrayOutputStream();
|
System.out.println(xml);
|
||||||
exporter.exportToXML(os, true);
|
}
|
||||||
String xml = os.toString("UTF-8");
|
|
||||||
System.out.println(xml);
|
|
||||||
}
|
}
|
||||||
pkg.close();
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,36 +32,36 @@ import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||||
*/
|
*/
|
||||||
public class EmbeddedObjects {
|
public class EmbeddedObjects {
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
XSSFWorkbook workbook = new XSSFWorkbook(args[0]);
|
try (XSSFWorkbook workbook = new XSSFWorkbook(args[0])) {
|
||||||
for (PackagePart pPart : workbook.getAllEmbedds()) {
|
for (PackagePart pPart : workbook.getAllEmbedds()) {
|
||||||
String contentType = pPart.getContentType();
|
String contentType = pPart.getContentType();
|
||||||
InputStream is = pPart.getInputStream();
|
try (InputStream is = pPart.getInputStream()) {
|
||||||
Closeable document;
|
Closeable document;
|
||||||
if (contentType.equals("application/vnd.ms-excel")) {
|
if (contentType.equals("application/vnd.ms-excel")) {
|
||||||
// Excel Workbook - either binary or OpenXML
|
// Excel Workbook - either binary or OpenXML
|
||||||
document = new HSSFWorkbook(is);
|
document = new HSSFWorkbook(is);
|
||||||
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
|
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
|
||||||
// Excel Workbook - OpenXML file format
|
// Excel Workbook - OpenXML file format
|
||||||
document = new XSSFWorkbook(is);
|
document = new XSSFWorkbook(is);
|
||||||
} else if (contentType.equals("application/msword")) {
|
} else if (contentType.equals("application/msword")) {
|
||||||
// Word Document - binary (OLE2CDF) file format
|
// Word Document - binary (OLE2CDF) file format
|
||||||
document = new HWPFDocument(is);
|
document = new HWPFDocument(is);
|
||||||
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
|
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
|
||||||
// Word Document - OpenXML file format
|
// Word Document - OpenXML file format
|
||||||
document = new XWPFDocument(is);
|
document = new XWPFDocument(is);
|
||||||
} else if (contentType.equals("application/vnd.ms-powerpoint")) {
|
} else if (contentType.equals("application/vnd.ms-powerpoint")) {
|
||||||
// PowerPoint Document - binary file format
|
// PowerPoint Document - binary file format
|
||||||
document = new HSLFSlideShow(is);
|
document = new HSLFSlideShow(is);
|
||||||
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
|
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
|
||||||
// PowerPoint Document - OpenXML file format
|
// PowerPoint Document - OpenXML file format
|
||||||
document = new XMLSlideShow(is);
|
document = new XMLSlideShow(is);
|
||||||
} else {
|
} else {
|
||||||
// Any other type of embedded object.
|
// Any other type of embedded object.
|
||||||
document = is;
|
document = is;
|
||||||
|
}
|
||||||
|
document.close();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
document.close();
|
|
||||||
is.close();
|
|
||||||
}
|
}
|
||||||
workbook.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -34,32 +34,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class FillsAndColors {
|
public class FillsAndColors {
|
||||||
public static void main(String[] args) throws IOException {
|
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("new sheet");
|
Sheet sheet = wb.createSheet("new sheet");
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
Row row = sheet.createRow(1);
|
Row row = sheet.createRow(1);
|
||||||
|
|
||||||
// Aqua background
|
// Aqua background
|
||||||
CellStyle style = wb.createCellStyle();
|
CellStyle style = wb.createCellStyle();
|
||||||
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
|
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
|
||||||
style.setFillPattern(FillPatternType.BIG_SPOTS);
|
style.setFillPattern(FillPatternType.BIG_SPOTS);
|
||||||
Cell cell = row.createCell(1);
|
Cell cell = row.createCell(1);
|
||||||
cell.setCellValue(new XSSFRichTextString("X"));
|
cell.setCellValue(new XSSFRichTextString("X"));
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
// Orange "foreground", foreground being the fill foreground not the font color.
|
// Orange "foreground", foreground being the fill foreground not the font color.
|
||||||
style = wb.createCellStyle();
|
style = wb.createCellStyle();
|
||||||
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
|
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
|
||||||
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||||
cell = row.createCell(2);
|
cell = row.createCell(2);
|
||||||
cell.setCellValue(new XSSFRichTextString("X"));
|
cell.setCellValue(new XSSFRichTextString("X"));
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,20 +27,20 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class FitSheetToOnePage {
|
public class FitSheetToOnePage {
|
||||||
|
|
||||||
public static void main(String[]args) throws IOException {
|
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("format sheet");
|
Sheet sheet = wb.createSheet("format sheet");
|
||||||
PrintSetup ps = sheet.getPrintSetup();
|
PrintSetup ps = sheet.getPrintSetup();
|
||||||
|
|
||||||
sheet.setAutobreaks(true);
|
sheet.setAutobreaks(true);
|
||||||
|
|
||||||
ps.setFitHeight((short) 1);
|
ps.setFitHeight((short) 1);
|
||||||
ps.setFitWidth((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");
|
try (FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,58 +28,57 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
|
|
||||||
public class HeadersAndFooters {
|
public class HeadersAndFooters {
|
||||||
|
|
||||||
|
|
||||||
public static void main(String[]args) throws IOException {
|
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("first-header - format sheet");
|
Sheet sheet = wb.createSheet("first-header - format sheet");
|
||||||
sheet.createRow(0).createCell(0).setCellValue(123);
|
sheet.createRow(0).createCell(0).setCellValue(123);
|
||||||
|
|
||||||
//set page numbers in the footer
|
//set page numbers in the footer
|
||||||
Footer footer = sheet.getFooter();
|
Footer footer = sheet.getFooter();
|
||||||
//&P == current page number
|
//&P == current page number
|
||||||
//&N == page numbers
|
//&N == page numbers
|
||||||
footer.setRight("Page &P of &N");
|
footer.setRight("Page &P of &N");
|
||||||
|
|
||||||
|
|
||||||
Header firstHeader=((XSSFSheet)sheet).getFirstHeader();
|
Header firstHeader = ((XSSFSheet) sheet).getFirstHeader();
|
||||||
//&F == workbook file name
|
//&F == workbook file name
|
||||||
firstHeader.setLeft("&F ......... first header");
|
firstHeader.setLeft("&F ......... first header");
|
||||||
|
|
||||||
for(int i=0;i<100;i=i+10){
|
for (int i = 0; i < 100; i = i + 10) {
|
||||||
sheet.createRow(i).createCell(0).setCellValue(123);
|
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,64 +35,62 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class HyperlinkExample {
|
public class HyperlinkExample {
|
||||||
|
|
||||||
|
|
||||||
public static void main(String[]args) throws IOException {
|
public static void main(String[]args) throws IOException {
|
||||||
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
|
try (Workbook wb = new XSSFWorkbook()) { //or new HSSFWorkbook();
|
||||||
CreationHelper createHelper = wb.getCreationHelper();
|
CreationHelper createHelper = wb.getCreationHelper();
|
||||||
|
|
||||||
//cell style for hyperlinks
|
//cell style for hyperlinks
|
||||||
//by default hyperlinks are blue and underlined
|
//by default hyperlinks are blue and underlined
|
||||||
CellStyle hlink_style = wb.createCellStyle();
|
CellStyle hlink_style = wb.createCellStyle();
|
||||||
Font hlink_font = wb.createFont();
|
Font hlink_font = wb.createFont();
|
||||||
hlink_font.setUnderline(Font.U_SINGLE);
|
hlink_font.setUnderline(Font.U_SINGLE);
|
||||||
hlink_font.setColor(IndexedColors.BLUE.getIndex());
|
hlink_font.setColor(IndexedColors.BLUE.getIndex());
|
||||||
hlink_style.setFont(hlink_font);
|
hlink_style.setFont(hlink_font);
|
||||||
|
|
||||||
Cell cell;
|
Cell cell;
|
||||||
Sheet sheet = wb.createSheet("Hyperlinks");
|
Sheet sheet = wb.createSheet("Hyperlinks");
|
||||||
//URL
|
//URL
|
||||||
cell = sheet.createRow(0).createCell(0);
|
cell = sheet.createRow(0).createCell(0);
|
||||||
cell.setCellValue("URL Link");
|
cell.setCellValue("URL Link");
|
||||||
|
|
||||||
Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL);
|
Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL);
|
||||||
link.setAddress("http://poi.apache.org/");
|
link.setAddress("http://poi.apache.org/");
|
||||||
cell.setHyperlink(link);
|
cell.setHyperlink(link);
|
||||||
cell.setCellStyle(hlink_style);
|
cell.setCellStyle(hlink_style);
|
||||||
|
|
||||||
//link to a file in the current directory
|
//link to a file in the current directory
|
||||||
cell = sheet.createRow(1).createCell(0);
|
cell = sheet.createRow(1).createCell(0);
|
||||||
cell.setCellValue("File Link");
|
cell.setCellValue("File Link");
|
||||||
link = createHelper.createHyperlink(HyperlinkType.FILE);
|
link = createHelper.createHyperlink(HyperlinkType.FILE);
|
||||||
link.setAddress("link1.xls");
|
link.setAddress("link1.xls");
|
||||||
cell.setHyperlink(link);
|
cell.setHyperlink(link);
|
||||||
cell.setCellStyle(hlink_style);
|
cell.setCellStyle(hlink_style);
|
||||||
|
|
||||||
//e-mail link
|
//e-mail link
|
||||||
cell = sheet.createRow(2).createCell(0);
|
cell = sheet.createRow(2).createCell(0);
|
||||||
cell.setCellValue("Email Link");
|
cell.setCellValue("Email Link");
|
||||||
link = createHelper.createHyperlink(HyperlinkType.EMAIL);
|
link = createHelper.createHyperlink(HyperlinkType.EMAIL);
|
||||||
//note, if subject contains white spaces, make sure they are url-encoded
|
//note, if subject contains white spaces, make sure they are url-encoded
|
||||||
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
|
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
|
||||||
cell.setHyperlink(link);
|
cell.setHyperlink(link);
|
||||||
cell.setCellStyle(hlink_style);
|
cell.setCellStyle(hlink_style);
|
||||||
|
|
||||||
//link to a place in this workbook
|
//link to a place in this workbook
|
||||||
|
|
||||||
//create a target sheet and cell
|
//create a target sheet and cell
|
||||||
Sheet sheet2 = wb.createSheet("Target Sheet");
|
Sheet sheet2 = wb.createSheet("Target Sheet");
|
||||||
sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
|
sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
|
||||||
|
|
||||||
cell = sheet.createRow(3).createCell(0);
|
cell = sheet.createRow(3).createCell(0);
|
||||||
cell.setCellValue("Worksheet Link");
|
cell.setCellValue("Worksheet Link");
|
||||||
Hyperlink link2 = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
|
Hyperlink link2 = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
|
||||||
link2.setAddress("'Target Sheet'!A1");
|
link2.setAddress("'Target Sheet'!A1");
|
||||||
cell.setHyperlink(link2);
|
cell.setHyperlink(link2);
|
||||||
cell.setCellStyle(hlink_style);
|
cell.setCellStyle(hlink_style);
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("hyperinks.xlsx");
|
try (FileOutputStream out = new FileOutputStream("hyperinks.xlsx")) {
|
||||||
wb.write(out);
|
wb.write(out);
|
||||||
out.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,17 +32,17 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class IterateCells {
|
public class IterateCells {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
Workbook wb = new XSSFWorkbook(new FileInputStream(args[0]));
|
try (Workbook wb = new XSSFWorkbook(new FileInputStream(args[0]))) {
|
||||||
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
|
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
|
||||||
Sheet sheet = wb.getSheetAt(i);
|
Sheet sheet = wb.getSheetAt(i);
|
||||||
System.out.println(wb.getSheetName(i));
|
System.out.println(wb.getSheetName(i));
|
||||||
for (Row row : sheet) {
|
for (Row row : sheet) {
|
||||||
System.out.println("rownum: " + row.getRowNum());
|
System.out.println("rownum: " + row.getRowNum());
|
||||||
for (Cell cell : row) {
|
for (Cell cell : row) {
|
||||||
System.out.println(cell);
|
System.out.println(cell);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -44,50 +44,50 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class LineChart {
|
public class LineChart {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
Workbook wb = new XSSFWorkbook();
|
try (Workbook wb = new XSSFWorkbook()) {
|
||||||
Sheet sheet = wb.createSheet("linechart");
|
Sheet sheet = wb.createSheet("linechart");
|
||||||
final int NUM_OF_ROWS = 3;
|
final int NUM_OF_ROWS = 3;
|
||||||
final int NUM_OF_COLUMNS = 10;
|
final int NUM_OF_COLUMNS = 10;
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
Row row;
|
Row row;
|
||||||
Cell cell;
|
Cell cell;
|
||||||
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
|
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
|
||||||
row = sheet.createRow((short) rowIndex);
|
row = sheet.createRow((short) rowIndex);
|
||||||
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
|
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
|
||||||
cell = row.createCell((short) colIndex);
|
cell = row.createCell((short) colIndex);
|
||||||
cell.setCellValue(colIndex * (rowIndex + 1));
|
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,19 +33,19 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class MergingCells {
|
public class MergingCells {
|
||||||
public static void main(String[] args) throws IOException {
|
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("new sheet");
|
Sheet sheet = wb.createSheet("new sheet");
|
||||||
|
|
||||||
Row row = sheet.createRow((short) 1);
|
Row row = sheet.createRow((short) 1);
|
||||||
Cell cell = row.createCell((short) 1);
|
Cell cell = row.createCell((short) 1);
|
||||||
cell.setCellValue(new XSSFRichTextString("This is a test of merging"));
|
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
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,28 +32,28 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class NewLinesInCells {
|
public class NewLinesInCells {
|
||||||
|
|
||||||
public static void main(String[]args) throws IOException {
|
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();
|
Sheet sheet = wb.createSheet();
|
||||||
|
|
||||||
Row row = sheet.createRow(2);
|
Row row = sheet.createRow(2);
|
||||||
Cell cell = row.createCell(2);
|
Cell cell = row.createCell(2);
|
||||||
cell.setCellValue("Use \n with word wrap on to create a new line");
|
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
|
//to enable newlines you need set a cell styles with wrap=true
|
||||||
CellStyle cs = wb.createCellStyle();
|
CellStyle cs = wb.createCellStyle();
|
||||||
cs.setWrapText(true);
|
cs.setWrapText(true);
|
||||||
cell.setCellStyle(cs);
|
cell.setCellStyle(cs);
|
||||||
|
|
||||||
//increase row height to accomodate two lines of text
|
//increase row height to accomodate two lines of text
|
||||||
row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
|
row.setHeightInPoints((2 * sheet.getDefaultRowHeightInPoints()));
|
||||||
|
|
||||||
//adjust column width to fit the content
|
//adjust column width to fit the content
|
||||||
sheet.autoSizeColumn(2);
|
sheet.autoSizeColumn(2);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,50 +35,44 @@ public class Outlining {
|
||||||
|
|
||||||
|
|
||||||
private void groupRowColumn() throws IOException {
|
private void groupRowColumn() throws IOException {
|
||||||
Workbook wb = new XSSFWorkbook();
|
try (Workbook wb = new XSSFWorkbook()) {
|
||||||
Sheet sheet1 = wb.createSheet("new sheet");
|
Sheet sheet1 = wb.createSheet("new sheet");
|
||||||
|
|
||||||
sheet1.groupRow( 5, 14 );
|
sheet1.groupRow(5, 14);
|
||||||
sheet1.groupRow( 7, 14 );
|
sheet1.groupRow(7, 14);
|
||||||
sheet1.groupRow( 16, 19 );
|
sheet1.groupRow(16, 19);
|
||||||
|
|
||||||
sheet1.groupColumn( (short)4, (short)7 );
|
sheet1.groupColumn((short) 4, (short) 7);
|
||||||
sheet1.groupColumn( (short)9, (short)12 );
|
sheet1.groupColumn((short) 9, (short) 12);
|
||||||
sheet1.groupColumn( (short)10, (short)11 );
|
sheet1.groupColumn((short) 10, (short) 11);
|
||||||
|
|
||||||
OutputStream fileOut = new FileOutputStream("outlining.xlsx");
|
try (OutputStream fileOut = new FileOutputStream("outlining.xlsx")) {
|
||||||
try {
|
wb.write(fileOut);
|
||||||
wb.write(fileOut);
|
}
|
||||||
} finally {
|
|
||||||
fileOut.close();
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void collapseExpandRowColumn() throws IOException {
|
private void collapseExpandRowColumn() throws IOException {
|
||||||
Workbook wb2 = new XSSFWorkbook();
|
try (Workbook wb2 = new XSSFWorkbook()) {
|
||||||
Sheet sheet2 = wb2.createSheet("new sheet");
|
Sheet sheet2 = wb2.createSheet("new sheet");
|
||||||
sheet2.groupRow( 5, 14 );
|
sheet2.groupRow(5, 14);
|
||||||
sheet2.groupRow( 7, 14 );
|
sheet2.groupRow(7, 14);
|
||||||
sheet2.groupRow( 16, 19 );
|
sheet2.groupRow(16, 19);
|
||||||
|
|
||||||
sheet2.groupColumn( (short)4, (short)7 );
|
sheet2.groupColumn((short) 4, (short) 7);
|
||||||
sheet2.groupColumn( (short)9, (short)12 );
|
sheet2.groupColumn((short) 9, (short) 12);
|
||||||
sheet2.groupColumn( (short)10, (short)11 );
|
sheet2.groupColumn((short) 10, (short) 11);
|
||||||
|
|
||||||
|
|
||||||
sheet2.setRowGroupCollapsed( 7, true );
|
sheet2.setRowGroupCollapsed(7, true);
|
||||||
//sheet1.setRowGroupCollapsed(7,false);
|
//sheet1.setRowGroupCollapsed(7,false);
|
||||||
|
|
||||||
sheet2.setColumnGroupCollapsed( (short)4, true );
|
sheet2.setColumnGroupCollapsed((short) 4, true);
|
||||||
sheet2.setColumnGroupCollapsed( (short)4, false );
|
sheet2.setColumnGroupCollapsed((short) 4, false);
|
||||||
|
|
||||||
OutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx");
|
try (OutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx")) {
|
||||||
try {
|
wb2.write(fileOut);
|
||||||
wb2.write(fileOut);
|
}
|
||||||
} finally {
|
|
||||||
fileOut.close();
|
|
||||||
wb2.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,49 +46,49 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class ScatterChart {
|
public class ScatterChart {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
Workbook wb = new XSSFWorkbook();
|
try (Workbook wb = new XSSFWorkbook()) {
|
||||||
Sheet sheet = wb.createSheet("Sheet 1");
|
Sheet sheet = wb.createSheet("Sheet 1");
|
||||||
final int NUM_OF_ROWS = 3;
|
final int NUM_OF_ROWS = 3;
|
||||||
final int NUM_OF_COLUMNS = 10;
|
final int NUM_OF_COLUMNS = 10;
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
Row row;
|
Row row;
|
||||||
Cell cell;
|
Cell cell;
|
||||||
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
|
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
|
||||||
row = sheet.createRow((short) rowIndex);
|
row = sheet.createRow((short) rowIndex);
|
||||||
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
|
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
|
||||||
cell = row.createCell((short) colIndex);
|
cell = row.createCell((short) colIndex);
|
||||||
cell.setCellValue(colIndex * (rowIndex + 1));
|
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,21 +26,20 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public abstract class SelectedSheet {
|
public abstract class SelectedSheet {
|
||||||
|
|
||||||
public static void main(String[]args) throws IOException {
|
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("row sheet");
|
||||||
wb.createSheet("another sheet");
|
wb.createSheet("another sheet");
|
||||||
Sheet sheet3 = wb.createSheet(" sheet 3 ");
|
Sheet sheet3 = wb.createSheet(" sheet 3 ");
|
||||||
sheet3.setSelected(true);
|
sheet3.setSelected(true);
|
||||||
wb.setActiveSheet(2);
|
wb.setActiveSheet(2);
|
||||||
|
|
||||||
// Create various cells and rows for spreadsheet.
|
// Create various cells and rows for spreadsheet.
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,32 +31,30 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class ShiftRows {
|
public class ShiftRows {
|
||||||
|
|
||||||
public static void main(String[]args) throws IOException {
|
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("Sheet1");
|
Sheet sheet = wb.createSheet("Sheet1");
|
||||||
|
|
||||||
Row row1 = sheet.createRow(1);
|
Row row1 = sheet.createRow(1);
|
||||||
row1.createCell(0).setCellValue(1);
|
row1.createCell(0).setCellValue(1);
|
||||||
|
|
||||||
Row row2 = sheet.createRow(4);
|
Row row2 = sheet.createRow(4);
|
||||||
row2.createCell(1).setCellValue(2);
|
row2.createCell(1).setCellValue(2);
|
||||||
|
|
||||||
Row row3 = sheet.createRow(5);
|
Row row3 = sheet.createRow(5);
|
||||||
row3.createCell(2).setCellValue(3);
|
row3.createCell(2).setCellValue(3);
|
||||||
|
|
||||||
Row row4 = sheet.createRow(6);
|
Row row4 = sheet.createRow(6);
|
||||||
row4.createCell(3).setCellValue(4);
|
row4.createCell(3).setCellValue(4);
|
||||||
|
|
||||||
Row row5 = sheet.createRow(9);
|
Row row5 = sheet.createRow(9);
|
||||||
row5.createCell(4).setCellValue(5);
|
row5.createCell(4).setCellValue(5);
|
||||||
|
|
||||||
// Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
|
// Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
|
||||||
sheet.shiftRows(5, 10, -4);
|
sheet.shiftRows(5, 10, -4);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,24 +29,24 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class SplitAndFreezePanes {
|
public class SplitAndFreezePanes {
|
||||||
public static void main(String[]args) throws IOException {
|
public static void main(String[]args) throws IOException {
|
||||||
Workbook wb = new XSSFWorkbook();
|
try (Workbook wb = new XSSFWorkbook()) {
|
||||||
Sheet sheet1 = wb.createSheet("new sheet");
|
Sheet sheet1 = wb.createSheet("new sheet");
|
||||||
Sheet sheet2 = wb.createSheet("second sheet");
|
Sheet sheet2 = wb.createSheet("second sheet");
|
||||||
Sheet sheet3 = wb.createSheet("third sheet");
|
Sheet sheet3 = wb.createSheet("third sheet");
|
||||||
Sheet sheet4 = wb.createSheet("fourth sheet");
|
Sheet sheet4 = wb.createSheet("fourth sheet");
|
||||||
|
|
||||||
// Freeze just one row
|
// Freeze just one row
|
||||||
sheet1.createFreezePane(0, 1, 0, 1);
|
sheet1.createFreezePane(0, 1, 0, 1);
|
||||||
// Freeze just one column
|
// Freeze just one column
|
||||||
sheet2.createFreezePane(1, 0, 1, 0);
|
sheet2.createFreezePane(1, 0, 1, 0);
|
||||||
// Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
|
// Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
|
||||||
sheet3.createFreezePane(2, 2);
|
sheet3.createFreezePane(2, 2);
|
||||||
// Create a split with the lower left side being the active quadrant
|
// Create a split with the lower left side being the active quadrant
|
||||||
sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
|
sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,37 +29,34 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class WorkbookProperties {
|
public class WorkbookProperties {
|
||||||
|
|
||||||
public static void main(String[]args) throws IOException {
|
public static void main(String[]args) throws IOException {
|
||||||
|
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
|
||||||
|
workbook.createSheet("Workbook Properties");
|
||||||
|
|
||||||
XSSFWorkbook workbook = new XSSFWorkbook();
|
POIXMLProperties props = workbook.getProperties();
|
||||||
workbook.createSheet("Workbook Properties");
|
|
||||||
|
|
||||||
POIXMLProperties props = workbook.getProperties();
|
/*
|
||||||
|
|
||||||
/**
|
|
||||||
* Extended properties are a predefined set of metadata properties
|
* Extended properties are a predefined set of metadata properties
|
||||||
* that are specifically applicable to Office Open XML documents.
|
* that are specifically applicable to Office Open XML documents.
|
||||||
* Extended properties consist of 24 simple properties and 3 complex properties stored in the
|
* Extended properties consist of 24 simple properties and 3 complex properties stored in the
|
||||||
* part targeted by the relationship of type
|
* part targeted by the relationship of type
|
||||||
*/
|
*/
|
||||||
POIXMLProperties.ExtendedProperties ext = props.getExtendedProperties();
|
POIXMLProperties.ExtendedProperties ext = props.getExtendedProperties();
|
||||||
ext.getUnderlyingProperties().setCompany("Apache Software Foundation");
|
ext.getUnderlyingProperties().setCompany("Apache Software Foundation");
|
||||||
ext.getUnderlyingProperties().setTemplate("XSSF");
|
ext.getUnderlyingProperties().setTemplate("XSSF");
|
||||||
|
|
||||||
/**
|
/*
|
||||||
* Custom properties enable users to define custom metadata properties.
|
* 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");
|
POIXMLProperties.CustomProperties cust = props.getCustomProperties();
|
||||||
workbook.write(out);
|
cust.addProperty("Author", "John Smith");
|
||||||
out.close();
|
cust.addProperty("Year", 2009);
|
||||||
workbook.close();
|
cust.addProperty("Price", 45.50);
|
||||||
|
cust.addProperty("Available", true);
|
||||||
|
|
||||||
|
try (FileOutputStream out = new FileOutputStream("workbook.xlsx")) {
|
||||||
|
workbook.write(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
|
@ -34,32 +34,32 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class WorkingWithBorders {
|
public class WorkingWithBorders {
|
||||||
public static void main(String[] args) throws IOException {
|
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("borders");
|
Sheet sheet = wb.createSheet("borders");
|
||||||
|
|
||||||
// Create a row and put some cells in it. Rows are 0 based.
|
// Create a row and put some cells in it. Rows are 0 based.
|
||||||
Row row = sheet.createRow((short) 1);
|
Row row = sheet.createRow((short) 1);
|
||||||
|
|
||||||
// Create a cell and put a value in it.
|
// Create a cell and put a value in it.
|
||||||
Cell cell = row.createCell((short) 1);
|
Cell cell = row.createCell((short) 1);
|
||||||
cell.setCellValue(4);
|
cell.setCellValue(4);
|
||||||
|
|
||||||
// Style the cell with borders all around.
|
// Style the cell with borders all around.
|
||||||
CellStyle style = wb.createCellStyle();
|
CellStyle style = wb.createCellStyle();
|
||||||
style.setBorderBottom(BorderStyle.THIN);
|
style.setBorderBottom(BorderStyle.THIN);
|
||||||
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
|
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
|
||||||
style.setBorderLeft(BorderStyle.THIN);
|
style.setBorderLeft(BorderStyle.THIN);
|
||||||
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
|
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
|
||||||
style.setBorderRight(BorderStyle.THIN);
|
style.setBorderRight(BorderStyle.THIN);
|
||||||
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
|
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
|
||||||
style.setBorderTop(BorderStyle.MEDIUM_DASHED);
|
style.setBorderTop(BorderStyle.MEDIUM_DASHED);
|
||||||
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
|
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
|
||||||
cell.setCellStyle(style);
|
cell.setCellStyle(style);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,75 +33,75 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
*/
|
*/
|
||||||
public class WorkingWithFonts {
|
public class WorkingWithFonts {
|
||||||
public static void main(String[] args) throws IOException {
|
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("Fonts");
|
Sheet sheet = wb.createSheet("Fonts");
|
||||||
|
|
||||||
Font font0 = wb.createFont();
|
Font font0 = wb.createFont();
|
||||||
font0.setColor(IndexedColors.BROWN.getIndex());
|
font0.setColor(IndexedColors.BROWN.getIndex());
|
||||||
CellStyle style0 = wb.createCellStyle();
|
CellStyle style0 = wb.createCellStyle();
|
||||||
style0.setFont(font0);
|
style0.setFont(font0);
|
||||||
|
|
||||||
Font font1 = wb.createFont();
|
Font font1 = wb.createFont();
|
||||||
font1.setFontHeightInPoints((short)14);
|
font1.setFontHeightInPoints((short) 14);
|
||||||
font1.setFontName("Courier New");
|
font1.setFontName("Courier New");
|
||||||
font1.setColor(IndexedColors.RED.getIndex());
|
font1.setColor(IndexedColors.RED.getIndex());
|
||||||
CellStyle style1 = wb.createCellStyle();
|
CellStyle style1 = wb.createCellStyle();
|
||||||
style1.setFont(font1);
|
style1.setFont(font1);
|
||||||
|
|
||||||
Font font2 = wb.createFont();
|
Font font2 = wb.createFont();
|
||||||
font2.setFontHeightInPoints((short)16);
|
font2.setFontHeightInPoints((short) 16);
|
||||||
font2.setFontName("Arial");
|
font2.setFontName("Arial");
|
||||||
font2.setColor(IndexedColors.GREEN.getIndex());
|
font2.setColor(IndexedColors.GREEN.getIndex());
|
||||||
CellStyle style2 = wb.createCellStyle();
|
CellStyle style2 = wb.createCellStyle();
|
||||||
style2.setFont(font2);
|
style2.setFont(font2);
|
||||||
|
|
||||||
Font font3 = wb.createFont();
|
Font font3 = wb.createFont();
|
||||||
font3.setFontHeightInPoints((short)18);
|
font3.setFontHeightInPoints((short) 18);
|
||||||
font3.setFontName("Times New Roman");
|
font3.setFontName("Times New Roman");
|
||||||
font3.setColor(IndexedColors.LAVENDER.getIndex());
|
font3.setColor(IndexedColors.LAVENDER.getIndex());
|
||||||
CellStyle style3 = wb.createCellStyle();
|
CellStyle style3 = wb.createCellStyle();
|
||||||
style3.setFont(font3);
|
style3.setFont(font3);
|
||||||
|
|
||||||
Font font4 = wb.createFont();
|
Font font4 = wb.createFont();
|
||||||
font4.setFontHeightInPoints((short)18);
|
font4.setFontHeightInPoints((short) 18);
|
||||||
font4.setFontName("Wingdings");
|
font4.setFontName("Wingdings");
|
||||||
font4.setColor(IndexedColors.GOLD.getIndex());
|
font4.setColor(IndexedColors.GOLD.getIndex());
|
||||||
CellStyle style4 = wb.createCellStyle();
|
CellStyle style4 = wb.createCellStyle();
|
||||||
style4.setFont(font4);
|
style4.setFont(font4);
|
||||||
|
|
||||||
Font font5 = wb.createFont();
|
Font font5 = wb.createFont();
|
||||||
font5.setFontName("Symbol");
|
font5.setFontName("Symbol");
|
||||||
CellStyle style5 = wb.createCellStyle();
|
CellStyle style5 = wb.createCellStyle();
|
||||||
style5.setFont(font5);
|
style5.setFont(font5);
|
||||||
|
|
||||||
Cell cell0 = sheet.createRow(0).createCell(1);
|
Cell cell0 = sheet.createRow(0).createCell(1);
|
||||||
cell0.setCellValue("Default");
|
cell0.setCellValue("Default");
|
||||||
cell0.setCellStyle(style0);
|
cell0.setCellStyle(style0);
|
||||||
|
|
||||||
Cell cell1 = sheet.createRow(1).createCell(1);
|
Cell cell1 = sheet.createRow(1).createCell(1);
|
||||||
cell1.setCellValue("Courier");
|
cell1.setCellValue("Courier");
|
||||||
cell1.setCellStyle(style1);
|
cell1.setCellStyle(style1);
|
||||||
|
|
||||||
Cell cell2 = sheet.createRow(2).createCell(1);
|
Cell cell2 = sheet.createRow(2).createCell(1);
|
||||||
cell2.setCellValue("Arial");
|
cell2.setCellValue("Arial");
|
||||||
cell2.setCellStyle(style2);
|
cell2.setCellStyle(style2);
|
||||||
|
|
||||||
Cell cell3 = sheet.createRow(3).createCell(1);
|
Cell cell3 = sheet.createRow(3).createCell(1);
|
||||||
cell3.setCellValue("Times New Roman");
|
cell3.setCellValue("Times New Roman");
|
||||||
cell3.setCellStyle(style3);
|
cell3.setCellStyle(style3);
|
||||||
|
|
||||||
Cell cell4 = sheet.createRow(4).createCell(1);
|
Cell cell4 = sheet.createRow(4).createCell(1);
|
||||||
cell4.setCellValue("Wingdings");
|
cell4.setCellValue("Wingdings");
|
||||||
cell4.setCellStyle(style4);
|
cell4.setCellStyle(style4);
|
||||||
|
|
||||||
Cell cell5 = sheet.createRow(5).createCell(1);
|
Cell cell5 = sheet.createRow(5).createCell(1);
|
||||||
cell5.setCellValue("Symbol");
|
cell5.setCellValue("Symbol");
|
||||||
cell5.setCellStyle(style5);
|
cell5.setCellStyle(style5);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
wb.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,9 +30,9 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
public class WorkingWithPageSetup {
|
public class WorkingWithPageSetup {
|
||||||
|
|
||||||
public static void main(String[]args) throws Exception {
|
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.
|
* 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:
|
* 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.
|
* 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.
|
* To stop the columns from repeating pass in -1 as the start and end rows.
|
||||||
*/
|
*/
|
||||||
Sheet sheet1 = wb.createSheet("new sheet");
|
Sheet sheet1 = wb.createSheet("new sheet");
|
||||||
Sheet sheet2 = wb.createSheet("second sheet");
|
Sheet sheet2 = wb.createSheet("second sheet");
|
||||||
|
|
||||||
// Set the columns to repeat from column 0 to 2 on the first sheet
|
// Set the columns to repeat from column 0 to 2 on the first sheet
|
||||||
Row row1 = sheet1.createRow(0);
|
Row row1 = sheet1.createRow(0);
|
||||||
row1.createCell(0).setCellValue(1);
|
row1.createCell(0).setCellValue(1);
|
||||||
row1.createCell(1).setCellValue(2);
|
row1.createCell(1).setCellValue(2);
|
||||||
row1.createCell(2).setCellValue(3);
|
row1.createCell(2).setCellValue(3);
|
||||||
Row row2 = sheet1.createRow(1);
|
Row row2 = sheet1.createRow(1);
|
||||||
row2.createCell(1).setCellValue(4);
|
row2.createCell(1).setCellValue(4);
|
||||||
row2.createCell(2).setCellValue(5);
|
row2.createCell(2).setCellValue(5);
|
||||||
|
|
||||||
|
|
||||||
Row row3 = sheet2.createRow(1);
|
Row row3 = sheet2.createRow(1);
|
||||||
row3.createCell(0).setCellValue(2.1);
|
row3.createCell(0).setCellValue(2.1);
|
||||||
row3.createCell(4).setCellValue(2.2);
|
row3.createCell(4).setCellValue(2.2);
|
||||||
row3.createCell(5).setCellValue(2.3);
|
row3.createCell(5).setCellValue(2.3);
|
||||||
Row row4 = sheet2.createRow(2);
|
Row row4 = sheet2.createRow(2);
|
||||||
row4.createCell(4).setCellValue(2.4);
|
row4.createCell(4).setCellValue(2.4);
|
||||||
row4.createCell(5).setCellValue(2.5);
|
row4.createCell(5).setCellValue(2.5);
|
||||||
|
|
||||||
// Set the columns to repeat from column 0 to 2 on the first sheet
|
// Set the columns to repeat from column 0 to 2 on the first sheet
|
||||||
sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
|
sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
|
||||||
// Set the the repeating rows and columns on the second sheet.
|
// Set the the repeating rows and columns on the second sheet.
|
||||||
CellRangeAddress cra = CellRangeAddress.valueOf("E2:F3");
|
CellRangeAddress cra = CellRangeAddress.valueOf("E2:F3");
|
||||||
sheet2.setRepeatingColumns(cra);
|
sheet2.setRepeatingColumns(cra);
|
||||||
sheet2.setRepeatingRows(cra);
|
sheet2.setRepeatingRows(cra);
|
||||||
|
|
||||||
//set the print area for the first sheet
|
//set the print area for the first sheet
|
||||||
wb.setPrintArea(0, 1, 2, 0, 3);
|
wb.setPrintArea(0, 1, 2, 0, 3);
|
||||||
|
|
||||||
|
|
||||||
FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx");
|
try (FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx")) {
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
fileOut.close();
|
}
|
||||||
|
}
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -39,45 +39,38 @@ public class WorkingWithPictures {
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
|
|
||||||
//create a new workbook
|
//create a new workbook
|
||||||
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
|
try (Workbook wb = new XSSFWorkbook()) {
|
||||||
try {
|
|
||||||
CreationHelper helper = wb.getCreationHelper();
|
CreationHelper helper = wb.getCreationHelper();
|
||||||
|
|
||||||
//add a picture in this workbook.
|
//add a picture in this workbook.
|
||||||
InputStream is = new FileInputStream(args[0]);
|
InputStream is = new FileInputStream(args[0]);
|
||||||
byte[] bytes = IOUtils.toByteArray(is);
|
byte[] bytes = IOUtils.toByteArray(is);
|
||||||
is.close();
|
is.close();
|
||||||
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
|
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
|
||||||
|
|
||||||
//create sheet
|
//create sheet
|
||||||
Sheet sheet = wb.createSheet();
|
Sheet sheet = wb.createSheet();
|
||||||
|
|
||||||
//create drawing
|
//create drawing
|
||||||
Drawing<?> drawing = sheet.createDrawingPatriarch();
|
Drawing<?> drawing = sheet.createDrawingPatriarch();
|
||||||
|
|
||||||
//add a picture shape
|
//add a picture shape
|
||||||
ClientAnchor anchor = helper.createClientAnchor();
|
ClientAnchor anchor = helper.createClientAnchor();
|
||||||
anchor.setCol1(1);
|
anchor.setCol1(1);
|
||||||
anchor.setRow1(1);
|
anchor.setRow1(1);
|
||||||
Picture pict = drawing.createPicture(anchor, pictureIdx);
|
Picture pict = drawing.createPicture(anchor, pictureIdx);
|
||||||
|
|
||||||
//auto-size picture
|
//auto-size picture
|
||||||
pict.resize(2);
|
pict.resize(2);
|
||||||
|
|
||||||
//save workbook
|
//save workbook
|
||||||
String file = "picture.xls";
|
String file = "picture.xls";
|
||||||
if(wb instanceof XSSFWorkbook)
|
if (wb instanceof XSSFWorkbook) {
|
||||||
{
|
|
||||||
file += "x"; // NOSONAR
|
file += "x"; // NOSONAR
|
||||||
}
|
}
|
||||||
OutputStream fileOut = new FileOutputStream(file);
|
try (OutputStream fileOut = new FileOutputStream(file)) {
|
||||||
try {
|
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
} finally {
|
|
||||||
fileOut.close();
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,41 +28,34 @@ import java.io.OutputStream;
|
||||||
public class WorkingWithRichText {
|
public class WorkingWithRichText {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
|
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||||
XSSFWorkbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
|
|
||||||
try {
|
|
||||||
XSSFSheet sheet = wb.createSheet();
|
XSSFSheet sheet = wb.createSheet();
|
||||||
XSSFRow row = sheet.createRow(2);
|
XSSFRow row = sheet.createRow(2);
|
||||||
|
|
||||||
XSSFCell cell = row.createCell(1);
|
XSSFCell cell = row.createCell(1);
|
||||||
XSSFRichTextString rt = new XSSFRichTextString("The quick brown fox");
|
XSSFRichTextString rt = new XSSFRichTextString("The quick brown fox");
|
||||||
|
|
||||||
XSSFFont font1 = wb.createFont();
|
XSSFFont font1 = wb.createFont();
|
||||||
font1.setBold(true);
|
font1.setBold(true);
|
||||||
font1.setColor(new XSSFColor(new java.awt.Color(255, 0, 0)));
|
font1.setColor(new XSSFColor(new java.awt.Color(255, 0, 0)));
|
||||||
rt.applyFont(0, 10, font1);
|
rt.applyFont(0, 10, font1);
|
||||||
|
|
||||||
XSSFFont font2 = wb.createFont();
|
XSSFFont font2 = wb.createFont();
|
||||||
font2.setItalic(true);
|
font2.setItalic(true);
|
||||||
font2.setUnderline(XSSFFont.U_DOUBLE);
|
font2.setUnderline(XSSFFont.U_DOUBLE);
|
||||||
font2.setColor(new XSSFColor(new java.awt.Color(0, 255, 0)));
|
font2.setColor(new XSSFColor(new java.awt.Color(0, 255, 0)));
|
||||||
rt.applyFont(10, 19, font2);
|
rt.applyFont(10, 19, font2);
|
||||||
|
|
||||||
XSSFFont font3 = wb.createFont();
|
XSSFFont font3 = wb.createFont();
|
||||||
font3.setColor(new XSSFColor(new java.awt.Color(0, 0, 255)));
|
font3.setColor(new XSSFColor(new java.awt.Color(0, 0, 255)));
|
||||||
rt.append(" Jumped over the lazy dog", font3);
|
rt.append(" Jumped over the lazy dog", font3);
|
||||||
|
|
||||||
cell.setCellValue(rt);
|
cell.setCellValue(rt);
|
||||||
|
|
||||||
// Write the output to a file
|
// Write the output to a file
|
||||||
OutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx");
|
try (OutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx")) {
|
||||||
try {
|
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
} finally {
|
|
||||||
fileOut.close();
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
wb.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,26 +31,26 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||||
public class BetterHeaderFooterExample {
|
public class BetterHeaderFooterExample {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
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();
|
XWPFRun r = p.createRun();
|
||||||
r.setText("Some Text");
|
r.setText("Some Text");
|
||||||
r.setBold(true);
|
r.setBold(true);
|
||||||
r = p.createRun();
|
r = p.createRun();
|
||||||
r.setText("Goodbye");
|
r.setText("Goodbye");
|
||||||
|
|
||||||
// create header/footer functions insert an empty paragraph
|
// create header/footer functions insert an empty paragraph
|
||||||
XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT);
|
XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT);
|
||||||
head.createParagraph().createRun().setText("header");
|
head.createParagraph().createRun().setText("header");
|
||||||
|
|
||||||
XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT);
|
XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT);
|
||||||
foot.createParagraph().createRun().setText("footer");
|
foot.createParagraph().createRun().setText("footer");
|
||||||
|
|
||||||
OutputStream os = new FileOutputStream(new File("header2.docx"));
|
try (OutputStream os = new FileOutputStream(new File("header2.docx"))) {
|
||||||
doc.write(os);
|
doc.write(os);
|
||||||
os.close();
|
}
|
||||||
doc.close();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -41,65 +41,65 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblLayoutType;
|
||||||
public class HeaderFooterTable {
|
public class HeaderFooterTable {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
XWPFDocument doc = new XWPFDocument();
|
try (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);
|
|
||||||
|
|
||||||
// Set table width to 6.5 inches in 1440ths of a point
|
// Create a header with a 1 row, 3 column table
|
||||||
tbl.setWidth((int)(6.5 * 1440));
|
// changes made for issue 57366 allow a new header or footer
|
||||||
// Can not yet set table or cell width properly, tables default to
|
// to be created empty. This is a change. You will have to add
|
||||||
// autofit layout, and this requires fixed layout
|
// either a paragraph or a table to the header or footer for
|
||||||
CTTbl ctTbl = tbl.getCTTbl();
|
// the document to be considered valid.
|
||||||
CTTblPr ctTblPr = ctTbl.addNewTblPr();
|
XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
|
||||||
CTTblLayoutType layoutType = ctTblPr.addNewTblLayout();
|
XWPFTable tbl = hdr.createTable(1, 3);
|
||||||
layoutType.setType(STTblLayoutType.FIXED);
|
|
||||||
|
|
||||||
// Now set up a grid for the table, cells will fit into the grid
|
// Set the padding around text in the cells to 1/10th of an inch
|
||||||
// Each cell width is 3120 in 1440ths of an inch, or 1/3rd of 6.5"
|
int pad = (int) (.1 * 1440);
|
||||||
BigInteger w = new BigInteger("3120");
|
tbl.setCellMargins(pad, pad, pad, pad);
|
||||||
CTTblGrid grid = ctTbl.addNewTblGrid();
|
|
||||||
for (int i = 0; i < 3; i++) {
|
// Set table width to 6.5 inches in 1440ths of a point
|
||||||
CTTblGridCol gridCol = grid.addNewGridCol();
|
tbl.setWidth((int) (6.5 * 1440));
|
||||||
gridCol.setW(w);
|
// 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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -36,95 +36,95 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||||
public class SimpleDocument {
|
public class SimpleDocument {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
XWPFDocument doc = new XWPFDocument();
|
try (XWPFDocument doc = new XWPFDocument()) {
|
||||||
|
|
||||||
XWPFParagraph p1 = doc.createParagraph();
|
XWPFParagraph p1 = doc.createParagraph();
|
||||||
p1.setAlignment(ParagraphAlignment.CENTER);
|
p1.setAlignment(ParagraphAlignment.CENTER);
|
||||||
p1.setBorderBottom(Borders.DOUBLE);
|
p1.setBorderBottom(Borders.DOUBLE);
|
||||||
p1.setBorderTop(Borders.DOUBLE);
|
p1.setBorderTop(Borders.DOUBLE);
|
||||||
|
|
||||||
p1.setBorderRight(Borders.DOUBLE);
|
p1.setBorderRight(Borders.DOUBLE);
|
||||||
p1.setBorderLeft(Borders.DOUBLE);
|
p1.setBorderLeft(Borders.DOUBLE);
|
||||||
p1.setBorderBetween(Borders.SINGLE);
|
p1.setBorderBetween(Borders.SINGLE);
|
||||||
|
|
||||||
p1.setVerticalAlignment(TextAlignment.TOP);
|
p1.setVerticalAlignment(TextAlignment.TOP);
|
||||||
|
|
||||||
XWPFRun r1 = p1.createRun();
|
XWPFRun r1 = p1.createRun();
|
||||||
r1.setBold(true);
|
r1.setBold(true);
|
||||||
r1.setText("The quick brown fox");
|
r1.setText("The quick brown fox");
|
||||||
r1.setBold(true);
|
r1.setBold(true);
|
||||||
r1.setFontFamily("Courier");
|
r1.setFontFamily("Courier");
|
||||||
r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
|
r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
|
||||||
r1.setTextPosition(100);
|
r1.setTextPosition(100);
|
||||||
|
|
||||||
XWPFParagraph p2 = doc.createParagraph();
|
XWPFParagraph p2 = doc.createParagraph();
|
||||||
p2.setAlignment(ParagraphAlignment.RIGHT);
|
p2.setAlignment(ParagraphAlignment.RIGHT);
|
||||||
|
|
||||||
//BORDERS
|
//BORDERS
|
||||||
p2.setBorderBottom(Borders.DOUBLE);
|
p2.setBorderBottom(Borders.DOUBLE);
|
||||||
p2.setBorderTop(Borders.DOUBLE);
|
p2.setBorderTop(Borders.DOUBLE);
|
||||||
p2.setBorderRight(Borders.DOUBLE);
|
p2.setBorderRight(Borders.DOUBLE);
|
||||||
p2.setBorderLeft(Borders.DOUBLE);
|
p2.setBorderLeft(Borders.DOUBLE);
|
||||||
p2.setBorderBetween(Borders.SINGLE);
|
p2.setBorderBetween(Borders.SINGLE);
|
||||||
|
|
||||||
XWPFRun r2 = p2.createRun();
|
XWPFRun r2 = p2.createRun();
|
||||||
r2.setText("jumped over the lazy dog");
|
r2.setText("jumped over the lazy dog");
|
||||||
r2.setStrikeThrough(true);
|
r2.setStrikeThrough(true);
|
||||||
r2.setFontSize(20);
|
r2.setFontSize(20);
|
||||||
|
|
||||||
XWPFRun r3 = p2.createRun();
|
XWPFRun r3 = p2.createRun();
|
||||||
r3.setText("and went away");
|
r3.setText("and went away");
|
||||||
r3.setStrikeThrough(true);
|
r3.setStrikeThrough(true);
|
||||||
r3.setFontSize(20);
|
r3.setFontSize(20);
|
||||||
r3.setSubscript(VerticalAlign.SUPERSCRIPT);
|
r3.setSubscript(VerticalAlign.SUPERSCRIPT);
|
||||||
|
|
||||||
|
|
||||||
XWPFParagraph p3 = doc.createParagraph();
|
XWPFParagraph p3 = doc.createParagraph();
|
||||||
p3.setWordWrapped(true);
|
p3.setWordWrapped(true);
|
||||||
p3.setPageBreak(true);
|
p3.setPageBreak(true);
|
||||||
|
|
||||||
//p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
|
|
||||||
p3.setAlignment(ParagraphAlignment.BOTH);
|
|
||||||
p3.setSpacingBetween(15, LineSpacingRule.EXACT);
|
|
||||||
|
|
||||||
p3.setIndentationFirstLine(600);
|
//p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
|
||||||
|
p3.setAlignment(ParagraphAlignment.BOTH);
|
||||||
|
p3.setSpacingBetween(15, LineSpacingRule.EXACT);
|
||||||
|
|
||||||
XWPFRun r4 = p3.createRun();
|
p3.setIndentationFirstLine(600);
|
||||||
r4.setTextPosition(20);
|
|
||||||
r4.setText("To be, or not to be: that is the question: "
|
|
||||||
+ "Whether 'tis nobler in the mind to suffer "
|
XWPFRun r4 = p3.createRun();
|
||||||
+ "The slings and arrows of outrageous fortune, "
|
r4.setTextPosition(20);
|
||||||
+ "Or to take arms against a sea of troubles, "
|
r4.setText("To be, or not to be: that is the question: "
|
||||||
+ "And by opposing end them? To die: to sleep; ");
|
+ "Whether 'tis nobler in the mind to suffer "
|
||||||
r4.addBreak(BreakType.PAGE);
|
+ "The slings and arrows of outrageous fortune, "
|
||||||
r4.setText("No more; and by a sleep to say we end "
|
+ "Or to take arms against a sea of troubles, "
|
||||||
+ "The heart-ache and the thousand natural shocks "
|
+ "And by opposing end them? To die: to sleep; ");
|
||||||
+ "That flesh is heir to, 'tis a consummation "
|
r4.addBreak(BreakType.PAGE);
|
||||||
+ "Devoutly to be wish'd. To die, to sleep; "
|
r4.setText("No more; and by a sleep to say we end "
|
||||||
+ "To sleep: perchance to dream: ay, there's the rub; "
|
+ "The heart-ache and the thousand natural shocks "
|
||||||
+ ".......");
|
+ "That flesh is heir to, 'tis a consummation "
|
||||||
r4.setItalic(true);
|
+ "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:
|
//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();
|
XWPFRun r5 = p3.createRun();
|
||||||
r5.setTextPosition(-10);
|
r5.setTextPosition(-10);
|
||||||
r5.setText("For in that sleep of death what dreams may come");
|
r5.setText("For in that sleep of death what dreams may come");
|
||||||
r5.addCarriageReturn();
|
r5.addCarriageReturn();
|
||||||
r5.setText("When we have shuffled off this mortal coil,"
|
r5.setText("When we have shuffled off this mortal coil,"
|
||||||
+ "Must give us pause: there's the respect"
|
+ "Must give us pause: there's the respect"
|
||||||
+ "That makes calamity of so long life;");
|
+ "That makes calamity of so long life;");
|
||||||
r5.addBreak();
|
r5.addBreak();
|
||||||
r5.setText("For who would bear the whips and scorns of time,"
|
r5.setText("For who would bear the whips and scorns of time,"
|
||||||
+ "The oppressor's wrong, the proud man's contumely,");
|
+ "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" + ".......");
|
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("simple.docx");
|
r5.addBreak(BreakClear.ALL);
|
||||||
doc.write(out);
|
r5.setText("The pangs of despised love, the law's delay,"
|
||||||
out.close();
|
+ "The insolence of office and the spurns" + ".......");
|
||||||
doc.close();
|
|
||||||
|
try (FileOutputStream out = new FileOutputStream("simple.docx")) {
|
||||||
|
doc.write(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,42 +35,36 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
|
||||||
*/
|
*/
|
||||||
public class SimpleDocumentWithHeader {
|
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) {
|
XWPFParagraph p = doc.createParagraph();
|
||||||
XWPFDocument doc = new XWPFDocument();
|
|
||||||
|
|
||||||
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();
|
CTP ctP = CTP.Factory.newInstance();
|
||||||
r.setText("Some Text");
|
CTText t = ctP.addNewR().addNewT();
|
||||||
r.setBold(true);
|
t.setStringValue("header");
|
||||||
r = p.createRun();
|
XWPFParagraph[] pars = new XWPFParagraph[1];
|
||||||
r.setText("Goodbye");
|
p = new XWPFParagraph(ctP, doc);
|
||||||
|
pars[0] = p;
|
||||||
|
|
||||||
CTP ctP = CTP.Factory.newInstance();
|
XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
|
||||||
CTText t = ctP.addNewR().addNewT();
|
hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
|
||||||
t.setStringValue("header");
|
|
||||||
pars = new XWPFParagraph[1];
|
|
||||||
p = new XWPFParagraph(ctP, doc);
|
|
||||||
pars[0] = p;
|
|
||||||
|
|
||||||
XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
|
ctP = CTP.Factory.newInstance();
|
||||||
hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
|
t = ctP.addNewR().addNewT();
|
||||||
|
t.setStringValue("My Footer");
|
||||||
ctP = CTP.Factory.newInstance();
|
pars[0] = new XWPFParagraph(ctP, doc);
|
||||||
t = ctP.addNewR().addNewT();
|
hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
|
||||||
t.setStringValue("My Footer");
|
|
||||||
pars[0] = new XWPFParagraph(ctP, doc);
|
try (OutputStream os = new FileOutputStream(new File("header.docx"))) {
|
||||||
hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
|
doc.write(os);
|
||||||
|
}
|
||||||
try {
|
|
||||||
OutputStream os = new FileOutputStream(new File("header.docx"));
|
|
||||||
doc.write(os);
|
|
||||||
} catch (IOException e) {
|
|
||||||
// TODO Auto-generated catch block
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -35,41 +35,41 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||||
public class SimpleImages {
|
public class SimpleImages {
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException, InvalidFormatException {
|
public static void main(String[] args) throws IOException, InvalidFormatException {
|
||||||
XWPFDocument doc = new XWPFDocument();
|
try (XWPFDocument doc = new XWPFDocument()) {
|
||||||
XWPFParagraph p = doc.createParagraph();
|
XWPFParagraph p = doc.createParagraph();
|
||||||
|
|
||||||
XWPFRun r = p.createRun();
|
XWPFRun r = p.createRun();
|
||||||
|
|
||||||
for(String imgFile : args) {
|
for (String imgFile : args) {
|
||||||
int format;
|
int format;
|
||||||
|
|
||||||
if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
|
if (imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
|
||||||
else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
|
else if (imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
|
||||||
else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
|
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(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
|
||||||
else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
|
else if (imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
|
||||||
else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
|
else if (imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
|
||||||
else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
|
else if (imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
|
||||||
else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
|
else if (imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
|
||||||
else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
|
else if (imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
|
||||||
else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
|
else if (imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
|
||||||
else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
|
else if (imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
|
||||||
else {
|
else {
|
||||||
System.err.println("Unsupported picture: " + imgFile +
|
System.err.println("Unsupported picture: " + imgFile +
|
||||||
". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
|
". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
|
||||||
continue;
|
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);
|
try (FileOutputStream out = new FileOutputStream("images.docx")) {
|
||||||
r.addBreak();
|
doc.write(out);
|
||||||
r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
|
}
|
||||||
r.addBreak(BreakType.PAGE);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
FileOutputStream out = new FileOutputStream("images.docx");
|
|
||||||
doc.write(out);
|
|
||||||
out.close();
|
|
||||||
doc.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -69,9 +69,7 @@ public class SimpleTable {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void createSimpleTable() throws Exception {
|
public static void createSimpleTable() throws Exception {
|
||||||
XWPFDocument doc = new XWPFDocument();
|
try (XWPFDocument doc = new XWPFDocument()) {
|
||||||
|
|
||||||
try {
|
|
||||||
XWPFTable table = doc.createTable(3, 3);
|
XWPFTable table = doc.createTable(3, 3);
|
||||||
|
|
||||||
table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");
|
table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");
|
||||||
|
@ -93,14 +91,9 @@ public class SimpleTable {
|
||||||
|
|
||||||
table.getRow(2).getCell(2).setText("only text");
|
table.getRow(2).getCell(2).setText("only text");
|
||||||
|
|
||||||
OutputStream out = new FileOutputStream("simpleTable.docx");
|
try (OutputStream out = new FileOutputStream("simpleTable.docx")) {
|
||||||
try {
|
|
||||||
doc.write(out);
|
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
|
* 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
|
* for me. Given the scarcity of XWPF examples, I thought this may prove
|
||||||
* instructive and give you ideas for your own solutions.
|
* instructive and give you ideas for your own solutions.
|
||||||
|
|
||||||
* @throws Exception
|
|
||||||
*/
|
*/
|
||||||
public static void createStyledTable() throws Exception {
|
public static void createStyledTable() throws Exception {
|
||||||
// Create a new document from scratch
|
// Create a new document from scratch
|
||||||
XWPFDocument doc = new XWPFDocument();
|
|
||||||
|
|
||||||
try {
|
try (XWPFDocument doc = new XWPFDocument()) {
|
||||||
// -- OR --
|
// -- OR --
|
||||||
// open an existing empty document with styles already defined
|
// open an existing empty document with styles already defined
|
||||||
//XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
|
//XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
|
||||||
|
@ -201,14 +191,9 @@ public class SimpleTable {
|
||||||
} // for row
|
} // for row
|
||||||
|
|
||||||
// write the file
|
// write the file
|
||||||
OutputStream out = new FileOutputStream("styledTable.docx");
|
try (OutputStream out = new FileOutputStream("styledTable.docx")) {
|
||||||
try {
|
|
||||||
doc.write(out);
|
doc.write(out);
|
||||||
} finally {
|
|
||||||
out.close();
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
doc.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue