C#如何使用DocumentFormat.OpenXml生成WORD插入表格时宽度按百分比
在 ?DocumentFormat.OpenXml? 中,设置表格按百分比宽度需通过 TableWidth 的 Type 属性和值调整实现。以下是具体方法及代码示例:
?1. 设置表格整体宽度为百分比?
通过 TableWidth.Type = TableWidthUnitValues.Pct 定义表格占页面宽度的百分比,数值需 ?乘以 100?(例如 50% 对应 Width = "5000"):
Table table = new Table();
// 设置表格宽度为页面宽度的 50%
TableProperties tableProperties = new TableProperties(
new TableWidth {
Width = "5000", // 50% → 5000 (50 * 100)
Type = TableWidthUnitValues.Pct
}
);
table.AppendChild(tableProperties);
?2. 设置列宽按比例分配?
由于 OpenXML ?不支持直接定义列宽的百分比?,需通过以下两种方式模拟比例效果:
?方法一:自动列宽(推荐)?
让 Word 根据内容自动分配列宽(适合动态内容):
// 启用表格自动布局
tableProperties.Append(new TableLayout { Type = TableLayoutValues.Autofit });
// 不定义 GridColumn 的 Width,或设置为自动
TableGrid grid = new TableGrid();
grid.Append(new GridColumn(), new GridColumn()); // 两列自动调整
table.Append(grid);
?方法二:固定列宽模拟比例?
手动计算固定单位(如 Dxa)的列宽,使总和等于表格总宽度(适合已知页面尺寸的场景):
// 假设页面宽度为 11906 Dxa(A4 纸,21厘米)
int tableTotalWidthDxa = 11906 / 2; // 表格占页面 50%(5953 Dxa)
// 定义两列分别占 30% 和 70%
int col1Width = (int)(tableTotalWidthDxa * 0.3); // 1785 Dxa
int col2Width = (int)(tableTotalWidthDxa * 0.7); // 4167 Dxa
TableGrid grid = new TableGrid();
grid.Append(
new GridColumn { Width = col1Width.ToString() },
new GridColumn { Width = col2Width.ToString() }
);
table.Append(grid);
?完整代码示例?
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
// 创建表格
Table table = new Table();
// 设置表格占页面宽度 50%
TableProperties tableProperties = new TableProperties(
new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct },
new TableLayout { Type = TableLayoutValues.Autofit } // 自动调整列宽
);
table.AppendChild(tableProperties);
// 添加两列(自动调整宽度)
TableGrid grid = new TableGrid();
grid.Append(new GridColumn(), new GridColumn());
table.Append(grid);
// 添加行和单元格
TableRow row = new TableRow();
row.Append(
new TableCell(new Paragraph(new Run(new Text("列1")))),
new TableCell(new Paragraph(new Run(new Text("列2"))))
);
table.Append(row);
// 将表格添加到文档
Body body = new Body();
body.Append(table);
?关键参数说明?
属性/值 说明
TableWidthUnitValues.Pct 表示百分比单位,需将实际百分比乘以 100(如 75% → Width = "7500")
TableLayoutValues.Autofit 自动调整列宽,适合动态内容
TableLayoutValues.Fixed 固定列宽,需手动设置 GridColumn.Width(单位:Dxa)
?注意事项?
?百分比基准?
TableWidth 的百分比基于 ?页面有效宽度?(去除页边距后的区域),而非整个纸张宽度。
?列宽精度?
手动计算固定列宽时,需确保总和等于表格总宽度,否则可能导致布局错位。
?动态页面兼容性?
若需适应不同页面尺寸,优先使用 Autofit 自动布局,而非固定数值。
通过上述方法,即可在 Word 文档中生成按百分比调整宽度的表格,并根据需求选择自动或固定列宽模式。
查看更多关于C#如何使用DocumentFormat.OpenXml生成WORD插入表格时宽度按百分比的详细内容...