Home » excel » c# – Display cell with vertical text using EPPlus

c# – Display cell with vertical text using EPPlus

Posted by: admin May 14, 2020 Leave a comment

Questions:

Using EPPlus, how can i change a cells text to display as a vertical text like this,

Sample

In excel, you can do this by clicking on this button when setting cell orientation,

Excel orientation

I’m trying to play around with the .TextRotation but this does not achieve what I want, setting it to something like 180 degrees will give me something like this,

enter image description here

ws.Cells[row, 2].Style.TextRotation = 180;, .TextRotation only accepts an integer value so I was wondering how I can get the “Text” buttons value,

How to&Answers:

Its definitely a bug you found. There is a way but it is pretty ugly. You can use the StyleID created by the cell when you change it to anything other than the default:

[TestMethod]
public void Text_Rotate_Test()
{
    //https://stackoverflow.com/questions/57603348/display-cell-with-vertical-text-using-epplus

    var fileInfo = new FileInfo(@"c:\temp\Text_Rotate_Test.xlsx");
    if (fileInfo.Exists)
        fileInfo.Delete();

    using (var pck = new ExcelPackage(fileInfo))
    {
        var workbook = pck.Workbook;
        var worksheet = workbook.Worksheets.Add("Sheet1");
        var cell = worksheet.Cells[1, 1];

        cell.Value = "Test Text Value";

        //Trigger epplus to create a new style specific for the cell.
        //This needs to be done even thought it will be overridden in 
        //order to ref by index.  But have to be careful not to step
        //on other styles so make it as unique as it needs to be.
        cell.Style.TextRotation = 180;

        //Make sure the update the xml before looking up by index
        workbook.Styles.UpdateXml();
        workbook.Styles.CellXfs[cell.StyleID].TextRotation = 255;

        pck.Save();
    }
}

Which gives this:

enter image description here