在Word文檔中, 表格 能使 文本內容更加 簡潔 明了 ,同時也能使 數據 的 展示 更加清晰直觀。 本文將介紹如何使 用 Java 代碼 在Word文檔中創建表格 并 設置 其單元格的 背景顏色 。
Jar文件導入方法
方法一:
下載 免費 的 Free Spire. Doc for Java 包并解壓縮 , 然后從lib文件夾下, 將 Spire. Doc .jar包 導入 到你的Java應用程序中。 ( 導入成功 后 如下圖所示 )

方法二:
通過 Maven倉庫安裝 導入 。 詳細的操作步驟 請參考鏈接:
https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html
Java代碼示例 :
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("創建表格.docx", FileFormat.Docx_2013);
}
}
創建表格效果圖:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。