【问题标题】:How can I create a style with borders from VSTO code?如何从 VSTO 代码创建带有边框的样式?
【发布时间】:2015-05-13 09:18:10
【问题描述】:

我正在使用 VSTO 在 C# 中开发 Excel 插件。在这个插件中,我创建了一些样式并将它们添加到当前工作簿中。一切正常,直到我尝试为我的风格设置一些边界。

这是我使用的代码:

var style = workbook.styles.Add("My style");

style.IncludeAlignment = false;
style.IncludeFont = false;
style.IncludeNumber = false;
style.IncludeProtection = false;
style.IncludePatterns = false;

style.IncludeBorder = true;
foreach (XlBordersIndex borderIndex in new[] { 
                XlBordersIndex.xlEdgeLeft, 
                XlBordersIndex.xlEdgeRight, 
                XlBordersIndex.xlEdgeTop, 
                XlBordersIndex.xlEdgeBottom })
{
    style.Borders[borderIndex].LineStyle = XlLineStyle.xlContinuous;
}

我希望这段代码创建一个设置了四个边框的样式,但似乎只设置了左边缘(我可以通过在循环后从调试器中查看样式对象,并在 Excel 中通过编辑“我的风格”)。

我尝试录制一个 VBA 宏来查看 Excel 生成的代码,我得到了这个:

ActiveWorkbook.Styles.Add Name:="My style"
With ActiveWorkbook.Styles("My style")
    .IncludeNumber = False
    .IncludeFont = False
    .IncludeAlignment = False
    .IncludeBorder = True
    .IncludePatterns = False
    .IncludeProtection = False
End With
With ActiveWorkbook.Styles("My style").Borders(xlLeft)
    .LineStyle = xlContinuous
    .TintAndShade = 0
    .Weight = xlThin
End With
With ActiveWorkbook.Styles("My style").Borders(xlRight)
    .LineStyle = xlContinuous
    .TintAndShade = 0
    .Weight = xlThin
End With
With ActiveWorkbook.Styles("My style").Borders(xlTop)
    .LineStyle = xlContinuous
    .TintAndShade = 0
    .Weight = xlThin
End With
With ActiveWorkbook.Styles("My style").Borders(xlBottom)
    .LineStyle = xlContinuous
    .TintAndShade = 0
    .Weight = xlThin
End With

此宏按预期工作。我注意到它使用xlTopxlLeft 等而不是xlEdgeTopxlEdgeLeft,但我找不到关于这些常量的任何文档,并且它们在VSTO 枚举XlBordersIndex 中不可用。根据我的发现,似乎后者代表范围的边缘,而前者代表每个单元格的边缘,但我不确定这一点,我认为在谈论样式时差异没有多大意义,这适用于单细胞 AFAICT。

为什么我的 C# 插件和这个 VBA 宏的行为不同?如何从我的 VSTO 代码创建带边框的样式?

【问题讨论】:

标签: c# excel vsto


【解决方案1】:

根据this discussion,看起来样式的边框和范围的边框是有区别的:后者被XlBordersIndex索引(xlEdgeTopxlEdgeLeft,...) , 如the documentation 所述,但前者由Constants (xlTop, xlLeft,...) 索引。

如果我们认为样式适用于单个单元格而不是范围,这可能是有意义的,但这也意味着要访问样式边框,我们必须使用不相关的常量绕过Borders 接口的接口。 AnushRudaa here 提出的这种解决方法似乎有效:

foreach (XlBordersIndex borderIndex in new[] { 
                (XlBordersIndex)Constants.xlLeft, 
                (XlBordersIndex)Constants.xlRight, 
                (XlBordersIndex)Constants.xlTop, 
                (XlBordersIndex)Constants.xlBottom })
{
    style.Borders[borderIndex].LineStyle = XlLineStyle.xlContinuous;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 2016-02-26
    • 1970-01-01
    • 2014-05-05
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多