This project is read-only.

Alignment not working

May 26, 2011 at 10:43 PM

I am having trouble getting alignment working in the NPOI-generated Excel file.

If I create a Cell on a Row and set its CellStyle.Alignment to, say, HorizontalAlignment.CENTER, it affects ALL cells in the entire Excel Worksheet. The last assignment to this property effects the alignment for the entire page. Anyone else run into this? Solution?

Thanks,

Jim

Coordinator
May 31, 2011 at 12:54 AM
Edited May 31, 2011 at 12:54 AM

Can you show me some runnable code? I'd like to make sure if it's caused by mistake in your code. Btw, which version are you using?

Jun 4, 2011 at 2:02 AM

Below is code that I have compiled and tested. It's straightforward -- changing the CellStyle.Alignment for one cell, either in the header or in the other rows, affects the entire page. In fact, ce.CellStyle.Alignment seems to act like a single instance global variable. The last assignment to Alignment affects the entire Worksheet.

I am using version 1.2.3.0.

 

            foreach (ISDWorksheetCell hCell in row0.Cells)
            {
                Cell ce = r.CreateCell(c);

                ce.CellStyle.Alignment = HorizontalAlignment.RIGHT;

                ce.SetCellValue(hCell.Text);

                c++;
            }

            string myValue = "";

            for (rIndex = 1; rIndex < rows.Count; rIndex++)
            {
                ISDWorksheetRow currentRow = (ISDWorksheetRow)rows[rIndex];

                r = sh.CreateRow(rIndex);
                c = 0;

                foreach (ISDWorksheetCell dCell in currentRow.Cells)
                {
                    myValue = dCell.Text.Replace("'", "''");

                    if (myValue.Length > 255)
                    {
                        myValue = myValue.Substring(0, 255);
                    }

                    Cell ce = r.CreateCell(c);

                    ce.CellStyle.Alignment = HorizontalAlignment.CENTER;

                    ce.SetCellValue(myValue);

                    c++;
                }
            }

Jun 13, 2011 at 1:37 PM

Same is The problem with me.Please suggest me and give the Solution

Nov 29, 2011 at 6:20 PM

I've got a similar problem.
For some reason, the CellStyle property is shared by the cells, so I've solved the issue creating a new CellStyle instance for every new cell.

In your loop:

Cell ce = r.CreateCell(c);
ce.CellStyle = workbook.CreateCellStyle();
ce.CellStyle.Alignment = HorizontalAlignment.CENTER;
ce.SetCellValue(myValue);

Coordinator
Dec 13, 2011 at 2:45 AM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.