Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center the text in PHPExcel merged cell

Tags:

php

phpexcel

How to center text "test"?

This is my code:

<?php     /** Error reporting */     error_reporting(E_ALL);     ini_set('display_errors', TRUE);     ini_set('display_startup_errors', TRUE);     date_default_timezone_set('Europe/London');      /** Include PHPExcel */     require_once '../Classes/PHPExcel.php';      $objPHPExcel = new PHPExcel();     $sheet = $objPHPExcel->getActiveSheet();     $sheet->setCellValueByColumnAndRow(0, 1, "test");     $sheet->mergeCells('A1:B1');     $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');     $objWriter->save("test.xlsx"); 

Output Excel document:

enter image description here

like image 602
user4035 Avatar asked Jan 22 '14 14:01

user4035


People also ask

How do I center text in merged cells in Google Sheets?

In Google Sheets, to change the horizontal alignment of text in a cell, select the cell and click the Horizontal Align button on the toolbar (shown above). Once done, you'll have the option to select Left, Center, and Right alignment. Press one of the shortcut keys to adjust the alignment of any selected cell.

How do you wrap text in PHPExcel?

I know that this line of code will make the cell text-wrap: $objPHPExcel->getActiveSheet()->getStyle('D1')->getAlignment()->setWrapText(true);

How do I merge cells in PHPExcel?

$sheet = $workbook->getActiveSheet(); $sheet->setCellValue('A1','A pretty long sentence that deserves to be in a merged cell'); $sheet->mergeCells('A1:C1');


2 Answers

if you want to align only this cells, you can do something like this:

    $style = array(         'alignment' => array(             'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,         )     );      $sheet->getStyle("A1:B1")->applyFromArray($style); 

But, if you want to apply this style to all cells, try this:

    $style = array(         'alignment' => array(             'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,         )     );      $sheet->getDefaultStyle()->applyFromArray($style); 
like image 141
dap.tci Avatar answered Sep 29 '22 22:09

dap.tci


<?php     /** Error reporting */     error_reporting(E_ALL);     ini_set('display_errors', TRUE);     ini_set('display_startup_errors', TRUE);     date_default_timezone_set('Europe/London');      /** Include PHPExcel */     require_once '../Classes/PHPExcel.php';      $objPHPExcel = new PHPExcel();     $sheet = $objPHPExcel->getActiveSheet();     $sheet->setCellValueByColumnAndRow(0, 1, "test");     $sheet->mergeCells('A1:B1');     $sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);     $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');     $objWriter->save("test.xlsx"); ?> 
like image 22
Rogerio de Moraes Avatar answered Sep 29 '22 23:09

Rogerio de Moraes