如何使用C#在Excel范围周围添加边框?

时间:2014-10-03 09:22:40

标签: c# excel vsto

有人能告诉我如何在另一种颜色的细胞范围外添加边框吗?理想情况下,我希望能够通过一种方法完成此操作,我将不得不多次这样做。搜索完之后,我找到了两种显然可以做到这一点的方法 - BorderAroundBorderAround2。我想我的第一个问题是这两种方法有什么区别?我尝试过使用其中的每一个,只识别了BorderAround2

无论如何,`BorderAround2'几乎做我想要的。我使用了以下代码行,它确实在范围的外部放置了一个边框,但它是黑色的,而不是红色的:

ws.get_Range("B2", "E3").BorderAround2(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThick, Excel.XlColorIndex.xlColorIndexNone, Color.FromArgb(255, 0, 0), Type.Missing);

此方法的MSDN documentation说明:

  

您必须指定ColorIndex或Color,但不能同时指定两者。

我该怎么做呢?如果我将ColourIndex参数设置为Type.Missingnull或完全错过,则会产生错误。任何帮助将不胜感激。

最后我应该指出,我找到了一个解决方案解决方案here,您可以在其中分别设置各个边缘,但正如我所说,我希望使用单个方法执行此操作,因为必须重复多次。

2 个答案:

答案 0 :(得分:2)

向Excel范围的一个或多个边添加边框(单元格范围,通常可以包含1..many行和1..many列,但对于此特定方案,我们可能希望坚持有一行和1..many列),你只需要做三件事:

0) Define the range
1) Get a reference to the Range's Borders array
2) Assign a border to one or more of the Border array's edges/sides (top, bottom, left, right)

首先,定义您想要操作的范围,如下所示:

var rowToBottomBorderizeRange = _xlSheet.Range[_xlSheet.Cells[rowToBottomBorderize, ITEMDESC_COL], _xlSheet.Cells[rowToBottomBorderize, TOTALS_COL]];

接下来,获取对Range的Borders数组的引用,如下所示:

Borders border = rowToBottomBorderizeRange.Borders;

最后,为一个或多个Border数组的边指定边框;例如,如果要将boder添加到底部,如下所示:

border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;

总而言之,代码可以是:

var rowToBottomBorderizeRange = _xlSheet.Range[_xlSheet.Cells[rowToBottomBorderize, ITEMDESC_COL], _xlSheet.Cells[rowToBottomBorderize, TOTALS_COL]];
Borders border = rowToBottomBorderizeRange.Borders;
border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;

如果你在几个地方这样做,你可以用它来制作一个方法:

private void AddBottomBorder(int rowToBottomBorderize)
{
    var rowToBottomBorderizeRange = _xlSheet.Range[_xlSheet.Cells[rowToBottomBorderize, ITEMDESC_COL], _xlSheet.Cells[rowToBottomBorderize, TOTALS_COL]];
    Borders border = rowToBottomBorderizeRange.Borders;
    border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
}

上面的示例显示只添加了一个底部边框,但您可以轻松添加顶部,左侧或右侧边框线,将“xlEdgeBottom”替换为“xlEdgeTop”,“xlEdgeRight”或“xlEdgeLeft”

或者,您可以在以下范围内添加边框:

private void Add360Borders(int rowToBorderize)
{
    var rowToBottomBorderizeRange = _xlSheet.Range[_xlSheet.Cells[rowToBorderize, ITEMDESC_COL], _xlSheet.Cells[rowToBorderize, TOTALS_COL]];
    Borders border = rowToBorderizeRange.Borders;
    border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
    border[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
    border[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
    border[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
}

注意:您需要像这样定义表格:

private Worksheet _xlSheet;

...并在解决方案中引用Microsoft.Office.Interop.Excel程序集。

答案 1 :(得分:0)

尝试:

ws.get_Range("B2", "E3").Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
ws.get_Range("B2", "E3").Borders.Color = ColorTranslator.ToOle(Color.Red);