4

I'd like to rotate headers in an Excel file using Microsoft.Office.Interop. To achieve this, I'm using the following code:

worksheet.Range["A1:" + worksheet.UsedRange.Columns.Count + "1"].Style.Orientation
    = Excel.XlOrientation.xlUpwards;

The result looks like this:

Rotated cells

As you can see, every cell gets rotated although I'm only specifying the first row. However, I just want the headers to be rotated:

Rotated headers

I even tried it with a for loop for every column:

for (int counter = 1; counter <= worksheet.UsedRange.Columns.Count; counter++)
    worksheet.Range[GetExcelColumnName(counter) + "1"].Style.Orientation
        = Excel.XlOrientation.xlUpwards;

But I get the same result. What should I do to only change the orientation of the headers?

(Method GetExcelColumnName)

diiN__________
  • 7,393
  • 6
  • 42
  • 69

2 Answers2

5

Just convert the entire row 1.

worksheet.Range["1:1"].Style.Orientation = Excel.XlOrientation.xlUpwards;
worksheet.Rows["1"].Style.Orientation = Excel.XlOrientation.xlUpwards;

fwiw, in VBA this might be best handled with application.intersect of rows(1) and the .usedrange. From your code it looks like that would be,

Excel.Intersect(worksheet.Range["1:1"], worksheet.UsedRange).Style.Orientation = Excel.XlOrientation.xlUpwards;
/* just the cells, not the style */
Excel.Intersect(worksheet.Range["1:1"], worksheet.UsedRange).Cells.Orientation = Excel.XlOrientation.xlUpwards;
  • Nice idea, but still all rows are rotated :( – diiN__________ Jun 15 '17 at 13:35
  • It sounds like you have a linked style and you are resetting the properties of the entire style. Can you *just* reset the orientation of the cells without changing the style or can you apply a different style to the non-headers? –  Jun 15 '17 at 13:38
  • 2
    There is a [Style.Orientation](https://msdn.microsoft.com/en-us/library/office/ff839229.aspx) property and a [Range.Orientation](https://msdn.microsoft.com/en-us/library/office/ff198186.aspx) property; you need the latter. –  Jun 15 '17 at 13:43
  • 1
    Your edit worked ("just the cells, not the style"). I changed the code to `worksheet.Rows["1"].Cells.Orientation`. Thank you! – diiN__________ Jun 15 '17 at 13:43
0

What worked for me was:

ws.SelectedRange[1, 1, 1, 15].Style.TextRotation = 180;

TextRotation for vertical text: 90 or 180 (upwards, downwards)

FrenkyB
  • 6,625
  • 14
  • 67
  • 114