这里只讲生成,不讲解析。。
首先先讲一下思路
大概从大到小的层级的关系是
XWPFDocument -> XWPFParagragh -> XWPFRun
具体添加文字,做各种文字颜色了效果了,都是用XWPFRun
贴代码
用document去建paragraph,用paragraph去建run
XWPFDocument xdoc = new XWPFDocument();
XWPFParagraph p = xdoc.createParagraph();
XWPFRun run = p.createRun();
然后就在run里写东西,就会,更新到文件里了
run.setBold(true); // 设置字体是否为加粗
run.setText("测试加粗字体sduasdashduiasdas "); //设置具体文字是什么
run.setColor("FF0000"); // 设置文字颜色
基本上大部分博客讲到这里就结束了
然而问题却还有很多,这个段落里我如果还想加内容呢,怎么办,重新都setText肯定是可以的,但是显得xue微有点不灵活了
然后就去查了一下Apache的文档,摸摸猜猜,搞出来了
大致可以分为两种情况
1、这个paragraph后面还想加文字,并且文字的颜色等样式,跟之前一模一样
直接贴代码
run.setText("另一个测试",1);
run.setText("测试字体2",2);
后面的第二个input 变量往上叠加就行了
2、这个paragraph后面想加的文字跟之前的样式不一样
这时候就需要,新建一个run,来处理
run = p.createRun();
run.setText("追加在后面");
这样就最后的结果就是
成功了,恭喜你,你先来
然后如果加paragraph就很简单了
再xdoc.createParagraph就行了
后面如果要传输,就再包裹成 数据流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
document.write(baos);
} catch (Exception e) {
throw new ServiceBizException("0", "生成excel异常");
}
byte[] content = baos.toByteArray();
InputStream inputStream = new ByteArrayInputStream(content);
最后贴上最终的完全代码
该有的功能解释, 注释里写的已经算比较详细了吧。。。。
package util;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author Ross
* 目前只包含 docx生成功能,不包含docx解析功能
* 包含写入不同字体
* 包含插入表格功能
* @date 2020 Jun.06
*/
public class DocUtil {
// 默认字号 12号 字体 宋体 颜色黑色 RGB16进制表示字体颜色
public static final int D_FONT_SIZE = 12;
public static final String D_FONT_TYPE = "宋体";
public static final String D_FONT_COLOR = "000000";
private XWPFDocument document;
private XWPFParagraph curPara;
private XWPFRun curRun;
private XWPFTable curTable;
//Constructors
public DocUtil() {
this.document = new XWPFDocument();
this.curPara = this.document.createParagraph();
this.curRun = this.curPara.createRun();
}
public DocUtil(XWPFDocument doc) {
this.document = doc;
this.curPara = this.document.createParagraph();
this.curRun = this.curPara.createRun();
}
public DocUtil(InputStream is) throws IOException {
this.document = new XWPFDocument(is);
this.curPara = this.document.createParagraph();
this.curRun = this.curPara.createRun();
}
// Getters
public XWPFDocument getDocument() {
return document;
}
public XWPFParagraph getCurPara() {
return curPara;
}
public XWPFRun getCurRun() {
return curRun;
}
/**
* 生成带页眉图片的模板
*/
public void genBonusTemplate() {
try {
this.document = new XWPFDocument(POIXMLDocument.openPackage(
"src/main/resources/file/bonusApplicationTemplate.docx"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 设置首行缩进几个 中文字符
*
* @param num
*/
public void setIndentation(int num) {
int twip = 239;
if (num > 0 && num <= 10) {
this.curPara.setIndentationFirstLine(num * twip);
}
}
/**
* 新开一个页面,强制分页
*/
public void createNewPage() {
this.curPara = this.document.createParagraph();
this.curPara.setPageBreak(true);
}
/**
* 设置当前段落行距
*
* @param num 磅的数量
*/
public void setSpacing(double num) {
this.curPara.setSpacingBetween(num, LineSpacingRule.EXACT);
}
/**
* 设置 写到目前为止的所有文档 内容的行距
*
* @param num 磅的数量
*/
public void setDocSpacing(double num) {
List<XWPFParagraph> list = this.document.getParagraphs();
for (int i = 0; i < list.size(); i++) {
list.get(i).setSpacingBetween(num, LineSpacingRule.EXACT);
}
}
/**
* 换行,开启新的一个段落
*/
public void newPara() {
this.curPara = this.document.createParagraph();
}
/**
* 按默认样式写入当前段落
*
* @param text
*/
public void write(String text) {
this.write(text, 0);
}
/**
* 按照某种模板样式写
*
* @param text
* @param styleNum
*/
public void write(String text, int styleNum) {
// 默认正文字体
this.curRun = this.curPara.createRun();
this.curRun.setText(text);
this.setFont(D_FONT_TYPE);
this.setFontSize(D_FONT_SIZE);
this.setFontColor(D_FONT_COLOR);
switch (styleNum) {
case 1:
//表头 加粗字体
this.setBold(true);
break;
case 2:
// 红字
this.setFontColor("FF00000");
break;
case 3:
//标题字体
this.setFontSize(17);
this.setBold(true);
this.setAlignment("center");
break;
case 4:
this.setUnderline(true);
break;
default:
}
}
/**
* 按目标样式写入当前段落
*
* @param text
* @param fontSize
* @param fontType
* @param fontColor
*/
public void write(String text,
int fontSize, String fontType, String fontColor) {
this.write(text, fontSize, fontType, fontColor, false, false, false);
}
/**
* 按目标样式写入当前段落
*
* @param text
* @param fontSize
* @param fontType
* @param fontColor
* @param bold
* @param underline
* @param italic
*/
public void write(String text,
int fontSize, String fontType, String fontColor,
boolean bold, boolean underline, boolean italic) {
this.curRun = this.curPara.createRun();
this.curRun.setText(text);
this.setFontSize(fontSize);
this.setFont(fontType);
this.setFontColor(fontColor);
this.setBold(bold);
this.setUnderline(underline);
this.setItalic(italic);
}
/// 字体样式
/**
* 设置当前字体
*
* @param font
*/
public void setFont(String font) {
this.curRun.setFontFamily(font);
}
/**
* 设置当前字号
*
* @param fontSize
*/
public void setFontSize(int fontSize) {
this.curRun.setFontSize(fontSize);
}
/**
* 设置当前字体颜色
*
* @param color
*/
public void setFontColor(String color) {
this.curRun.setColor(color);
}
/**
* 设置当前写入是否加粗
*
* @param bold
*/
public void setBold(boolean bold) {
this.curRun.setBold(bold);
}
/**
* 设置当前写入是否有下划线
*
* @param under
*/
public void setUnderline(boolean under) {
if (under) {
this.curRun.setUnderline(UnderlinePatterns.SINGLE);
} else {
this.curRun.setUnderline(UnderlinePatterns.NONE);
}
}
/**
* 设置当前写入是否斜体
*
* @param italic
*/
public void setItalic(boolean italic) {
this.curRun.setItalic(italic);
}
// 对齐
/**
* 设置当前段落的对齐方式,输入忽略大小写
* 写错了就是左对齐
*
* @param alignment
*/
public void setAlignment(String alignment) {
if (alignment == null) {
return;
}
this.setAlignment(alignment, this.document.getPosOfParagraph(this.curPara));
}
/**
* 设置第n段的对齐方式
*
* @param alignment
* @param paraNum
*/
public void setAlignment(String alignment, int paraNum) {
if (alignment == null || paraNum < 0) {
return;
}
List<XWPFParagraph> list = this.document.getParagraphs();
if (list.size() == 0 || list.size() <= paraNum) {
return;
}
String al = alignment.trim().toLowerCase();
XWPFParagraph p = list.get(paraNum);
if (al.equals("right")) {
p.setAlignment(ParagraphAlignment.RIGHT);
} else if (al.equals("center")) {
p.setAlignment(ParagraphAlignment.CENTER);
} else {
p.setAlignment(ParagraphAlignment.LEFT);
}
}
// 表格
/**
* 插入一个 row行 col列的空表格
*
* @param row
* @param col
*/
public void insertTable(int row, int col) {
if (row <= 0 || col <= 0) {
throw new IndexOutOfBoundsException();
}
this.curTable = this.document.createTable(row, col);
this.curTable.setWidthType(TableWidthType.PCT);
this.curTable.setTableAlignment(TableRowAlign.CENTER);
}
/**
* 生成一个表头为 String[] 的表格
*
* @param header
*/
public void insertTable(String[] header) {
if (header == null || header.length == 0) {
return;
}
this.insertTable(1, header.length);
XWPFTableRow r = this.curTable.getRow(0);
for (int i = 0; i < header.length; i++) {
//表头样式
this.setCellText(header[i], r.getCell(i), 1);
}
}
/**
* 按照 String [][] 的长宽和内容,生成一个table
*
* @param table
*/
public void insertTable(String[][] table) {
if (table == null || table.length == 0 || table[0].length == 0) {
return;
}
this.insertTable(table[0]);
for (int i = 1; i < table.length; i++) {
XWPFTableRow curR = this.curTable.createRow();
for (int j = 0; j < table[0].length; j++) {
this.setCellText(table[i][j], curR.getCell(j), 0);
}
}
}
/**
* 插入空的一行
*/
public void insertNewRow() {
if (this.curTable == null) {
throw new ServiceBizException("请先创建表格");
}
XWPFTableRow r = this.curTable.createRow();
//this.curTable.addRow(r);
}
/**
* 插入一列
*/
public void insertCol() {
if (this.curTable == null) {
throw new ServiceBizException("请先创建表格");
}
this.curTable.addNewCol();
}
/**
* 批量写入已经建好的表格
*/
public void writeInTable(String[][] info,int startRow) {
if (info == null || info.length == 0 || info[0].length == 0) {
return;
}
if (this.curTable == null) {
this.insertTable(info);
return;
}
int rows = this.curTable.getNumberOfRows();
for (int i = startRow; i < rows && i < info.length; i++) {
XWPFTableRow r = this.curTable.getRow(i);
for (int j = 0; j < info[0].length; j++) {
XWPFTableCell c = r.getCell(j);
if (c != null) {
this.setCellText(info[i-startRow][j], c, 0);
} else {
break;
}
}
}
}
/**
* 在原来的基础上,插入若干行
*/
public void writeMoreTable(String[][] info) {
if (info == null || info.length == 0 || info[0].length == 0) {
return;
}
if (this.curTable == null) {
this.insertTable(info);
return;
}
for (int i = 0; i < info.length; i++) {
XWPFTableRow r = this.curTable.createRow();
for (int j = 0; j < info[0].length; j++) {
XWPFTableCell c = r.getCell(j);
if (c != null) {
this.setCellText(info[i][j], c, 0);
} else {
break;
}
}
//this.curTable.addRow(r);
}
}
/**
* 将当前表格的第row行第col列改成 text
*
* @param row
* @param col
* @param text
* @param style
*/
public void setTableText(int row, int col, String text, int style) {
if (row < 0 || col < 0) {
return;
}
XWPFTableRow r = this.curTable.getRow(row);
if (r == null) {
return;
}
XWPFTableCell c = r.getCell(col);
if (c == null) {
return;
}
this.setCellText(text, c, style);
}
/**
* 插入默认样式的Text到某个cell里
*
* @param row
* @param col
* @param text
*/
public void setTableText(int row, int col, String text) {
this.setTableText(row, col, text, 0);
}
/**
* 按照一个预设样式插入text到cell 里
*
* @param text
* @param cell
* @param style
*/
public void setCellText(String text, XWPFTableCell cell, int style) {
if (text == null || text.length() == 0 || cell == null || style < 0) {
return;
}
this.curPara = cell.getParagraphs().get(0);
this.write(text, style);
}
/**
* 转换成Stream
*
* @return
*/
public InputStream toInputStream() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
document.write(baos);
} catch (Exception e) {
throw new ServiceBizException("0", "生成Word文件异常");
}
byte[] content = baos.toByteArray();
baos.close();
return new ByteArrayInputStream(content);
}
/**
* 关闭文件流
*/
public void close(){
try {
this.document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}