Search code examples
c#alignmentexcel-interopright-align

How can I get Excel cell contents to right justify using C#?


A portion of my dynamically-created spreadsheet looks like this:

enter image description here

At first, both currency values (the second and third rows in each block of four rows inside the bounded column) were (by default) offset a little from the right, as you can see the second currency value / third row is now.

Thus, the two currency rows were not quite aligning with the first (int) row and the last (%) row.

I want them all to hug the vertical border on the right side of the block, like the int and the % rows.

I experimented by adding this code for the first currency value / second row, to attempt to justify it, hoping it would justify right:

monthPurchasesCell.HorizontalAlignment = XlVAlign.xlVAlignJustify;

...but, as you can see in the screen shot snippet, it does the opposite (justifies left). There is no "xlVAlignJustifyRight" or so.

In context, the code to display the four rows in a month block is:

private void AddMonthData(int packages, decimal purchases, decimal avgPrice, double percent, int colToPopulate)
{
    var monthPackagesCell = (Range)_xlSheet.Cells[_curDescriptionTopRow, colToPopulate];
    monthPackagesCell.Value2 = packages.ToString("N0", CultureInfo.CurrentCulture);
    var monthPurchasesCell = (Range)_xlSheet.Cells[_curDescriptionTopRow + 1, colToPopulate];
    monthPurchasesCell.Value2 = purchases.ToString("C", CultureInfo.CurrentCulture);
    monthPurchasesCell.HorizontalAlignment = XlVAlign.xlVAlignJustify;
    var monthAvgPriceCell = (Range)_xlSheet.Cells[_curDescriptionTopRow + 2, colToPopulate];
    monthAvgPriceCell.Value2 = avgPrice.ToString("C", CultureInfo.CurrentCulture);
    var monthPercentOfTotalCell = (Range)_xlSheet.Cells[_curDescriptionTopRow + 3, colToPopulate];
    monthPercentOfTotalCell.Value2 = percent.ToString("P", CultureInfo.CurrentCulture);
}

How can I justify the currency values to the right?


Solution

  • I think you have to use XlHAlign for horizontal alignments.