2

I want to create border on a cell and then a left and right border.

I tried this code but it doesnt work:(

objSheet.get_Range("F19").Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = true;
objSheet.get_Range("F19").Borders.Color = Color.Black;

I get the second one you see here. (A border all around) https://i.stack.imgur.com/H4Ujy.png

How can I get this working? Or is a border at the left and right side of a cell not possible from C# to Excel?

Marco
  • 33
  • 2
  • 4

2 Answers2

2

Try this:

var range = objSheet.get_Range("F19");
System.Drawing.Color color = System.Drawing.Color.Black;
range.Borders[XlBordersIndex.xlEdgeRight].Color = color;
range.Borders[XlBordersIndex.xlEdgeLeft].Color = color;

Edit: If you're worried about cleaning up your Excel objects and you want to avoid using two dots (see discussion here), you can keep a reference the the borders that you use like so:

var right = range.Borders[XlBordersIndex.xlEdgeRight];
var left = range.Borders[XlBordersIndex.xlEdgeLeft];
right.Color = color;
left.Color = color;

I think my original version indirectly uses two dots.

Community
  • 1
  • 1
user2023861
  • 8,030
  • 9
  • 57
  • 86
1

You can set the line style and colour for specific borders like this:

Excel.Range range = objSheet.get_Range("F19");
Excel.Border border = range.Borders[Excel.XlBordersIndex.xlEdgeRight];
border.LineStyle = Excel.XlLineStyle.xlContinuous;
border.Color = Color.Black;

border = range.Borders[Excel.XlBordersIndex.xlEdgeLeft];
border.LineStyle = Excel.XlLineStyle.xlContinuous;
border.Color = Color.Black;

And then clean up your references:

border = null;
range = null;

Specifically creating a reference to the Excel.Border object ensures you can dispose of it and won't leave it hanging around. See Eliminating use of '2 dots' when using Excel...

Community
  • 1
  • 1
Sid Holland
  • 2,871
  • 3
  • 27
  • 43