最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#代碼實(shí)現(xiàn)設(shè)置Word表格的列寬

 更新時(shí)間:2026年06月17日 11:52:28   作者:2501_93070778  
設(shè)置 Word 表格的列寬對(duì)于提升文檔的可讀性和整體美觀度至關(guān)重要,本文將介紹如何在 C# 項(xiàng)目中用代碼設(shè)置 Word 表格的列寬,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

設(shè)置 Word 表格的列寬對(duì)于提升文檔的可讀性和整體美觀度至關(guān)重要。合理的列寬能夠避免文本過(guò)長(zhǎng)導(dǎo)致閱讀困難,尤其是在內(nèi)容較多的表格中。Word 提供了兩種常見(jiàn)的列寬設(shè)置方式:按百分比設(shè)置和按固定值設(shè)置。

使用百分比設(shè)置列寬時(shí),表格能夠根據(jù)頁(yè)面或窗口大小自動(dòng)調(diào)整布局,使內(nèi)容保持整齊排列,從而提升閱讀體驗(yàn)。而使用固定值設(shè)置列寬,則可以更精確地控制表格結(jié)構(gòu),確保版式一致性和專業(yè)性,特別適用于對(duì)數(shù)據(jù)對(duì)齊要求較高或布局較為復(fù)雜的文檔。

本文將介紹如何在 C# 項(xiàng)目中設(shè)置 Word 表格的列寬。

準(zhǔn)備開(kāi)發(fā)環(huán)境

在開(kāi)始之前,您需要在 .NET 項(xiàng)目中添加用于操作 Word 文檔的相關(guān)庫(kù)。您可以通過(guò)下載 DLL 文件并添加引用,或直接使用 NuGet 進(jìn)行安裝。

PM> Install-Package Spire.Doc

在 C# 中按百分比設(shè)置 Word 表格列寬

在 Word 表格中使用百分比設(shè)置列寬時(shí),首先需要將表格的首選寬度類型設(shè)置為百分比。例如,可以通過(guò) Table.PreferredWidth = new PreferredWidth(WidthType.Percentage, (short)100) 將表格寬度設(shè)置為頁(yè)面寬度的 100%。隨后,遍歷表格中的各列,并根據(jù)需要為其設(shè)置相同或不同的百分比寬度。

具體步驟如下:

  1. 創(chuàng)建一個(gè) Document 對(duì)象。
  2. 使用 Document.LoadFromFile() 方法加載 Word 文檔。
  3. 通過(guò) Document.Sections[0] 獲取文檔中的第一個(gè)節(jié)。
  4. 通過(guò) Section.Tables[0] 獲取該節(jié)中的第一個(gè)表格。
  5. 使用 for 循環(huán)遍歷表格中的所有行。
  6. 使用 TableRow.Cells[index].SetCellWidth(value, CellWidthType.Percentage) 方法為不同列中的單元格設(shè)置百分比列寬。
  7. 使用 Document.SaveToFile() 方法保存修改后的 Word 文檔。

完整示例代碼如下:

using Spire.Doc;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 創(chuàng)建一個(gè)新的 Document 對(duì)象
            Document doc = new Document();

            // 加載名為“Sample.docx”的文檔
            doc.LoadFromFile("Sample.docx");

            // 獲取文檔中的第一個(gè)節(jié)
            Section section = doc.Sections[0];

            // 獲取該節(jié)中的第一個(gè)表格
            Table table = (Table)section.Tables[0];

            // 創(chuàng)建 PreferredWidth 對(duì)象,將寬度類型設(shè)置為百分比,并將寬度值設(shè)置為 100%
            PreferredWidth percentageWidth = new PreferredWidth(WidthType.Percentage, (short)100);

            // 將表格的首選寬度設(shè)置為上述 PreferredWidth 對(duì)象
            table.PreferredWidth = percentageWidth;

            // 定義一個(gè) TableRow 類型變量
            TableRow tableRow;

            // 遍歷表格中的所有行
            for (int i = 0; i < table.Rows.Count; i++)
            {
                // 獲取當(dāng)前行
                tableRow = table.Rows[i];

                // 將第一列單元格寬度設(shè)置為 34%,寬度類型為百分比
                tableRow.Cells[0].SetCellWidth(34, CellWidthType.Percentage);

                // 將第二列單元格寬度設(shè)置為 33%,寬度類型為百分比
                tableRow.Cells[1].SetCellWidth(33, CellWidthType.Percentage);

                // 將第三列單元格寬度設(shè)置為 33%,寬度類型為百分比
                tableRow.Cells[2].SetCellWidth(33, CellWidthType.Percentage);
            }

            // 保存修改后的文檔,并指定文件格式為 Docx2016
            doc.SaveToFile("set_column_width_by_percentage.docx", FileFormat.Docx2016);

            // 關(guān)閉文檔
            doc.Close();
        }
    }
}

在 C# 中按固定值設(shè)置 Word 表格列寬

在 Word 表格中使用固定值設(shè)置列寬時(shí),首先需要將表格布局設(shè)置為固定模式,即通過(guò) Table.TableFormat.LayoutType = LayoutType.Fixed 進(jìn)行設(shè)置。隨后,遍歷表格中的各列,并根據(jù)需要為其設(shè)置相同或不同的固定寬度值。

具體步驟如下:

  1. 創(chuàng)建一個(gè) Document 對(duì)象。
  2. 使用 Document.LoadFromFile() 方法加載 Word 文檔。
  3. 通過(guò) Document.Sections[0] 獲取文檔中的第一個(gè)節(jié)。
  4. 通過(guò) Section.Tables[0] 獲取該節(jié)中的第一個(gè)表格。
  5. 使用 for 循環(huán)遍歷表格中的所有行。
  6. 使用 TableRow.Cells[index].SetCellWidth(value, CellWidthType.Point) 方法為不同列中的單元格設(shè)置固定列寬。其中,value 需要替換為所需的寬度值(單位為磅)。
  7. 使用 Document.SaveToFile() 方法保存修改后的 Word 文檔。

完整示例代碼如下:

using Spire.Doc;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 創(chuàng)建一個(gè)新的 Document 對(duì)象
            Document doc = new Document();

            // 加載文檔
            doc.LoadFromFile("Sample.docx");

            // 獲取文檔中的第一個(gè)節(jié)
            Section section = doc.Sections[0];

            // 獲取該節(jié)中的第一個(gè)表格
            Table table = (Table)section.Tables[0];

            // 將表格布局類型設(shè)置為固定
            table.Format.LayoutType = LayoutType.Fixed;

            // 獲取左邊距
            float leftMargin = section.PageSetup.Margins.Left;

            // 獲取右邊距
            float rightMargin = section.PageSetup.Margins.Right;

            // 計(jì)算頁(yè)面寬度(減去左右邊距)
            double pageWidth = section.PageSetup.PageSize.Width - leftMargin - rightMargin;

            // 定義一個(gè) TableRow 類型變量
            TableRow tableRow;

            // 遍歷表格中的所有行
            for (int i = 0; i < table.Rows.Count; i++)
            {
                // 獲取當(dāng)前行
                tableRow = table.Rows[i];

                // 將第一列單元格寬度設(shè)置為頁(yè)面寬度的 34%
                tableRow.Cells[0].SetCellWidth((float)(pageWidth * 0.34), CellWidthType.Point);

                // 將第二列單元格寬度設(shè)置為頁(yè)面寬度的 33%
                tableRow.Cells[1].SetCellWidth((float)(pageWidth * 0.33), CellWidthType.Point);

                // 將第三列單元格寬度設(shè)置為頁(yè)面寬度的 33%
                tableRow.Cells[2].SetCellWidth((float)(pageWidth * 0.33), CellWidthType.Point);
            }

            // 保存修改后的文檔,并指定文件格式為 Docx2016
            doc.SaveToFile("set_column_width_to_fixed_value.docx", FileFormat.Docx2016);

            // 關(guān)閉文檔
            doc.Close();
        }
    }
}

知識(shí)擴(kuò)展

在 C# 中設(shè)置 Word 表格列寬,根據(jù)使用的庫(kù)不同,實(shí)現(xiàn)方式也有所差異。Spire.Doc 通過(guò)遍歷行設(shè)置單元格寬度,Open XML SDK 操作 GridColumn 元素,Aspose.Words 則提供了 PreferredWidth 屬性。

方案一:使用 Spire.Doc for .NET

Spire.Doc 是操作 Word 文檔的主流商業(yè)庫(kù)之一,無(wú)需安裝 Microsoft Office 即可在 .NET 環(huán)境下高效處理 Word 文檔。

安裝:

PM> Install-Package Spire.Doc

示例代碼:設(shè)置指定列的寬度

using Spire.Doc;
using Spire.Doc.Documents;
// 1. 加載文檔
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
// 2. 獲取第一個(gè)表格
Table table = (Table)doc.Sections[0].Tables[0];
// 3. 設(shè)置表格首選寬度為 100%(百分比模式)
table.PreferredWidth = new PreferredWidth(WidthType.Percentage, (short)100);
// 4. 遍歷所有行,設(shè)置列寬[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);
參數(shù)說(shuō)明
CellWidthType.Point磅(Point)為單位設(shè)置固定寬度
CellWidthType.Percentage百分比為單位設(shè)置相對(duì)寬度

注意:Spire.Doc 沒(méi)有直接設(shè)置列寬的方法,需要遍歷表格的每一行,通過(guò)設(shè)置該行中對(duì)應(yīng)單元格的寬度來(lái)實(shí)現(xiàn)列寬控制。

方案二:使用 Open XML SDK(官方免費(fèi),適合服務(wù)端)

Open XML SDK 是微軟官方提供的庫(kù),無(wú)需安裝 Office,適合在服務(wù)端進(jìn)行批量文檔處理。

安裝:

PM> Install-Package DocumentFormat.OpenXml

示例代碼:操作 TableGrid 的 GridColumn

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using (WordprocessingDocument doc = WordprocessingDocument.Open("Sample.docx", true))
{
    // 獲取文檔主體中的第一個(gè)表格
    Table table = doc.MainDocumentPart.Document.Body.Descendants<Table>().First();
    // 獲取或創(chuàng)建表格網(wǎng)格(TableGrid)
    TableGrid tableGrid = table.GetFirstChild<TableGrid>();
    if (tableGrid == null)
    {
        tableGrid = new TableGrid();
        table.InsertAt(tableGrid, 0);
    }
    // 清空現(xiàn)有網(wǎng)格列
    tableGrid.RemoveAllChildren();
    // 定義各列寬度(單位:緹,1 磅 = 20 緹)
    int[] columnWidthsInTwips = new int[] { 4000, 2000, 3000 }; // 分別對(duì)應(yīng) 200、100、150 磅
    foreach (int width in columnWidthsInTwips)
    {
        tableGrid.AppendChild(new GridColumn() { Width = width.ToString() });
    }
    doc.Save();
}
關(guān)鍵點(diǎn)說(shuō)明
GridColumn.Width指定網(wǎng)格列的寬度,以二十分之一磅(Twips)為單位
換算關(guān)系1 磅 = 20 緹,如 4000 緹 = 200 磅
TableGrid定義表格的列結(jié)構(gòu),必須在設(shè)置列寬前存在

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

Aspose.Words 是功能全面的商業(yè) Word 操作庫(kù),提供了更豐富的表格格式化能力。

安裝:

PM> Install-Package Aspose.Words

示例代碼:設(shè)置單元格的首選寬度

using Aspose.Words;
using Aspose.Words.Tables;
Document doc = new Document("Sample.docx");
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// 遍歷每一行,設(shè)置列寬[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");
方法說(shuō)明
PreferredWidth.FromPoints()設(shè)置固定寬度,單位為
PreferredWidth.FromPercent()設(shè)置相對(duì)寬度,單位為百分比
PreferredWidth.Auto自動(dòng)調(diào)整寬度

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

此方案依賴本地安裝的 Microsoft Office Word,適合 Windows 桌面端應(yīng)用。

using Microsoft.Office.Interop.Word;
Application wordApp = new Application();
Document doc = wordApp.Documents.Open(@"C:\Sample.docx");
// 獲取第一個(gè)表格
Table table = doc.Tables[1];
// 設(shè)置第一列寬度為 200 磅[reference:19]
table.Columns[1].SetWidth(200, WdRulerStyle.wdAdjustNone);
// 設(shè)置第二列寬度為 100 磅
table.Columns[2].SetWidth(100, WdRulerStyle.wdAdjustNone);
doc.Save();
doc.Close();
wordApp.Quit();
枚舉值說(shuō)明
WdRulerStyle.wdAdjustNone僅調(diào)整指定列,不影響其他列
WdRulerStyle.wdAdjustFirstColumn調(diào)整第一列
WdRulerStyle.wdAdjustProportional按比例調(diào)整所有列

到此這篇關(guān)于C#代碼實(shí)現(xiàn)設(shè)置Word表格的列寬的文章就介紹到這了,更多相關(guān)C#設(shè)置Word表格列寬內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

普安县| 芜湖县| 苍山县| 连城县| 建瓯市| 苍山县| 英超| 万山特区| 大姚县| 西盟| 和田县| 谢通门县| 正镶白旗| 南澳县| 海原县| 汪清县| 柳林县| 兴山县| 玉林市| 彭水| 奈曼旗| 天台县| 越西县| 周至县| 美姑县| 澄城县| 澎湖县| 涞源县| 关岭| 彩票| 沙湾县| 永安市| 浮梁县| 巴彦县| 安平县| 吉林省| 启东市| 通榆县| 洪洞县| 唐山市| 新源县|