C#代码实现设置Word表格的列宽
探讨了在C#中设置Word表格列宽的两种方式:按百分比使表格自适应页面,按固定值保持结构稳定。通过Spire.Doc遍历行设置单元格宽度实现百分比或固定值控制,并介绍了OpenXMLSDK与Aspose.Words的替代方案。
表格列宽这事儿吧,别看它不起眼,其实直接影响着整个文档的“颜值”和阅读体验。特别是当你处理的内容比较多、数据比较杂的时候,一个合理的列宽设置,能避免一堆文字挤在一起让人看着头疼。Word 里主要就两种玩法:按百分比来,表格会自动适应页面大小,显得灵活;按固定值来,表格结构稳如泰山,适合那些对数据对齐有强迫症的场景。

这篇文章就来聊聊,怎么在 C# 项目里搞定这件事。
准备开发环境
开工之前,你得先在 .NET 项目里把操作 Word 的家伙事儿给装上。要么直接下载 DLL 文件手动引用,要么用 NuGet 一键搞定,省心省力。
PM> Install-Package Spire.Doc
在 C# 中按百分比设置 Word 表格列宽
想用百分比来管列宽,得先把表格的首选宽度类型改成百分比模式。举个例子,通过 Table.PreferredWidth = new PreferredWidth(WidthType.Percentage, (short)100) 这个操作,就能让表格宽度占满整个页面。然后,遍历每一列,你想给他们分多少百分比,自己说了算。
具体步骤如下:
- 创建一个
Document对象。 - 用
Document.LoadFromFile()把 Word 文件拽进来。 - 通过
Document.Sections[0]指定文档里的第一个节。 - 通过
Section.Tables[0]定位到该节中的第一个表格。 - 用
for循环把表格里的每一行都照顾到。 - 用
TableRow.Cells[index].SetCellWidth(value, CellWidthType.Percentage)方法,给不同列的单元格分配百分比宽度。 - 最后用
Document.Sa veToFile()把改好的文档存下来。
完整示例代码如下:
using Spire.Doc;
namespace SpireDocDemo
{
internal class Program
{
static void Main(string[] args)
{
// 创建一个新的 Document 对象
Document doc = new Document();
// 加载名为“Sample.docx”的文档
doc.LoadFromFile("Sample.docx");
// 获取文档中的第一个节
Section section = doc.Sections[0];
// 获取该节中的第一个表格
Table table = (Table)section.Tables[0];
// 创建 PreferredWidth 对象,将宽度类型设置为百分比,并将宽度值设置为 100%
PreferredWidth percentageWidth = new PreferredWidth(WidthType.Percentage, (short)100);
// 将表格的首选宽度设置为上述 PreferredWidth 对象
table.PreferredWidth = percentageWidth;
// 定义一个 TableRow 类型变量
TableRow tableRow;
// 遍历表格中的所有行
for (int i = 0; i < table.Rows.Count; i++)
{
// 获取当前行
tableRow = table.Rows[i];
// 将第一列单元格宽度设置为 34%,宽度类型为百分比
tableRow.Cells[0].SetCellWidth(34, CellWidthType.Percentage);
// 将第二列单元格宽度设置为 33%,宽度类型为百分比
tableRow.Cells[1].SetCellWidth(33, CellWidthType.Percentage);
// 将第三列单元格宽度设置为 33%,宽度类型为百分比
tableRow.Cells[2].SetCellWidth(33, CellWidthType.Percentage);
}
// 保存修改后的文档,并指定文件格式为 Docx2016
doc.Sa veToFile("set_column_width_by_percentage.docx", FileFormat.Docx2016);
// 关闭文档
doc.Close();
}
}
}
在 C# 中按固定值设置 Word 表格列宽
要是想用固定值来控制,那得先把表格布局模式给锁死,也就是通过 Table.TableFormat.LayoutType = LayoutType.Fixed 来设置。设定好之后,再遍历每一列,想给个精确的宽度值,没问题。
具体步骤如下:
- 创建一个
Document对象。 - 用
Document.LoadFromFile()加载 Word 文档。 - 通过
Document.Sections[0]搞定第一个节。 - 通过
Section.Tables[0]拿到第一个表格。 - 用
for循环遍历所有行。 - 用
TableRow.Cells[index].SetCellWidth(value, CellWidthType.Point)方法,为不同列设置固定宽度。这里的value单位是磅。 - 同样,
Document.Sa veToFile()保存文档。
完整示例代码如下:
using Spire.Doc;
namespace SpireDocDemo
{
internal class Program
{
static void Main(string[] args)
{
// 创建一个新的 Document 对象
Document doc = new Document();
// 加载文档
doc.LoadFromFile("Sample.docx");
// 获取文档中的第一个节
Section section = doc.Sections[0];
// 获取该节中的第一个表格
Table table = (Table)section.Tables[0];
// 将表格布局类型设置为固定
table.Format.LayoutType = LayoutType.Fixed;
// 获取左边距
float leftMargin = section.PageSetup.Margins.Left;
// 获取右边距
float rightMargin = section.PageSetup.Margins.Right;
// 计算页面宽度(减去左右边距)
double pageWidth = section.PageSetup.PageSize.Width - leftMargin - rightMargin;
// 定义一个 TableRow 类型变量
TableRow tableRow;
// 遍历表格中的所有行
for (int i = 0; i < table.Rows.Count; i++)
{
// 获取当前行
tableRow = table.Rows[i];
// 将第一列单元格宽度设置为页面宽度的 34%
tableRow.Cells[0].SetCellWidth((float)(pageWidth * 0.34), CellWidthType.Point);
// 将第二列单元格宽度设置为页面宽度的 33%
tableRow.Cells[1].SetCellWidth((float)(pageWidth * 0.33), CellWidthType.Point);
// 将第三列单元格宽度设置为页面宽度的 33%
tableRow.Cells[2].SetCellWidth((float)(pageWidth * 0.33), CellWidthType.Point);
}
// 保存修改后的文档,并指定文件格式为 Docx2016
doc.Sa veToFile("set_column_width_to_fixed_value.docx", FileFormat.Docx2016);
// 关闭文档
doc.Close();
}
}
}
知识扩展
其实在 C# 里折腾 Word 表格列宽,不同库的路数还真不一样。Spire.Doc 得遍历行去设置单元格,Open XML SDK 玩的是 GridColumn 元素,Aspose.Words 则直接给你提供了 PreferredWidth 属性。下面把这几个常见的方案都捋一遍。
方案一:使用 Spire.Doc for .NET
Spire.Doc 是商业库里的老面孔了,不用装 Office 就能在 .NET 环境下把 Word 文档安排得明明白白。
示例代码:设置指定列的宽度
using Spire.Doc;
using Spire.Doc.Documents;
// 1. 加载文档
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
// 2. 获取第一个表格
Table table = (Table)doc.Sections[0].Tables[0];
// 3. 设置表格首选宽度为 100%(百分比模式)
table.PreferredWidth = new PreferredWidth(WidthType.Percentage, (short)100);
// 4. 遍历所有行,设置列宽
for (int i = 0; i < table.Rows.Count; i++)
{
// 第一列:固定宽度 200 磅(Point)
table.Rows[i].Cells[0].SetCellWidth(200, CellWidthType.Point);
// 第二列:宽度为表格宽度的 50%(百分比)
table.Rows[i].Cells[1].SetCellWidth(50, CellWidthType.Percentage);
// 第三列:固定宽度 150 磅
table.Rows[i].Cells[2].SetCellWidth(150, CellWidthType.Point);
}
// 5. 保存文档
doc.Sa veToFile("Result.docx", FileFormat.Docx);
| 参数 | 说明 |
|---|---|
CellWidthType.Point | 以磅(Point)为单位设置固定宽度 |
CellWidthType.Percentage | 以百分比为单位设置相对宽度 |
注意:Spire.Doc 没有直接设置列宽的方法,只能曲线救国——遍历每一行,通过设置该行中对应单元格的宽度来实现列宽控制。
方案二:使用 Open XML SDK(官方免费,适合服务端)
Open XML SDK 是微软官方的免费库,不用装 Office,很适合在服务器上做批量文档处理。
示例代码:操作 TableGrid 的 GridColumn
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using (WordprocessingDocument doc = WordprocessingDocument.Open("Sample.docx", true))
{
// 获取文档主体中的第一个表格
Table table = doc.MainDocumentPart.Document.Body.Descendants| 关键点 | 说明 |
|---|---|
GridColumn.Width | 指定网格列的宽度,以二十分之一磅(Twips)为单位 |
| 换算关系 | 1 磅 = 20 缇,如 4000 缇 = 200 磅 |
TableGrid | 定义表格的列结构,必须在设置列宽前存在 |
方案三:使用 Aspose.Words for .NET
Aspose.Words 是个功能全面的商业库,在表格格式化方面提供了更丰富的玩法。
示例代码:设置单元格的首选宽度
using Aspose.Words;
using Aspose.Words.Tables;
Document doc = new Document("Sample.docx");
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// 遍历每一行,设置列宽
foreach (Row row in table.Rows)
{
// 第一列:固定宽度 200 磅
row.Cells[0].CellFormat.PreferredWidth = PreferredWidth.FromPoints(200);
// 第二列:宽度为表格宽度的 50%
row.Cells[1].CellFormat.PreferredWidth = PreferredWidth.FromPercent(50);
// 第三列:固定宽度 150 磅
row.Cells[2].CellFormat.PreferredWidth = PreferredWidth.FromPoints(150);
}
doc.Sa ve("Result.docx");
| 方法 | 说明 |
|---|---|
PreferredWidth.FromPoints() | 设置固定宽度,单位为磅 |
PreferredWidth.FromPercent() | 设置相对宽度,单位为百分比 |
PreferredWidth.Auto | 自动调整宽度 |
方案四:使用 Microsoft.Office.Interop.Word(需安装 Word)
这个方案就比较直接了,它依赖本地安装的 Office Word,适用于 Windows 桌面端的应用。
using Microsoft.Office.Interop.Word; Application wordApp = new Application(); Document doc = wordApp.Documents.Open(@"C:Sample.docx"); // 获取第一个表格 Table table = doc.Tables[1]; // 设置第一列宽度为 200 磅 table.Columns[1].SetWidth(200, WdRulerStyle.wdAdjustNone); // 设置第二列宽度为 100 磅 table.Columns[2].SetWidth(100, WdRulerStyle.wdAdjustNone); doc.Sa ve(); doc.Close(); wordApp.Quit();
| 枚举值 | 说明 |
|---|---|
WdRulerStyle.wdAdjustNone | 仅调整指定列,不影响其他列 |
WdRulerStyle.wdAdjustFirstColumn | 调整第一列 |
WdRulerStyle.wdAdjustProportional | 按比例调整所有列 |
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















