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

user1702273 picture user1702273 · Sep 27, 2012 · Viewed 40.2k times · Source

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);

Answer

Mark Baker picture Mark Baker · Sep 27, 2012

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);