row.Cells[0].CellFormat.Width():统一使用遍历每行单元格来设置对应的单元格宽度

#region 宽度赋值
foreach (Aspose.Words.Tables.Row row in tableNow.Rows)
{
      row.Cells[0].CellFormat.Width = 80;
      row.Cells[1].CellFormat.Width = 60;
      row.Cells[2].CellFormat.Width = 70;
      row.Cells[3].CellFormat.Width = 105;
      row.Cells[4].CellFormat.Width = 70;
      row.Cells[5].CellFormat.Width = 70;
      row.Cells[6].CellFormat.Width = 115;
}
#endregion

优点就是比较集中,方便设置修改。但是在表格构造完后会出现问题就是无论怎么调整width的数值,表格的整体长度是不变的,只是单元格比例的变化(设置数值占数值总和的比例)

builder.CellFormat.Width():在创建单元格时设置宽度

builder.InsertCell();
builder.CellFormat.Width = 80;
builder.Write("检测项目");
builder.InsertCell();
builder.CellFormat.Width = 60;
builder.Write("单位");
builder.InsertCell();
builder.CellFormat.Width = 70;
builder.Write("检测结果");
builder.InsertCell();
builder.CellFormat.Width = 105;
builder.Write("检测依据");
builder.InsertCell();
builder.CellFormat.Width = 70;
builder.Write("标准要求");
builder.InsertCell();
builder.CellFormat.Width = 70;
builder.Write("单项判定");
builder.InsertCell();
builder.CellFormat.Width = 115;
builder.Write("判断依据");
builder.EndRow();

这样设置的单元格宽度才会随数值变化而变化,但是就是不够统一,不美观也不方便修改。

row.Cells[0].CellFormat.Width()为什么会出现这种问题?

在Aspose.Words中,表格的布局行为取决于:

  1. 表格的自动调整设置Table.AllowAutoFit

  2. 设置宽度的时机 - 在创建时设置 vs 创建后设置

  3. 表格的布局算法 - 默认会按比例分配剩余空间

为什么builder.InsertCell()能成功?

因为在使用DocumentBuilder创建单元格时:

  • 宽度设置是立即生效

  • 表格布局算法会尊重创建时的设置

  • 没有后续的自动调整干扰

所以想要构建表后使用row.Cells[0].CellFormat.Width()来设置单元格宽度有两种方法:

方案1:禁用表格自动调整(推荐)
// 在设置宽度之前,禁用表格的自动调整
tableNow.AllowAutoFit = false;

#region 宽度赋值
foreach (Aspose.Words.Tables.Row row in tableNow.Rows)
{
      row.Cells[0].CellFormat.Width = 80;
      row.Cells[1].CellFormat.Width = 60;
      row.Cells[2].CellFormat.Width = 70;
      row.Cells[3].CellFormat.Width = 105;
      row.Cells[4].CellFormat.Width = 70;
      row.Cells[5].CellFormat.Width = 70;
      row.Cells[6].CellFormat.Width = 115;
}
#endregion
方案2:设置表格首选宽度
//设置表格的首选宽度
tableNow.PreferredWidth = PreferredWidth.FromPoints(570); // 首选宽度,根据总宽度调整,没有设置就会导致只会按下面比例生成不可控的宽度

#region 宽度赋值
foreach (Aspose.Words.Tables.Row row in tableNow.Rows)
{
      row.Cells[0].CellFormat.Width = 80;
      row.Cells[1].CellFormat.Width = 60;
      row.Cells[2].CellFormat.Width = 70;
      row.Cells[3].CellFormat.Width = 105;
      row.Cells[4].CellFormat.Width = 70;
      row.Cells[5].CellFormat.Width = 70;
      row.Cells[6].CellFormat.Width = 115;
}
#endregion

结果如图:

更多推荐