Easy as 1-2-3
To add a border to one or more sides of an Excel Range (range of cells, which can normally be comprised of 1..many rows and 1..many columns, but for this specific scenario, we probably want to stick with one row and 1..many columns), you only need do three things:
- Define the range
- Get a reference to the
Range
's Borders
array - Assign a border to one or more of the
Border
array's edges/sides (top, bottom, left, right)
First, define the range over which you want to operate on like so:
var rowToBottomBorderizeRange = _xlSheet.Range[_xlSheet.Cells[rowToBottomBorderize, ITEMDESC_COL],
_xlSheet.Cells[rowToBottomBorderize, TOTALS_COL]];
Next, obtain a reference to the Range
's Borders
array like this:
Borders border = rowToBottomBorderizeRange.Borders;
Finally, assign a border to one or more of the Border
array's edges; for example, if you want to add a border to the bottom, like so:
border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
Putting it all together, the code could be:
var rowToBottomBorderizeRange = _xlSheet.Range[_xlSheet.Cells[rowToBottomBorderize,
ITEMDESC_COL], _xlSheet.Cells[rowToBottomBorderize, TOTALS_COL]];
Borders border = rowToBottomBorderizeRange.Borders;
border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
If you do this in several places, you could make a method out of it:
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;
}
The example above shows just adding a bottom border, but you can add top, left, or right border lines just as easily, replacing "xlEdgeBottom
" with "xlEdgeTop
", "xlEdgeRight
", or "xlEdgeLeft
"
Or, you could add borders all around a range like this:
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;
}
Note: You will need to define the sheet like this:
private Worksheet _xlSheet;
...and reference the Microsoft.Office.Interop.Excel
assembly in your solution.