PHPExcel how to apply alignment for the whole document created from thesql table

PHPphpexcel

I used PHPExcel library to generate excel files based on the table created by the mysql query. I created multiple tabs with individual data from different queries.

I need to align the data in the all the cells in all the tabs (worksheets) to center.

This is my code:

$mysql_xls = new MySqlExcelBuilder($mysql_db,$mysql_user,$mysql_pass);

// Add the SQL statements to the spread sheet

$tab_name = "tabname";
$mysql_xls->add_page($tab_name,$sql_statement,NULL,'A',1);

$phpExcel = $mysql_xls->getExcel();

$phpExcel->setActiveSheetIndex(0); // Set the sheet to the first page (default first page).

I tried the following to align the text in the cells but no change:

$phpExcel->getActiveSheet(0)->getStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

Best Answer

Option #1

Set a default style for the entire workbook

$objPHPExcel->getDefaultStyle()
    ->getAlignment()
    ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

Option #2

Apply the style to a range of cells (the entire worksheet in this case) on each individual worksheet

$phpExcel->getActiveSheet()
    ->getStyle( $phpExcel->getActiveSheet()->calculateWorksheetDimension() )
    ->getAlignment()
    ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);  
Related Topic