用Java生成Word主流的方案有以下几种:
- 直接生成Word,需要自己一点点的生成标题、段落、表格等,缺点是比较手动原始并且工作量大,优点是快捷可控性强。主流的方案如:Java2Word(https://github.com/leonardoanalista/java2wordhttps://github.com/leonardoanalista/java2word)
- 通过html或者模板生成Word,主流的方案有开源的Apache POI(http://poi.apache.org/),商业的Aspose.Word for Java(https://www.componentsource.com/zh-hans/product/aspose-words-java/prices) 官网售价2w。
本文只讨论方案1,即基于开源的java2word组件开发。
运行Demo步骤:
- 克隆工程(https://github.com/leonardoanalista/java2word)
- 进入java2word目录,运行mvn clean install将工程安装到本地
- 获取本地生成的java2word-3.3.jar,并上传至maven私服
- 本地工程添加maven依赖,并编写demo代码:
<dependency>
<groupId>com.java2word</groupId>
<artifactId>java2word</artifactId>
<version>3.3</version>
</dependency>
@Test
public void testJava2wordAllInOne() {
IDocument myDoc = new Document2004();
// myDoc.setPageOrientationLandscape();
// default is Portrait be can be changed.
myDoc.encoding(Document2004.Encoding.UTF_8); //or ISO8859-1. Default is UTF-8
myDoc.addEle(BreakLine.times(1).create()); // this is one breakline
// Headings
myDoc.addEle(Heading1.with("===== Java2word ======").create());
myDoc.addEle(Heading2.with("===== Headings ======").create());
myDoc.addEle(Paragraph
.with("This doc has been generated by the unit test testJava2wordAllInOne() in the class DocumentTest2004Test.java.")
.create());
myDoc.addEle(BreakLine.times(1).create());
myDoc.addEle(Paragraph
.with("I will try to use a little bit of everything in the API Java2word. "
+ "I realised that is very dificult to keep the doucmentation updated "
+ "so this is where I will demostrate how to do some cool things with Java2word!")
.create());
myDoc.addEle(Heading1.with("Heading01 without styling").create());
myDoc.addEle(Heading2.with("Heading02 with style Center").withStyle()
.align(HeadingStyle.Align.CENTER).italic().create());
myDoc.addEle(Heading3.with("Heading03 aligned Right").withStyle().bold()
.align(HeadingStyle.Align.RIGHT).create());
// Paragraph and ParagrapPiece
myDoc.addEle(Heading2.with("===== Paragraph and ParagrapPiece ======")
.create());
myDoc.addEle(Paragraph.with("I am a very simple paragraph.").create());
myDoc.addEle(BreakLine.times(1).create());
ParagraphPiece myParPiece01 = ParagraphPiece
.with("If you use the class 'Paragraph', you will have limited style. Maybe only paragraph Aligment or BgColor.");
ParagraphPiece myParPiece02 = ParagraphPiece
.with("In order to use more advanced style, you have to use ParagraphPiece");
ParagraphPiece myParPiece03 = ParagraphPiece
.with("One example of this is when you want to make ONLY one word BOLD or ITALIC. the way to to this is create many pieces, format them separetely and put all together in a Paragraph object. Example:");
myDoc.addEle(Paragraph.withPieces(myParPiece01, myParPiece02,
myParPiece03).create());
ParagraphPiece myParPieceJava = ParagraphPiece.with("I like Java and ")
.withStyle().font(Font.COURIER).create();
ParagraphPiece myParPieceRuby = ParagraphPiece.with("Ruby!!! ")
.withStyle().bold().italic().create();
ParagraphPiece myParPieceAgile = ParagraphPiece
.with("I actually like Java, Ruby Agile, BDD, Cucumber... ")
.withStyle().textColor("008000").create();
myDoc.addEle(Paragraph.withPieces(myParPieceJava, myParPieceRuby,
myParPieceAgile).create());
myDoc.addEle(BreakLine.times(2).create());
myDoc.addEle(Paragraph.withPieces(
ParagraphPiece.with("This is a manual 'bold' and 'italic'")
.withStyle().font(Font.COURIER).bold().italic()
.create()).create());
myDoc.addEle(Paragraph
.withPieces(
ParagraphPiece
.with("This is the SAME as the above line but with 'Smart' Bold/Italic ")
.withStyle().font(Font.COURIER_BOLD_ITALIC)
.create()).create());
myDoc.addEle(BreakLine.times(1).create());
// font size
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("No size")
.create(), ParagraphPiece.with(" but I am size 24.").withStyle()
.fontSize("24").create()));
//ParagraphPiece and other format/styles
myDoc.addEle(BreakLine.times(1).create());
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("New ParagraphPiece styles have been implemented. Here they are:").withStyle().fontSize("14").create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("Subscript").withStyle().subscript().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("Superscript").withStyle().superscript().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("Strike").withStyle().strike().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("Caps").withStyle().caps().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("SmallCaps").withStyle().smallCaps().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("DoubleStrike").withStyle().doubleStrike().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("Emboss").withStyle().emboss().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("Imprint").withStyle().imprint().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("Outline").withStyle().outline().create()));
myDoc.addEle(Paragraph.withPieces(ParagraphPiece.with("The Style is: ").create(), ParagraphPiece.with("Shadow").withStyle().shadow().create()));
myDoc.addEle(BreakLine.times(2).create());
myDoc.addEle(Paragraph.with("Remember to scape special characters like empsersand &").create());
// Document Header and Footer
myDoc.addEle(BreakLine.times(2).create());
myDoc.addEle(Heading2.with("===== Document Header and Footer ======")
.create());
myDoc.addEle(Paragraph
.with("By default everything is added to the Body when you do 'myDoc.addEle(...)'."
+ " But you can add elements to the Header and/or Footer. Other cool thing is show page number or not.")
.create());
myDoc.addEle(BreakLine.times(2).create());
myDoc.addEle(Paragraph
.with("Page number is displayed by default but you can disable: 'myDoc.getFooter().showPageNumber(false)' ")
.create());
myDoc.addEle(BreakLine.times(2).create());
myDoc.addEle(Paragraph
.with("you can also hide Header and Footer in the first Page. This is useful for when you have a cover page.: 'myDoc.getHeader().setHideHeaderAndFooterFirstPage(true)' ")
.create());
myDoc.getHeader().addEle(
Paragraph.withPieces(
ParagraphPiece.with("I am in the"),
ParagraphPiece.with(" Header ").withStyle().bold()
.create(), ParagraphPiece.with("of all pages"))
.create());
myDoc.getFooter().addEle(
Paragraph.with("I am in the Footer of all pages").create());
// Images
myDoc.addEle(BreakLine.times(1).create());
myDoc.addEle(Heading2.with("===== Images ======").create());
myDoc.addEle(Paragraph
.with("Images can be created from diferent locations. It can be from your local machine, from web URL or classpath.")
.create());
myDoc.addEle(Paragraph.with(
"This one is coming from WEB, google web site: ").create());
myDoc.addEle(Image
.from_WEB_URL("https://test-cgsaas.oss-cn-shenzhen.aliyuncs.com/zt/8oc44k4ttv5.png"));
myDoc.addEle(BreakLine.times(2).create());
myDoc.addEle(Paragraph.with("You can change the image dimensions:.")
.create());
myDoc.addEle(Image
.from_WEB_URL("https://test-cgsaas.oss-cn-shenzhen.aliyuncs.com/zt/8oc44k4ttv5.png")
.setHeight("40").setWidth("80").create());
myDoc.addEle(BreakLine.times(2).create());
myDoc.addEle(Paragraph
.with("You can always be creative and mix up images inside other IElements. Eg.: Paragraphs, Tables, etc.")
.create());
// myDoc.addEle(Paragraph
// .with("This document inside the paragraph, coming from '/Users/xiayang/Pictures/Jeff.jpeg': "
// + Image.from_FULL_LOCAL_PATHL(
// Utils.getAppRoot()
// + "/images/Jeff.jpeg")
// .getContent()));
myDoc.addEle(BreakLine.times(1).create());
myDoc.addEle(PageBreak.create());
// Table
myDoc.addEle(Heading2.with("===== Table ======").create());
myDoc.addEle(Paragraph
.with("Table of The Best Soccer Players Ever and Their Number of Gols:")
.create());
myDoc.addEle(BreakLine.times(1).create());
Table tbl = new Table();
tbl.addTableEle(TableEle.TH, "Name", "Number of gols", "Country");
tbl.setRepeatTableHeaderOnEveryPage();
tbl.addTableEle(TableEle.TD, "* Arthur Friedenreich", "1329", "Brazil");
tbl.addTableEle(TableEle.TD, "Pele", "1281", "Brazil");
tbl.addTableEle(TableEle.TD, "Romario", "1002", "Brazil");
tbl.addTableEle(TableEle.TD, "Tulio Maravilha", "956", "Brazil");
tbl.addTableEle(TableEle.TD, "** Zico", "815", "Brazil");
tbl.addTableEle(TableEle.TD, "Roberto Dinamite", "748", "Brazil");
tbl.addTableEle(TableEle.TD, "Di Stéfano", "715", "Argentina");
tbl.addTableEle(TableEle.TD, "Puskas", "689", "Hungary");
tbl.addTableEle(TableEle.TD, "Flávio", "591", "Brazil");
tbl.addTableEle(TableEle.TD, "James McGory", "550", "Scotland");
tbl.addTableEle(TableEle.TD, "*** Leonardo Correa", "299", "Brazil/Australia");
tbl.addTableEle(TableEle.TD, "Maradona", "258", "Argentina");
tbl.addTableEle(TableEle.TF, "Total", "1,100,000.00", " ");
myDoc.addEle(tbl);
myDoc.addEle(BreakLine.times(1).create());
myDoc.addEle(Paragraph
.withPieces(
ParagraphPiece
.with("* Arthur Friedenreich - unofficial stats")
.withStyle().italic().create()).create());
myDoc.addEle(Paragraph
.withPieces(
ParagraphPiece
.with("** Zico was a mid-fieldfer and managed to score all those goals!")
.withStyle().italic().create()).create());
myDoc.addEle(Paragraph
.withPieces(
ParagraphPiece
.with("*** Leonardo Correa's goals (me) including futsal, soccer, friendly games, training games, so on... (but not playstation)")
.withStyle().italic().create()).create());
// HyperLink
myDoc.addEle(BreakLine.times(1).create());
myDoc.addEle(HyperLink.with("https://www.baidu.com/", "Hyperlink to baidu.com").create());
// PageBreaks
myDoc.addEle(Heading2.with("===== PageBreak ======").create());
myDoc.addEle(Paragraph.with("There is a PAGE BREAK after this line:")
.create());
myDoc.addEle(PageBreak.create());
myDoc.addEle(Paragraph.with("There is a PAGE BREAK before this line:")
.create());
String myWord = myDoc.getContent();
System.out.println(myWord);
TestUtils.createLocalDoc(myDoc.getContent());
}
附:以下提供直接可运行的spring boot工程:>>>点击这里下载代码