Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cell Style Alignment on a range

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?

like image 421
kschieck Avatar asked Jul 17 '12 19:07

kschieck


People also ask

How many formatting alignment of a cell range explain in brief?

Data in a cell can be positioned horizontally and vertically within the cell. There are three horizontal alignments available – against the left border, against the right border, and in the centre. There are also three vertical alignments available – against the top border, against the bottom border, and in the middle.


2 Answers

This works good

worksheet.get_Range("A1","A14").Cells.HorizontalAlignment =                   Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; 
like image 161
Manikandan Avatar answered Oct 03 '22 02:10

Manikandan


Based on this comment from the OP, "I found the problem. apparentlyworksheet.Cells[y + 1, x + 1].HorizontalAlignment", I believe the real explanation is that all the cells start off sharing the same Style object. So if you change that style object, it changes all the cells that use it. But if you just change the cell's alignment property directly, only that cell is affected.

like image 43
DGH Avatar answered Oct 03 '22 01:10

DGH