在word中,表格可以帮助我们更加清晰、直观地分析和展示数据。本文将介绍如何使用spire.doc for java在word文档中创建表格。
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) {
//创建word文档
document document = new document();
//添加一个section
section section = document.addsection();
//数据
string[] header = {"姓名", "性别", "部门", "工号"};
string[][] data =
{
new string[]{"winny", "女", "综合", "0109"},
new string[]{"lois", "女", "综合", "0111"},
new string[]{"jois", "男", "技术", "0110"},
new string[]{"moon", "女", "销售", "0112"},
new string[]{"vinit", "女", "后勤", "0113"},
};
//添加表格
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 range1 = p.appendtext(header[i]);
range1.getcharacterformat().setfontname("arial");
range1.getcharacterformat().setfontsize(12f);
range1.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);
textrange range2 = datarow.getcells().get(c).addparagraph().appendtext(data[r][c]);
range2.getcharacterformat().setfontname("arial");
range2.getcharacterformat().setfontsize(10f);
}
}
//设置单元格背景颜色
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("createtable.docx", fileformat.docx_2013);
}
}