Cell Style Alignment on a range

kschieck picture kschieck · Jul 17, 2012 · Viewed 121.3k times · Source

I'm having a problem fromatting cells in an excel sheet. For some reason my code seems to be changing the style of all cells when I just want to change the style of a few specified, or a specified range.

Here's some of the code that I am using:

app = new Microsoft.Office.Interop.Excel.Application();
workbook = app.Workbooks.Add(1);
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];

//Change all cells' alignment to center
worksheet.Cells.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

//But then this line changes every cell style back to left alignment
worksheet.Cells[y + 1, x + 2].Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

Why would it change the style of multiple cells when I set it to just work on one? Is it not supposed to work how I want it to? Is there another way of doing this?

Answer

Manikandan picture Manikandan · Jul 31, 2013

This works good

worksheet.get_Range("A1","A14").Cells.HorizontalAlignment = 
                 Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;