C#.NET Interop Excel - Not able to align only specific Columns

32 Views Asked by At

I am trying to create an Excel Export file and I want to align some of the columns horizontally centered and some of them should be aligned to the Right.

However when I set the Style.HorizontalAlignment of the Range, it sets all the cells to that alignment, even if i pick only specific cells.

Here is my code:

var xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Add(Type.Missing);
Excel.Worksheet xlSheet = xlWorkbook.ActiveSheet;       
// Columns
xlSheet.Cells[1, 1] = "Column 1";
xlSheet.Cells[1, 2] = "Column 2";
xlSheet.Cells[1, 3] = "Column 3";
xlSheet.Cells[1, 4] = "Column 4";
xlSheet.Cells[1, 5] = "Column 5";
xlSheet.Cells[1, 6] = "Column 6";
xlSheet.Cells[1, 7] = "Column 7";
xlSheet.Cells[1, 8] = "Column 8";
// Header Row Format
var headerRow = xlSheet.Range["A1", "H1"];
headerRow.Font.Bold = true;
headerRow.Interior.Color = ColorTranslator.FromHtml("#e1e1e1");
// Column Alignments
((Excel.Style)xlSheet.Cells[1, 5].Style).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
((Excel.Style)xlSheet.Cells[1, 6].Style).HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
((Excel.Style)xlSheet.Cells[1, 7].Style).HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
((Excel.Style)xlSheet.Cells[1, 8].Style).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

I also have tried this:

(xlSheet.Range["A1", "A1"].EntireColumn.Style as Excel.Style).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

But it still sets all the cells instead of only the whole Column "A".

I am using the Microsoft COM Library:

using Excel = Microsoft.Office.Interop.Excel;

What am I missing here? I also tried to use different methods to set the Range Alignment of a column, but no chance, everytime i set the Alignment it sets it for all the cells.

In my code above the last setted Alignment Option wins, so if the last setting would be Excel.XlHAlign.xlHAlignLeft, then all the cells would be alignt to left.

I am not sure, but could it be something about UsedRange?

Any help would be appreciated.

Thanks

1

There are 1 best solutions below

0
Leon On

All right, now I found a solution thanks to the following thread: Changing font size of one cell in excel using C#

It seems that using of .Style on the Range or Cells affects all the cells in the Excel Sheet.

Therefore i had to use the following syntax without the .Style attribute:

xlSheet.Range["A1"].Cells.EntireColumn.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
xlSheet.Range["B1"].Cells.EntireColumn.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

or much easier:

xlSheet.Columns["A"].HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
xlSheet.Columns["B"].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

Now it works.