广告位联系
返回顶部
分享到

C#代码实现设置Word表格的列宽

C语言 来源:互联网 作者:佚名 发布时间:2026-06-17 22:33:09 人浏览
摘要

设置 Word 表格的列宽对于提升文档的可读性和整体美观度至关重要。合理的列宽能够避免文本过长导致阅读困难,尤其是在内容较多的表格中。Word 提供了两种常见的列宽设置方式:按百分比设

设置 Word 表格的列宽对于提升文档的可读性和整体美观度至关重要。合理的列宽能够避免文本过长导致阅读困难,尤其是在内容较多的表格中。Word 提供了两种常见的列宽设置方式:按百分比设置和按固定值设置。

使用百分比设置列宽时,表格能够根据页面或窗口大小自动调整布局,使内容保持整齐排列,从而提升阅读体验。而使用固定值设置列宽,则可以更精确地控制表格结构,确保版式一致性和专业性,特别适用于对数据对齐要求较高或布局较为复杂的文档。

本文将介绍如何在 C# 项目中设置 Word 表格的列宽。

准备开发环境

在开始之前,您需要在 .NET 项目中添加用于操作 Word 文档的相关库。您可以通过下载 DLL 文件并添加引用,或直接使用 NuGet 进行安装。

1

PM> Install-Package Spire.Doc

在 C# 中按百分比设置 Word 表格列宽

在 Word 表格中使用百分比设置列宽时,首先需要将表格的首选宽度类型设置为百分比。例如,可以通过 Table.PreferredWidth = new PreferredWidth(WidthType.Percentage, (short)100) 将表格宽度设置为页面宽度的 100%。随后,遍历表格中的各列,并根据需要为其设置相同或不同的百分比宽度。

具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.LoadFromFile() 方法加载 Word 文档。
  3. 通过 Document.Sections[0] 获取文档中的第一个节。
  4. 通过 Section.Tables[0] 获取该节中的第一个表格。
  5. 使用 for 循环遍历表格中的所有行。
  6. 使用 TableRow.Cells[index].SetCellWidth(value, CellWidthType.Percentage) 方法为不同列中的单元格设置百分比列宽。
  7. 使用 Document.SaveToFile() 方法保存修改后的 Word 文档。

完整示例代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

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.SaveToFile("set_column_width_by_percentage.docx", FileFormat.Docx2016);

 

            // 关闭文档

            doc.Close();

        }

    }

}

在 C# 中按固定值设置 Word 表格列宽

在 Word 表格中使用固定值设置列宽时,首先需要将表格布局设置为固定模式,即通过 Table.TableFormat.LayoutType = LayoutType.Fixed 进行设置。随后,遍历表格中的各列,并根据需要为其设置相同或不同的固定宽度值。

具体步骤如下:

  1. 创建一个 Document 对象。
  2. 使用 Document.LoadFromFile() 方法加载 Word 文档。
  3. 通过 Document.Sections[0] 获取文档中的第一个节。
  4. 通过 Section.Tables[0] 获取该节中的第一个表格。
  5. 使用 for 循环遍历表格中的所有行。
  6. 使用 TableRow.Cells[index].SetCellWidth(value, CellWidthType.Point) 方法为不同列中的单元格设置固定列宽。其中,value 需要替换为所需的宽度值(单位为磅)。
  7. 使用 Document.SaveToFile() 方法保存修改后的 Word 文档。

完整示例代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

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.SaveToFile("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 是操作 Word 文档的主流商业库之一,无需安装 Microsoft Office 即可在 .NET 环境下高效处理 Word 文档。

安装:

1

PM> Install-Package Spire.Doc

示例代码:设置指定列的宽度

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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. 遍历所有行,设置列宽[reference:5]

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.SaveToFile("Result.docx", FileFormat.Docx);

参数 说明
CellWidthType.Point 以磅(Point)为单位设置固定宽度
CellWidthType.Percentage 以百分比为单位设置相对宽度

注意:Spire.Doc 没有直接设置列宽的方法,需要遍历表格的每一行,通过设置该行中对应单元格的宽度来实现列宽控制。

方案二:使用 Open XML SDK(官方免费,适合服务端)

Open XML SDK 是微软官方提供的库,无需安装 Office,适合在服务端进行批量文档处理。

安装:

1

PM> Install-Package DocumentFormat.OpenXml

示例代码:操作 TableGrid 的 GridColumn

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

using DocumentFormat.OpenXml.Packaging;

using DocumentFormat.OpenXml.Wordprocessing;

using (WordprocessingDocument doc = WordprocessingDocument.Open("Sample.docx", true))

{

    // 获取文档主体中的第一个表格

    Table table = doc.MainDocumentPart.Document.Body.Descendants<Table>().First();

    // 获取或创建表格网格(TableGrid)

    TableGrid tableGrid = table.GetFirstChild<TableGrid>();

    if (tableGrid == null)

    {

        tableGrid = new TableGrid();

        table.InsertAt(tableGrid, 0);

    }

    // 清空现有网格列

    tableGrid.RemoveAllChildren();

    // 定义各列宽度(单位:缇,1 磅 = 20 缇)

    int[] columnWidthsInTwips = new int[] { 4000, 2000, 3000 }; // 分别对应 200、100、150 磅

    foreach (int width in columnWidthsInTwips)

    {

        tableGrid.AppendChild(new GridColumn() { Width = width.ToString() });

    }

    doc.Save();

}

关键点 说明
GridColumn.Width 指定网格列的宽度,以二十分之一磅(Twips)为单位
换算关系 1 磅 = 20 缇,如 4000 缇 = 200 磅
TableGrid 定义表格的列结构,必须在设置列宽前存在

方案三:使用 Aspose.Words for .NET

Aspose.Words 是功能全面的商业 Word 操作库,提供了更丰富的表格格式化能力。

安装:

1

PM> Install-Package Aspose.Words

示例代码:设置单元格的首选宽度

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

using Aspose.Words;

using Aspose.Words.Tables;

Document doc = new Document("Sample.docx");

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// 遍历每一行,设置列宽[reference:15]

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.Save("Result.docx");

方法 说明
PreferredWidth.FromPoints() 设置固定宽度,单位为磅
PreferredWidth.FromPercent() 设置相对宽度,单位为百分比
PreferredWidth.Auto 自动调整宽度

方案四:使用 Microsoft.Office.Interop.Word(需安装 Word)

此方案依赖本地安装的 Microsoft Office Word,适合 Windows 桌面端应用。

1

2

3

4

5

6

7

8

9

10

11

12

using Microsoft.Office.Interop.Word;

Application wordApp = new Application();

Document doc = wordApp.Documents.Open(@"C:\Sample.docx");

// 获取第一个表格

Table table = doc.Tables[1];

// 设置第一列宽度为 200 磅[reference:19]

table.Columns[1].SetWidth(200, WdRulerStyle.wdAdjustNone);

// 设置第二列宽度为 100 磅

table.Columns[2].SetWidth(100, WdRulerStyle.wdAdjustNone);

doc.Save();

doc.Close();

wordApp.Quit();

枚举值 说明
WdRulerStyle.wdAdjustNone 仅调整指定列,不影响其他列
WdRulerStyle.wdAdjustFirstColumn 调整第一列
WdRulerStyle.wdAdjustProportional 按比例调整所有列

版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 :
相关文章
  • C#代码实现设置Word表格的列宽
    设置 Word 表格的列宽对于提升文档的可读性和整体美观度至关重要。合理的列宽能够避免文本过长导致阅读困难,尤其是在内容较多的表格
  • C++中的引用传参和指针传参的区别介绍
    核心概念对比 概念 C++ 前端 (JS/TS) 值传递 默认方式,完整拷贝 基本类型 (number, string等) 引用传递 需显式使用 或指针 对象、数组、函数等引
  • C++中std::functional使用场景
    std::functional 是 C++ 标准库中一个非常强大的工具,它提供了一种**类型擦除(type erasure)**机制,让你能够存储、传递和调用任何可调用对象
  • C++入门指南:零基础入门教学
    学习C++就像学习一门新的语言,需要从字母开始,逐步构建句子和段落。本文就是你的C++字母表。本文介绍了C++编程语言的基本概念和学习
  • C++ io_uring的使用
    io_uring是 Linux 内核在 5.1 版本引入的一套全新的、高性能的异步 I/O (Asynchronous I/O) 接口。它的出现是为了解决旧有的epoll和linux-aio在面对现代
  • C++特有的bool变量使用
    C++中的bool类型 在C++中,bool是一种基本数据类型,专门用于表示布尔值(真或假)。它是C++语言特有的布尔类型,与C语言中使用整数模拟布
  • C++右值引用(rvalue references)与移动语义(move semant
    一、右值引用(rvalue references)与移动语义(move semantics)设计动机 1.1 为什么需要移动语义 传统 C++ 的对象拷贝(copy)在管理资源(堆内存
  • c++日志库log4cplus快速入门

    c++日志库log4cplus快速入门
    log4j 用于Java,log4cplus从它衍生而来,用于c++。 用于c++的日志库还有很多,如 log4cxx等,可以根据实际需求选择使用。 log4cplus 的地址:http
  • 从入门到精通C++11 <chrono> 库特性

    从入门到精通C++11 <chrono> 库特性
    在 C++11 标准中,引入了许多新的库特性,其中chrono库为时间处理提供了强大而灵活的支持。这个库使得在 C++ 中处理时间变得更加方便和精
  • C++ Sort函数使用场景分析

    C++ Sort函数使用场景分析
    C++ Sort函数详解 前言 :sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计