java word表格_Java 在Word中创建表格

这段代码展示了如何在Java应用中利用Spire.Doc库创建一个包含表头的Word文档表格。它首先创建了一个文档对象,然后添加了一个段落,并定义了表格的数据结构。接着,设置了表格的行数、列数,以及表头和数据的样式,包括字体、大小、颜色和对齐方式。最后,设置了单元格背景色并保存了文档。
摘要由CSDN通过智能技术生成

import com.spire.doc.*;import com.spire.doc.documents.*;importcom.spire.doc.fields.TextRange;import java.awt.*;public classCreateTable {public static voidmain(String[] args) {//创建Word文档

Document document = newDocument();//添加一个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("创建表格.docx", FileFormat.Docx_2013);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值