您的位置:首页 > 编程语言 > Java开发

通过Java添加Word文本框过程详解

2019-11-05 18:07 2516 查看

前言

在Word中,文本框是指一种可移动、可调节大小的文字或图形容器。我们可以向文本框中添加文字、图片、表格等对象,下面,将通过Java编程来实现添加以上对象到Word文本框。

使用工具:Free Spire.Doc for Java (免费版)

Jar文件获取及导入:

方法1:通过官网下载获取jar包。下载后,解压文件,并将lib文件夹下的Spire.Doc.jar文件导入Java程序。(如下图)

方法2:通过maven仓库安装导入。

Java代码示例

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextBox;
import com.spire.doc.fields.TextRange;
import java.awt.*;

public class AddTextbox {
public static void main(String[] args) {
//创建文档
Document doc = new Document();

//添加指定大小的文本框
TextBox tb = doc.addSection().addParagraph().appendTextBox(380, 280);
//设置文字环绕方式
tb.getFormat().setTextWrappingStyle(TextWrappingStyle.Square);
//设置文本框的相对位置
tb.getFormat().setHorizontalOrigin(HorizontalOrigin.Left_Margin_Area);
tb.getFormat().setHorizontalPosition(120f);
tb.getFormat().setVerticalOrigin(VerticalOrigin.Page);
tb.getFormat().setVerticalPosition(100f);
//设置文本框边框样式
tb.getFormat().setLineStyle(TextBoxLineStyle.Thin_Thick);
tb.getFormat().setLineColor(Color.gray);

//插入图片到文本框
Paragraph para = tb.getBody().addParagraph();
DocPicture picture = para.appendPicture("tp.png");
picture.setHeight(120f);
picture.setWidth(180f);
para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
para.getFormat().setAfterSpacing(13f);

//插入文字到文本框
para = tb.getBody().addParagraph();
TextRange textRange = para.appendText("中美贸易争端,又称中美贸易战,也叫中美贸易摩擦,是中美经济关系中的重要问题。 "
+ "贸易争端主要发生在两个方面:一是中国具有比较优势的出口领域;"
+ "二是中国没有优势的进口和技术知识领域。");
textRange.getCharacterFormat().setFontName("楷体");
textRange.getCharacterFormat().setFontSize(11f);
para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

//添加表格到文本框
//声明数组内容
String[][] data = new String[][]{
new String[]{"国家", "年份", "出口额(美元)", "进口额(美元)"},
new String[]{"中国", "2017", "125468", "101109"},
new String[]{"美国", "2017", "86452", "124298"},
};
//添加表格
Table table = tb.getBody().addTable();
//指定表格行数、列数
table.resetCells(3,4);
//将数组内容填充到表格
for (int i = 0; i < data.length; i++) {
TableRow dataRow = table.getRows().get(i);
dataRow.getCells().get(i).setWidth(70);
dataRow.setHeight(22);
dataRow.setHeightType(TableRowHeightType.Exactly);
for (int j = 0; j < data[i].length; j++) {
dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
TextRange range2 = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
range2.getCharacterFormat().setFontName("楷体");
range2.getCharacterFormat().setFontSize(11f);
range2.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
}
}
//应用表格样式
table.applyStyle(DefaultTableStyle.Colorful_Grid_Accent_3);

//保存文档
doc.saveToFile("AddTextbox.docx", FileFormat.Docx_2013);
}
}

文本框添加效果:

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 添加 word 文本框