简体   繁体   中英

how to merge cells in excel using php?

using php i exported report in excel.But got stuck in merging cells. i want to merge the first 10 cells to dispaly the Name of the Company. The variable which has the company name is in one cell, tried to merge the cells but i cudn't...

I used this function to export,

where $query variable holds the mysql query which is sent as a parameter, and in $fieldname variable, array of fieldnames to display header.

everything is ok, n works properly. one thing i cudn't do was merging cells....

function to_excel_export($query,$fieldName)
{

 $filename = date('d-m-Y');
 $headers = ''; 
 $data = '';
 $obj =& get_instance();
 if ($query->num_rows() == 0)
 {
      echo '<p>The table appears to have no data.</p>';
 }
 else
 {
     for($i=0;$i<sizeof($fieldName);$i++)
     {
         $headers .= $fieldName[$i] . "\t";
     }

      foreach ($query->result() as $row)
      {
           $line = '';
           foreach($row as $value)
           {                                            
                if ((!isset($value)) OR ($value == ""))
                {
                   $value = "\t";
                } 
                else 
                {
                   $value = str_replace('"', '""', $value);
                   $value = '"' . $value . '"' . "\t";
                }
                $line .= $value;
           }
           $data .= trim($line)."\n";
      }

      $data = str_replace("\r","",$data);
      header("Content-type: application/x-msdownload");
      header("Content-Disposition: attachment; filename=$filename.xls");

      $compName = 'C O M P A N Y - N A M E ';
      echo $compName."\n\n";
      echo $headers."\n".$data; 
 }

}

$compName = 'C O M P A N Y - N A M E ';
      echo $compName."\n\n";

how to merge the cells to display the name which is in $compName variable.

You're not creating an Excel file, you're creating a CSV file (tab separated in this case), and that format does NOT support any kind of formatting (font, color, even merging cells isn't an option).... and you're not even using PHP's built-in fputcsv() function to do so :(

Simply giving a file an extension of .xls doesn't make it an Excel file. MS Excel is capable of reading CSV files, but some versions of Excel will actually warn you that the format isn't correct when you load it.

Create a proper Excel BIFF or OfficeOpenXML file using one of the many libraries available to do so (such as PHPExcel), and then you'll be able to set formatting such as cell background colours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM