How to center align cells

Topics: Developer Forum, User Forum
Feb 20, 2013 at 6:50 PM
I am trying to center numbers in row cells and no matter what I try nothing is working.
Currently, I use the following to apply to each cell as I populate it with the decimal numbers.
$style_num = array('font' =>
                                    array('color' =>
                                      array('rgb' => '000000'),
                                      'bold' => false,
                                    ),
                           'alignment' => array(
                                            'wrap'       => true,
                                      'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                                      'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
                                        ),
                     );
//
//
          // write summary table rows
          //
          $col='A';
          $xrow++;
          for($x=0;$x<count($sum_com);$x++) {
            foreach($sum_com[$x] as $fieldname =>$fieldvalue) {
              switch ($fieldname) {
                case 'VM Qty':
                case 'ETF Qty':
                case 'Total Qty':
                  $worksheet->setCellValue($col.$xrow, $fieldvalue);
                  $worksheet->getStyle($col.$xrow)->applyFromArray($style_num);
                  break;
                default:
                  $worksheet->setCellValueExplicit($col.$xrow, $fieldvalue, PHPExcel_Cell_DataType::TYPE_STRING);
                  break;
              }    // end swt on fieldname
              $worksheet->getStyle($col.$xrow)->applyFromArray($style_textblack);
              $worksheet->getRowDimension($xrow)->setRowHeight(15);
              $col++;
            }
} // end for over summary
Feb 22, 2013 at 2:56 AM
Hi!

I'm not sure how you implement it but here's my code for alignment:
$sheet->getStyle("A".$rn.":B".$rn)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$sheet->getStyle("C".$rn.':V'.$rn)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
Feb 25, 2013 at 2:36 PM
Hi bluerain,
I tried the code you sent me, changing the addressing to my variable values and it still left-aligns those cells.

$worksheet->getStyle($col.$xrow.":".$col.$xrow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

This looks right and doesn't error, but the alignment still does not work.
Any other ideas?
Coordinator
Feb 25, 2013 at 3:02 PM
What Writer are you using?
Feb 25, 2013 at 3:49 PM
XLSX - as in code snippet below:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
thanks
Feb 26, 2013 at 7:46 PM
Edited Feb 26, 2013 at 7:46 PM
RESOLVED - sorry it was a user error. I had code below these lines that set the alignment back to HORIZONTAL_LEFT. When I removed that line, all worked fine.
Sorry for the bother!