Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel - colspan the subject name

Tags:

php

phpexcel

  • Table name: subject
    enter image description here

  • My Expected output
    enter image description here

  • My code

    <?php
        //dbconnection
    
        $q = "SELECT name FROM subject";
        $r = mysqli_query($dbc, $q);
    
        while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
        {
            $name[] = $row['name'];
        }
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
    
        $headers = array('School Name');
        $objPHPExcel->getActiveSheet()->fromArray($headers, null, 'A1');
        $objPHPExcel->getActiveSheet()->fromArray($name, null, 'B1');
    
        $objPHPExcel->getActiveSheet()->mergeCells('B1:C1');
        $objPHPExcel->getActiveSheet()->mergeCells('D1:E1');
        $objPHPExcel->getActiveSheet()->mergeCells('F1:G1');
        $objPHPExcel->getActiveSheet()->mergeCells('H1:I1');
    ?>
    
  • I want to set colspan = 2 for each subject. I don't want to write 4 individual lines of code. I try with for loop as below:

    $objWorksheet = $objPHPExcel->getActiveSheet();
    
    $row = 1;
    $highestColumn = $objWorksheet -> getHighestColumn();
    $highestColumn++;
    
    for($column = 'A'; $column != $highestColumn; $column++)
    {
        if($column <= 'C')
        {
            //[HERE]
        }
    }
    
  • After I write the for loop, I am stuck. I have no ideas on how to control the column name and set the colspan. Can someone help me?

like image 384
Michael Kuan Avatar asked Sep 17 '15 15:09

Michael Kuan


1 Answers

Probably a lot easier to do this in a loop over the subject list:

$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'School Name');
$objPHPExcel->getActiveSheet()->mergeCells('A1:A2');

$column = 'B';
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
    $objPHPExcel->getActiveSheet()->setCellValue($column.'1', $row['name']);
    $mergeRange = $column.'1:';
    $objPHPExcel->getActiveSheet()->setCellValue($column.'2', 'Student Name');
    $column++;
    $mergeRange .= $column.'1';
    $objPHPExcel->getActiveSheet()->setCellValue($column.'2', 'Grade');
    $objPHPExcel->getActiveSheet()->mergeCells($mergeRange);
    $column++;
}
like image 139
Mark Baker Avatar answered Sep 24 '22 03:09

Mark Baker