You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在.NET中用OpenXML和ASP.NET导出DataTable到Excel时边框设置异常

问题分析与修复

你的代码核心问题在于直接修改共享的CellFormat实例:当多个单元格(甚至不同表格的单元格)共用同一个样式索引时,修改该索引对应的CellFormat会影响所有使用该样式的单元格,导致两个表格的边框样式互相覆盖,无法同时生效。

修复后的代码

private void ApplyBorders(Row row, Stylesheet stylesheet, uint styleIndex)
{
    foreach (Cell cell in row.Elements<Cell>())
    {
        if (cell.StyleIndex != null)
        {
            int styleIndexValue = (int)cell.StyleIndex.Value;
            if (styleIndexValue < stylesheet.CellFormats.Count)
            {
                // 获取原样式,基于原样式创建新格式(避免修改共享实例)
                CellFormat originalFormat = (CellFormat)stylesheet.CellFormats.ElementAt(styleIndexValue);
                CellFormat newFormat = new CellFormat(originalFormat.ChildElements)
                {
                    BorderId = styleIndex,
                    ApplyBorder = true,
                    // 保留原样式的其他属性(字体、填充、数字格式等)
                    FontId = originalFormat.FontId,
                    FillId = originalFormat.FillId,
                    NumberFormatId = originalFormat.NumberFormatId,
                    ApplyFont = originalFormat.ApplyFont,
                    ApplyFill = originalFormat.ApplyFill,
                    ApplyNumberFormat = originalFormat.ApplyNumberFormat
                };

                stylesheet.CellFormats.Append(newFormat);
                // 更新当前单元格的样式索引为新格式的索引
                cell.StyleIndex = (uint)stylesheet.CellFormats.Count - 1;
            }
        }
        else
        {
            // 无现有样式时,直接创建带边框的新格式
            CellFormat cellFormat = new CellFormat { BorderId = styleIndex, ApplyBorder = true };
            stylesheet.CellFormats.Append(cellFormat);
            cell.StyleIndex = (uint)stylesheet.CellFormats.Count - 1;
        }
    }
}

额外注意事项

  • 确保你已正确创建Border对象并添加到stylesheet.Borders集合中,styleIndex必须对应该Border在集合中的索引(从0开始)。
  • 处理完所有表格后,手动更新CellFormats的计数,避免OpenXML解析异常:
    stylesheet.CellFormats.Count = (uint)stylesheet.CellFormats.Elements<CellFormat>().Count();
    
  • 导出工作簿时,确保样式表已正确关联到WorkbookStylesPart。

内容的提问来源于stack exchange,提问作者Om Chowkule

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 00:32:35