要在 Excel 范围(单元格范围,通常由 1.. 多行和 1.. 多列组成)的一侧或多侧添加边框,但对于这种特定情况,我们可能希望坚持一行1..多列),你只需要做三件事:
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 数组的一条或多条边分配一个边框;例如,如果您想在底部添加边框,如下所示:
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 程序集。