原文见:http://programmingbb.blogspot.com/2014/08/using-docx4j-to-generate-docx-files.html .下面的代码稍微修改了下:
import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import org.apache.commons.io.IOUtils; import org.docx4j.dml.wordprocessingDrawing.Inline; import org.docx4j.jaxb.Context; import org.docx4j.model.structure.PageDimensions; import org.docx4j.model.structure.PageSizePaper; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage; import org.docx4j.wml.Body; import org.docx4j.wml.BooleanDefaultTrue; import org.docx4j.wml.CTBorder; import org.docx4j.wml.CTShd; import org.docx4j.wml.CTTblPrBase.TblStyle; import org.docx4j.wml.CTVerticalJc; import org.docx4j.wml.Color; import org.docx4j.wml.Drawing; import org.docx4j.wml.HpsMeasure; import org.docx4j.wml.Jc; import org.docx4j.wml.JcEnumeration; import org.docx4j.wml.ObjectFactory; import org.docx4j.wml.P; import org.docx4j.wml.PPr; import org.docx4j.wml.R; import org.docx4j.wml.RFonts; import org.docx4j.wml.RPr; import org.docx4j.wml.STBorder; import org.docx4j.wml.STVerticalJc; import org.docx4j.wml.SectPr; import org.docx4j.wml.SectPr.PgMar; import org.docx4j.wml.Tbl; import org.docx4j.wml.TblPr; import org.docx4j.wml.TblWidth; import org.docx4j.wml.Tc; import org.docx4j.wml.TcMar; import org.docx4j.wml.TcPr; import org.docx4j.wml.TcPrInner.GridSpan; import org.docx4j.wml.TcPrInner.TcBorders; import org.docx4j.wml.TcPrInner.VMerge; import org.docx4j.wml.Text; import org.docx4j.wml.Tr; import org.docx4j.wml.U; import org.docx4j.wml.UnderlineEnumeration; //原文见:http://programmingbb.blogspot.com/2014/08/using-docx4j-to-generate-docx-files.html public class Docx4j_创建表格_S5_Test { public static void main(String[] args) throws Exception { Docx4j_创建表格_S5_Test t = new Docx4j_创建表格_S5_Test(); t.testDocx4jCreateTable(); } public void testDocx4jCreateTable() throws Exception { boolean landscape = false; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage .createPackage(PageSizePaper.A4, landscape); ObjectFactory factory = Context.getWmlObjectFactory(); setPageMargins(wordMLPackage, factory); String imgFilePath = "f:/saveFile/tmp/2sql日志.jpg"; Tbl table = createTableWithContent(wordMLPackage, factory, imgFilePath); wordMLPackage.getMainDocumentPart().addObject(table); wordMLPackage.save(new File("f:/saveFile/temp/sys_" + System.currentTimeMillis() + ".docx")); } public Tbl createTableWithContent(WordprocessingMLPackage wordMLPackage, ObjectFactory factory, String imgFilePath) throws Exception { Tbl table = factory.createTbl(); // for TEST: this adds borders to all cells TblPr tblPr = new TblPr(); TblStyle tblStyle = new TblStyle(); tblStyle.setVal("TableGrid"); tblPr.setTblStyle(tblStyle); table.setTblPr(tblPr); Tr tableRow = factory.createTr(); // a default table cell style Docx4jStyle_S3 defStyle = new Docx4jStyle_S3(); defStyle.setBold(false); defStyle.setItalic(false); defStyle.setUnderline(false); defStyle.setHorizAlignment(JcEnumeration.CENTER); // a specific table cell style Docx4jStyle_S3 style = new Docx4jStyle_S3(); style.setBold(true); style.setItalic(true); style.setUnderline(true); style.setFontSize("40"); style.setFontColor("FF0000"); style.setCnFontFamily("微软雅黑"); style.setEnFontFamily("Times New Roman"); style.setTop(300); style.setBackground("CCFFCC"); style.setVerticalAlignment(STVerticalJc.CENTER); style.setHorizAlignment(JcEnumeration.CENTER); style.setBorderTop(true); style.setBorderBottom(true); style.setNoWrap(true); addTableCell(factory, tableRow, "测试Field 1", 3500, style, 1, null); // start vertical merge for Filed 2 and Field 3 on 3 rows addTableCell(factory, tableRow, "测试Field 2", 3500, defStyle, 1, "restart"); addTableCell(factory, tableRow, "测试Field 3", 1500, defStyle, 1, "restart"); table.getContent().add(tableRow); tableRow = factory.createTr(); addTableCell(factory, tableRow, "Text", 3500, defStyle, 1, null); addTableCell(factory, tableRow, "", 3500, defStyle, 1, ""); addTableCell(factory, tableRow, "", 1500, defStyle, 1, ""); table.getContent().add(tableRow); tableRow = factory.createTr(); addTableCell(factory, tableRow, "Interval", 3500, defStyle, 1, null); addTableCell(factory, tableRow, "", 3500, defStyle, 1, "close"); addTableCell(factory, tableRow, "", 1500, defStyle, 1, "close"); table.getContent().add(tableRow); // add an image horizontally merged on 3 cells String filenameHint = null; String altText = null; int id1 = 0; int id2 = 1; byte[] bytes = getImageBytes(imgFilePath); P pImage; try { pImage = newImage(wordMLPackage, factory, bytes, filenameHint, altText, id1, id2, 8500); tableRow = factory.createTr(); addTableCell(factory, tableRow, pImage, 8500, defStyle, 3, null); table.getContent().add(tableRow); } catch (Exception e) { e.printStackTrace(); } return table; } public byte[] getImageBytes(String imgFilePath) throws Exception { return IOUtils.toByteArray(new FileInputStream(imgFilePath)); } public void addTableCell(ObjectFactory factory, Tr tableRow, P image, int width, Docx4jStyle_S3 style, int horizontalMergedCells, String verticalMergedVal) { Tc tableCell = factory.createTc(); addImageCellStyle(tableCell, image, style); setCellWidth(tableCell, width); setCellVMerge(tableCell, verticalMergedVal); setCellHMerge(tableCell, horizontalMergedCells); tableRow.getContent().add(tableCell); } public void addTableCell(ObjectFactory factory, Tr tableRow, String content, int width, Docx4jStyle_S3 style, int horizontalMergedCells, String verticalMergedVal) { Tc tableCell = factory.createTc(); addCellStyle(factory, tableCell, content, style); setCellWidth(tableCell, width); setCellVMerge(tableCell, verticalMergedVal); setCellHMerge(tableCell, horizontalMergedCells); if (style.isNoWrap()) { setCellNoWrap(tableCell); } tableRow.getContent().add(tableCell); } public void addCellStyle(ObjectFactory factory, Tc tableCell, String content, Docx4jStyle_S3 style) { if (style != null) { P paragraph = factory.createP(); Text text = factory.createText(); text.setValue(content); R run = factory.createR(); run.getContent().add(text); paragraph.getContent().add(run); setHorizontalAlignment(paragraph, style.getHorizAlignment()); RPr runProperties = factory.createRPr(); if (style.isBold()) { addBoldStyle(runProperties); } if (style.isItalic()) { addItalicStyle(runProperties); } if (style.isUnderline()) { addUnderlineStyle(runProperties); } setFontSize(runProperties, style.getFontSize()); setFontColor(runProperties, style.getFontColor()); setFontFamily(runProperties, style.getCnFontFamily(),style.getEnFontFamily()); setCellMargins(tableCell, style.getTop(), style.getRight(), style.getBottom(), style.getLeft()); setCellColor(tableCell, style.getBackground()); setVerticalAlignment(tableCell, style.getVerticalAlignment()); setCellBorders(tableCell, style.isBorderTop(), style.isBorderRight(), style.isBorderBottom(), style.isBorderLeft()); run.setRPr(runProperties); tableCell.getContent().add(paragraph); } } public void addImageCellStyle(Tc tableCell, P image, Docx4jStyle_S3 style) { setCellMargins(tableCell, style.getTop(), style.getRight(), style.getBottom(), style.getLeft()); setCellColor(tableCell, style.getBackground()); setVerticalAlignment(tableCell, style.getVerticalAlignment()); setHorizontalAlignment(image, style.getHorizAlignment()); setCellBorders(tableCell, style.isBorderTop(), style.isBorderRight(), style.isBorderBottom(), style.isBorderLeft()); tableCell.getContent().add(image); } public P newImage(WordprocessingMLPackage wordMLPackage, ObjectFactory factory, byte[] bytes, String filenameHint, String altText, int id1, int id2, long cx) throws Exception { BinaryPartAbstractImage imagePart = BinaryPartAbstractImage .createImagePart(wordMLPackage, bytes); Inline inline = imagePart.createImageInline(filenameHint, altText, id1, id2, cx, false); // Now add the inline in w:p/w:r/w:drawing P p = factory.createP(); R run = factory.createR(); p.getContent().add(run); Drawing drawing = factory.createDrawing(); run.getContent().add(drawing); drawing.getAnchorOrInline().add(inline); return p; } public void setCellBorders(Tc tableCell, boolean borderTop, boolean borderRight, boolean borderBottom, boolean borderLeft) { TcPr tableCellProperties = tableCell.getTcPr(); if (tableCellProperties == null) { tableCellProperties = new TcPr(); tableCell.setTcPr(tableCellProperties); } CTBorder border = new CTBorder(); // border.setColor("auto"); border.setColor("0000FF"); border.setSz(new BigInteger("20")); border.setSpace(new BigInteger("0")); border.setVal(STBorder.SINGLE); TcBorders borders = new TcBorders(); if (borderBottom) { borders.setBottom(border); } if (borderTop) { borders.setTop(border); } if (borderLeft) { borders.setLeft(border); } if (borderRight) { borders.setRight(border); } tableCellProperties.setTcBorders(borders); } public void setCellWidth(Tc tableCell, int width) { if (width > 0) { TcPr tableCellProperties = tableCell.getTcPr(); if (tableCellProperties == null) { tableCellProperties = new TcPr(); tableCell.setTcPr(tableCellProperties); } TblWidth tableWidth = new TblWidth(); tableWidth.setType("dxa"); tableWidth.setW(BigInteger.valueOf(width)); tableCellProperties.setTcW(tableWidth); } } public void setCellNoWrap(Tc tableCell) { TcPr tableCellProperties = tableCell.getTcPr(); if (tableCellProperties == null) { tableCellProperties = new TcPr(); tableCell.setTcPr(tableCellProperties); } BooleanDefaultTrue b = new BooleanDefaultTrue(); b.setVal(true); tableCellProperties.setNoWrap(b); } public void setCellVMerge(Tc tableCell, String mergeVal) { if (mergeVal != null) { TcPr tableCellProperties = tableCell.getTcPr(); if (tableCellProperties == null) { tableCellProperties = new TcPr(); tableCell.setTcPr(tableCellProperties); } VMerge merge = new VMerge(); if (!"close".equals(mergeVal)) { merge.setVal(mergeVal); } tableCellProperties.setVMerge(merge); } } public void setCellHMerge(Tc tableCell, int horizontalMergedCells) { if (horizontalMergedCells > 1) { TcPr tableCellProperties = tableCell.getTcPr(); if (tableCellProperties == null) { tableCellProperties = new TcPr(); tableCell.setTcPr(tableCellProperties); } GridSpan gridSpan = new GridSpan(); gridSpan.setVal(new BigInteger(String .valueOf(horizontalMergedCells))); tableCellProperties.setGridSpan(gridSpan); tableCell.setTcPr(tableCellProperties); } } public void setCellColor(Tc tableCell, String color) { if (color != null) { TcPr tableCellProperties = tableCell.getTcPr(); if (tableCellProperties == null) { tableCellProperties = new TcPr(); tableCell.setTcPr(tableCellProperties); } CTShd shd = new CTShd(); shd.setFill(color); tableCellProperties.setShd(shd); } } public void setCellMargins(Tc tableCell, int top, int right, int bottom, int left) { TcPr tableCellProperties = tableCell.getTcPr(); if (tableCellProperties == null) { tableCellProperties = new TcPr(); tableCell.setTcPr(tableCellProperties); } TcMar margins = new TcMar(); if (bottom > 0) { TblWidth bW = new TblWidth(); bW.setType("dxa"); bW.setW(BigInteger.valueOf(bottom)); margins.setBottom(bW); } if (top > 0) { TblWidth tW = new TblWidth(); tW.setType("dxa"); tW.setW(BigInteger.valueOf(top)); margins.setTop(tW); } if (left > 0) { TblWidth lW = new TblWidth(); lW.setType("dxa"); lW.setW(BigInteger.valueOf(left)); margins.setLeft(lW); } if (right > 0) { TblWidth rW = new TblWidth(); rW.setType("dxa"); rW.setW(BigInteger.valueOf(right)); margins.setRight(rW); } tableCellProperties.setTcMar(margins); } public void setVerticalAlignment(Tc tableCell, STVerticalJc align) { if (align != null) { TcPr tableCellProperties = tableCell.getTcPr(); if (tableCellProperties == null) { tableCellProperties = new TcPr(); tableCell.setTcPr(tableCellProperties); } CTVerticalJc valign = new CTVerticalJc(); valign.setVal(align); tableCellProperties.setVAlign(valign); } } public void setFontSize(RPr runProperties, String fontSize) { if (fontSize != null && !fontSize.isEmpty()) { HpsMeasure size = new HpsMeasure(); size.setVal(new BigInteger(fontSize)); runProperties.setSz(size); runProperties.setSzCs(size); } } public void setFontFamily(RPr runProperties, String cnFontFamily,String enFontFamily) { if (cnFontFamily != null||enFontFamily!=null) { RFonts rf = runProperties.getRFonts(); if (rf == null) { rf = new RFonts(); runProperties.setRFonts(rf); } if(cnFontFamily!=null){ rf.setEastAsia(cnFontFamily); } if(enFontFamily!=null){ rf.setAscii(enFontFamily); } } } public void setFontColor(RPr runProperties, String color) { if (color != null) { Color c = new Color(); c.setVal(color); runProperties.setColor(c); } } public void setHorizontalAlignment(P paragraph, JcEnumeration hAlign) { if (hAlign != null) { PPr pprop = new PPr(); Jc align = new Jc(); align.setVal(hAlign); pprop.setJc(align); paragraph.setPPr(pprop); } } public void addBoldStyle(RPr runProperties) { BooleanDefaultTrue b = new BooleanDefaultTrue(); b.setVal(true); runProperties.setB(b); } public void addItalicStyle(RPr runProperties) { BooleanDefaultTrue b = new BooleanDefaultTrue(); b.setVal(true); runProperties.setI(b); } public void addUnderlineStyle(RPr runProperties) { U val = new U(); val.setVal(UnderlineEnumeration.SINGLE); runProperties.setU(val); } public void setPageMargins(WordprocessingMLPackage wordMLPackage, ObjectFactory factory) { try { Body body = wordMLPackage.getMainDocumentPart().getContents() .getBody(); PageDimensions page = new PageDimensions(); PgMar pgMar = page.getPgMar(); pgMar.setBottom(BigInteger.valueOf(pixelsToDxa(50))); pgMar.setTop(BigInteger.valueOf(pixelsToDxa(50))); pgMar.setLeft(BigInteger.valueOf(pixelsToDxa(50))); pgMar.setRight(BigInteger.valueOf(pixelsToDxa(50))); SectPr sectPr = factory.createSectPr(); body.setSectPr(sectPr); sectPr.setPgMar(pgMar); } catch (Exception e) { e.printStackTrace(); } } // get dots per inch public static int getDPI() { return GraphicsEnvironment.isHeadless() ? 96 : Toolkit .getDefaultToolkit().getScreenResolution(); } public int pixelsToDxa(int pixels) { return (1440 * pixels / getDPI()); } } class Docx4jStyle_S3 { private boolean bold; private boolean italic; private boolean underline; private String fontSize; private String fontColor; private String cnFontFamily; private String enFontFamily; // cell margins private int left; private int bottom; private int top; private int right; private String background; private STVerticalJc verticalAlignment; private JcEnumeration horizAlignment; private boolean borderLeft; private boolean borderRight; private boolean borderTop; private boolean borderBottom; private boolean noWrap; public boolean isBold() { return bold; } public void setBold(boolean bold) { this.bold = bold; } public boolean isItalic() { return italic; } public void setItalic(boolean italic) { this.italic = italic; } public boolean isUnderline() { return underline; } public void setUnderline(boolean underline) { this.underline = underline; } public String getFontSize() { return fontSize; } public void setFontSize(String fontSize) { this.fontSize = fontSize; } public String getFontColor() { return fontColor; } public void setFontColor(String fontColor) { this.fontColor = fontColor; } public String getCnFontFamily() { return cnFontFamily; } public void setCnFontFamily(String cnFontFamily) { this.cnFontFamily = cnFontFamily; } public String getEnFontFamily() { return enFontFamily; } public void setEnFontFamily(String enFontFamily) { this.enFontFamily = enFontFamily; } public int getLeft() { return left; } public void setLeft(int left) { this.left = left; } public int getBottom() { return bottom; } public void setBottom(int bottom) { this.bottom = bottom; } public int getTop() { return top; } public void setTop(int top) { this.top = top; } public int getRight() { return right; } public void setRight(int right) { this.right = right; } public String getBackground() { return background; } public void setBackground(String background) { this.background = background; } public STVerticalJc getVerticalAlignment() { return verticalAlignment; } public void setVerticalAlignment(STVerticalJc verticalAlignment) { this.verticalAlignment = verticalAlignment; } public JcEnumeration getHorizAlignment() { return horizAlignment; } public void setHorizAlignment(JcEnumeration horizAlignment) { this.horizAlignment = horizAlignment; } public boolean isBorderLeft() { return borderLeft; } public void setBorderLeft(boolean borderLeft) { this.borderLeft = borderLeft; } public boolean isBorderRight() { return borderRight; } public void setBorderRight(boolean borderRight) { this.borderRight = borderRight; } public boolean isBorderTop() { return borderTop; } public void setBorderTop(boolean borderTop) { this.borderTop = borderTop; } public boolean isBorderBottom() { return borderBottom; } public void setBorderBottom(boolean borderBottom) { this.borderBottom = borderBottom; } public boolean isNoWrap() { return noWrap; } public void setNoWrap(boolean noWrap) { this.noWrap = noWrap; } }
结果为:
全文完。
相关推荐
这篇博客“docx4j 动态生成表格 (一 )”将引导我们深入理解如何利用docx4j库来创建和操作Word文档中的表格。 首先,让我们了解docx4j的基本概念。docx4j是一个开源项目,它允许开发者通过编程方式创建、修改和...
下面是一个简单的示例,演示如何使用`docx4j`根据书签替换Word文档中的内容。首先,你需要在你的项目中引入`docx4j`库,可以通过Maven或者Gradle等构建工具添加依赖。 ```xml <groupId>org.docx4j <artifactId>...
以下是一个简单的示例,演示如何使用docx4j在现有Word文档中添加文本: ```java import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML....
**docx4j** 是一个Java库,专为处理Microsoft Office Open XML (OOXML) 文件格式而设计。...在实际项目中,确保正确地引入所有依赖,并遵循docx4j的官方文档和示例,可以帮助开发者高效地利用这个库。
在"docx4j运行需要的jar包,这里是整理好的所有必须的jar包"这一描述中,我们可以推断出这个压缩包包含了一系列docx4j运行所必需的依赖库。通常,一个完整的docx4j项目会包含以下几类jar文件: 1. **docx4j主库**:...
1. **文档创建**: docx4j可以生成全新的Word文档,包括创建段落、列表、表格等元素,并能设置字体、颜色、大小等样式。 2. **内容替换**: 使用`Docx4j.replaceText()`方法,可以方便地替换文档中的指定文本,这在...
**docx4j** 是一个Java库,专为处理Microsoft Office Open XML (OOXML) 文件格式,如.docx、.xlsx和.pptx而设计。它提供了强大的功能,包括创建、读取、修改以及转换这些文件。在本讨论中,我们将深入探讨docx4j在...
博客中的示例代码“MakeTemplateWord.java”很可能是展示如何利用docx4j创建复杂文档的一个实例。这个文件可能会包含一个完整的例子,从读取模板文档(如“template.docx”)开始,然后修改或添加内容,最后保存新...
docx4j是一个Java库,专门用于处理Microsoft Office Open XML(OOXML)格式,特别是.docx和.pptx文档。这个库提供了丰富的功能,包括创建、读取、修改以及转换这些文档。它允许开发者通过编程方式操作Word文档,极大...
2. **创建新文档**:使用`org.docx4j.jaxb.Context`类初始化上下文,然后通过`org.docx4j.Docx4J.createDocument()`方法创建一个新的Word文档。 3. **操作文档内容**:可以使用`org.docx4j.model.content.Body`和`...
docx4j是一个功能强大的Java类库,用于创建和操作Microsoft Open XML文件,如Word docx、PowerPoint pptx和Excel xlsx。今天,我们将详细介绍如何使用docx4j操作Word文档。 1. Docx4j介绍 docx4j是一个开源的Java...
为了方便开发者,一个名为docx4j的开源库应运而生,它允许程序员以编程方式创建、修改和转换docx文件。本文将深入探讨docx4j-3.3.3版本,以及它如何助力Java开发者在项目中高效地处理docx文档。 docx4j是一个基于...
赠送jar包:docx4j-3.3.5.jar; 赠送原API文档:docx4j-3.3.5-javadoc.jar; 赠送源代码:docx4j-3.3.5-sources.jar; 赠送Maven依赖信息文件:docx4j-3.3.5.pom; 包含翻译后的API文档:docx4j-3.3.5-javadoc-API...
docx4j提供了一系列API来操作docx文档,包括读取、创建、修改和合并。要实现多文档合并,你需要做以下步骤: 1. **读取docx文件**:使用`org.docx4j.openpackaging.packages.WordprocessingMLPackage`类加载每个...
《docx4j及其依赖的jar包:实现高效文档处理》 在信息技术领域,文档处理是日常工作中不可或缺的一部分。docx4j是一个强大的Java库,专门用于处理Microsoft Office Open XML (OOXML)格式的文件,如.docx和.xlsx。这...
Docx4j是一个用于Java语言中处理Word文档、PowerPoint演示文稿和Excel表格的开源类库。它允许开发者通过XML解析文档内容,而不是采用DOM或SAX解析器。Docx4j使用JAXB(Java API for XML Binding)在内存中构建文档的...
使用docx4j创建新文档,首先需要实例化对应的`Package`对象,然后可以使用`createPart`方法添加新的部分,如文本、表格、图片等。例如,创建一个新的.docx文档并添加段落: ```java WordprocessingMLPackage ...
用docx4j,jar出去word书签,在word书签中插入文本 源码可以通过以下链接查看: https://github.com/xulp-mzl/xlp-core https://github.com/xulp-mzl/xlp-third ...实例: public static void main(String[] args) ...
- **创建文档**:使用docx4j可以创建新的.docx文档,添加文本、段落、表格等元素。 - **读取文档**:读取现有.docx文件,获取其中的段落、表格、图片等信息。 - **修改文档**:更新文档内容,例如替换文本、修改...
### Docx4j入门中文版知识点...总之,Docx4j是一个强大且灵活的工具,为开发者提供了广泛的功能和支持,能够满足从简单的文档创建到复杂的数据处理等各种需求。无论是初学者还是有经验的开发者,都能够从中受益匪浅。