当我们在编辑Word文档时,如果遇到大量数据需要体现,可以选择直接在Word文档中创建表格。将数据应用于表格内,不仅能够简化文档语言,而且也可以使数据内容更加清晰、直观。下面我就将使用Free Spire.Doc
for Java演示如何在Java中创建Word表格。
安装Spire.Doc.Jar
方法一:
如果您使用的是 maven,可以通过添加以下代码到项目的 pom.xml 文件中,将 JAR 文件导入到应用程序中。
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
方法二:
在Word中创建表格:
具体操作步骤:
- 创建一个Document对象,并向其添加一个节。
- 将标题行和其他行的数据分别存储在一维字符串数组和二维字符串数组中。
- 使用Section.addTable()方法将表格添加到节。
- 将数据插入标题行,并设置行格式,包括行高、背景颜色和文本对齐方式。
- 将数据插入其余行,并对这些行应用格式。
- 使用Document.saveToFile()方法保存文件。
相关代码:
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import java.awt.*;
public class CreateTable
{
public static void main(String[] args)
{
//创建一个Document对象
Document document = new Document();
//添加一个节
Section section = document.addSection();
//定义表格数据
String[] header = { "学号", "姓名", "性别", "班级", "成绩" };
String[][] data =
{
new String[]{"0105", "李雷", "男", "1", "88"},
new String[]{"0721", "赵文", "女", "7", "92"},
new String[]{"1131", "陈华", "女", "11", "91"},
new String[]{"0418", "宋野", "男", "4", "95"},
new String[]{"0513", "韩梅", "女", "5", "94"},
};
//添加表格
Table table = section.addTable(true);
table.resetCells(data.length + 1, header.length);
//将第一行设置为表格标题
TableRow row = table.getRows().get(0);
row.isHeader(true);
row.setHeight(20);
row.setHeightType(TableRowHeightType.Exactly);
row.getRowFormat().setBackColor(Color.gray);
for (int i = 0; i < header.length; i++)
{
row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
Paragraph p = row.getCells().get(i).addParagraph();
p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
TextRange txtRange = p.appendText(header[i]);
txtRange.getCharacterFormat().setBold(true);
}
//将数据添加到其余行
for (int r = 0; r < data.length; r++)
{
TableRow dataRow = table.getRows().get(r + 1);
dataRow.setHeight(25);
dataRow.setHeightType(TableRowHeightType.Exactly);
dataRow.getRowFormat().setBackColor(Color.white);
for (int c = 0; c < data[r].length; c++)
{
dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
}
}
//设置单元格的背景颜色
for (int j = 1; j < table.getRows().getCount(); j++)
{
if (j % 2 == 0)
{
TableRow row2 = table.getRows().get(j);
for (int f = 0; f < row2.getCells().getCount(); f++)
{
row2.getCells().get(f).getCellFormat().setBackColor(new Color(173, 216, 230));
}
}
}
//保存结果文件
document.saveToFile("result.docx", FileFormat.Docx_2013);
}
}