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

有人可以告诉我如何添加另一种颜色的细胞范围外的边界? 理想情况下,我希望能够用一种方法来做到这一点,我将不得不多次这样做。 search后,我发现两个方法,显然会做到这一点 – 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文档指出:

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

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

最后,我要指出的是,我在这里find了一个解决scheme, 在这里你分别设置了不同的边缘,但是正如我所说的,我希望使用单一的方法做这个,因为它必须重复多次。

要将边框添加到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; 

最后,为一个或多个边界数组的边缘分配边界; 例如,如果你想添加一个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; } 

上面的例子显示的只是添加一个底部边框,但您可以轻松地添加顶部,左侧或右侧边框线,用“xlEdgeTop”,“xlEdgeRight”或“xlEdgeLeft”replace“xlEdgeBottom”

或者,你可以像这样在范围内添加边框:

 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; 

…并在您的解决scheme中引用Microsoft.Office.Interop.Excel程序集。

尝试:

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