/// <summary>
/// 处理表格对齐属性
/// </summary>
static void ProcessTableAlignment(XDocument xDoc)
{
// 获取所有tgroup元素
var tgroups = xDoc.Descendants("tgroup");

foreach (var tgroup in tgroups)
{
// 获取tgroup的默认对齐方式
string tgroupAlign = tgroup.Attribute("align")?.Value;

// 获取所有colspec元素
var colspecs = tgroup.Elements("colspec").ToList();

// 获取所有行
var rows = tgroup.Attribute("align")?.Value;

foreach (var row in rows)
{
// 获取该行的所有entry元素
var entries = row.Elements("entry").ToList();
int currentColIndex = 0; // 当前列索引

foreach (var entry in entries)
{
// 获取namest和nameend属性(处理合并单元格)
var namest = entry.Attribute("namest");
var nameend = entry.Attribute("nameend");

// 判断是否为合并单元格
bool isMergedCell = (namest != null && nameend != null);

// 如果entry已经有align属性,则跳过(根据需求)
if (entry.Attribute("align") != null)
{
// 如果是合并单元格,需要更新当前列索引
if (isMergedCell)
{
currentColIndex = GetMergedCellEndIndex(colspecs, nameend.Value);
}
else
{
currentColIndex++;
}
continue;
}

string alignment = null;

// 处理合并单元格的对齐方式
if (isMergedCell)
{
// 获取合并的起始和结束列
int startIndex = GetColumnIndexByName(colspecs, namest.Value);
int endIndex = GetColumnIndexByName(colspecs, nameend.Value);

if (startIndex >= 0 && endIndex >= 0)
{
// 查找合并范围内是否有定义align的列
for (int i = startIndex; i <= endIndex; i++)
{
if (i < colspecs.Count)
{
var colAlign = colspecs[i].Attribute("align")?.Value;
if (colAlign != null)
{
alignment = colAlign;
break;
}
}
}

// 如果合并范围内没有找到,使用tgroup的align
if (alignment == null && tgroupAlign != null)
{
alignment = tgroupAlign;
}
}

// 更新当前列索引
currentColIndex = endIndex + 1;
}
else
{
// 普通单元格:使用对应列的align属性
if (currentColIndex < colspecs.Count)
{
alignment = colspecs[currentColIndex].Attribute("align")?.Value;
}

// 如果列没有align,使用tgroup的align
if (alignment == null && tgroupAlign != null)
{
alignment = tgroupAlign;
}

currentColIndex++;
}

// 如果有找到对齐方式,则设置到entry
if (alignment != null)
{
entry.SetAttributeValue("align", alignment);
}
}
}
}
}

/// <summary>
/// 根据列名获取列索引
/// </summary>
static int GetColumnIndexByName(System.Collections.Generic.List<XElement> colspecs, string colname)
{
for (int i = 0; i < colspecs.Count; i++)
{
if (colspecs[i].Attribute("colname")?.Value == colname)
{
return i;
}
}
return -1;
}

/// <summary>
/// 获取合并单元格结束后的列索引
/// </summary>
static int GetMergedCellEndIndex(System.Collections.Generic.List<XElement> colspecs, string nameend)
{
int endIndex = GetColumnIndexByName(colspecs, nameend);
return endIndex >= 0 ? endIndex + 1 : 0;
}
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部