7
  • 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?

Michael Kuan
  • 1,085
  • 3
  • 10
  • 28
  • 1
    if you span a col/row, then the spanned cell's address is the address of the top-left corner of that spanned cell, so if you span B1->C1 to produce a single "two column" cell, the address is still B1, and C1 is hidden/suppressed – Marc B Sep 17 '15 at 15:35

1 Answers1

12

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++;
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385