PHPExcel Set URL Font Styles (Color and Underline)

When creating excel files using PHPExcel, on setting a hyperlink the cell value’s styling is generally not affected. This happens on purpose to give us more control on how we want to format our content. Usually this is how we’d set a hyperlink:

// Set hyperlink
$objPHPExcel->setActiveSheetIndex(0)
            ->getCell("A1")
            ->getHyperlink()
            ->setUrl('http://google.com');

// Set cell content
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue("A1", 'http://google.com/'); // Could also set to lets say "Google"

On viewing the excel file, the link won’t appear to be blue with an underline – which is what we’d expect to happen inherently. In order to achieve that, we’ll need to style/format it accordingly:

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

// Config
$link_style_array = [
  'font'  => [
    'color' => ['rgb' => '0000FF'],
    'underline' => 'single'
  ]
];

// Set it!
$objPHPExcel->getActiveSheet()->getStyle("A1")->applyFromArray($link_style_array);

Various values supported by the underline option are none, single, singleAccounting, double and doubleAccounting.

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

2 thoughts on “PHPExcel Set URL Font Styles (Color and Underline)”

  1. Rishabh:
    Buenas tardes
    Soy de Argentina (hablo español y algo de ingles), en mi script de PhpExcel tengo esta variable donde me viene una URL …
    Ejemplo http://xxx.com.ar/zzz.php
    $pagina = http://xxx.com.ar/zzz.php
    $objSheet->setCellValue(‘I’.$numero, $pagina);
    Si bien en el excel sale perfecto, no sale el link de manera automatica, ya que debo hacer un doble clic para que pueda hacer el linck
    ¿Si se te ocurre alguna idea, con mucho gusto la escucharia?
    Un saludo
    Daniel

  2. I see your site needs some fresh articles. Writing manually is time
    consuming, but there is tool for this task. Just search in gooogle for
    – Avurker’s essential tools

Leave a Reply

Your email address will not be published. Required fields are marked *