DOCX
表格
创建包含行、单元格、合并单元格、边框和样式的表格
使用 Table、TableRow 和 TableCell 向文档中添加结构化数据。
基本表格
import { Table, TableRow, TableCell, Paragraph, TextRun } from "@office-open/docx";
new Table({
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph({ children: [new TextRun("Name")] })],
}),
new TableCell({
children: [new Paragraph({ children: [new TextRun("Age")] })],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [new Paragraph({ children: [new TextRun("Alice")] })],
}),
new TableCell({
children: [new Paragraph({ children: [new TextRun("30")] })],
}),
],
}),
],
});
列宽
new Table({
columnWidths: [3000, 2000, 2000],
rows: [
new TableRow({
children: [
new TableCell({
width: { size: 3000, type: "dxa" },
children: [new Paragraph("Col 1")],
}),
new TableCell({
width: { size: 2000, type: "dxa" },
children: [new Paragraph("Col 2")],
}),
new TableCell({
width: { size: 2000, type: "dxa" },
children: [new Paragraph("Col 3")],
}),
],
}),
],
});
合并单元格
使用 verticalMerge 进行垂直合并,使用 columnSpan 进行水平合并:
import { VerticalMergeType } from "@office-open/docx";
new Table({
rows: [
new TableRow({
children: [
// 开始垂直合并
new TableCell({
verticalMerge: VerticalMergeType.RESTART,
children: [new Paragraph("Merged (2 rows)")],
}),
new TableCell({
children: [new Paragraph("B1")],
}),
],
}),
new TableRow({
children: [
// 继续垂直合并
new TableCell({
verticalMerge: VerticalMergeType.CONTINUE,
children: [new Paragraph()],
}),
new TableCell({
children: [new Paragraph("B2")],
}),
],
}),
],
});
表格边框
new Table({
borders: {
top: { style: "single", size: 1, color: "000000" },
bottom: { style: "single", size: 1, color: "000000" },
left: { style: "single", size: 1, color: "000000" },
right: { style: "single", size: 1, color: "000000" },
insideHorizontal: { style: "single", size: 1, color: "000000" },
insideVertical: { style: "single", size: 1, color: "000000" },
},
rows: [
// ...行
],
});
单元格格式
为单个单元格设置背景、边框和垂直对齐:
new TableCell({
shading: { fill: "F2F2F2" },
verticalAlign: "center",
borders: {
top: { style: "single", size: 1, color: "CCCCCC" },
bottom: { style: "single", size: 1, color: "CCCCCC" },
left: { style: "single", size: 1, color: "CCCCCC" },
right: { style: "single", size: 1, color: "CCCCCC" },
},
children: [new Paragraph("样式化单元格")],
});
表格宽度模式
控制表格如何占用页面宽度:
new Table({
width: { size: 100, type: "pct" }, // 占页面宽度 100%
rows: [
// ...行
],
});
宽度类型:
"dxa"— 固定宽度(TWIP)"pct"— 页面宽度百分比(50 = 50%)"auto"— 自动适应内容
Table 选项参考
| 选项 | 类型 | 说明 |
|---|---|---|
rows | TableRow[] | 表格行 |
width | object | 表格宽度({ size, type }) |
columnWidths | number[] | 各列宽度(TWIP) |
borders | object | 所有边的边框定义 |
float | object | 浮动表格定位 |