PHPExcel: How to insert an image in the first page header and enlarge it to fit it's content?

穿精又带淫゛_ 提交于 2019-12-10 15:12:51

问题


I have an Excel file made with PHPExcel which have an header with a left aligned logo and right aligned date & user text. For the first page, I want a similar header (same logo and same date & user text) but with some added information (title and parameters of the file centered a couples lines later).

This is what I'm doing so far:

<?php

    $sheet = $this->_spreadsheet->getActiveSheet(); //_spreadsheet is an instance of PHPExcel

    $logo = new PHPExcel_Worksheet_HeaderFooterDrawing();
    $logo->setName('Logo');
    $logo->setPath(DOCUMENT_ROOT . '/public/logo.jpg'); //Path is OK & tested under PHP
    $logo->setHeight(38); //If image is larger/smaller than that, image will be proportionally resized
    $sheet->getHeaderFooter()->addImage($logo, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT);

    $sheet->getHeaderFooter()->setOddHeader('&L&G&RExport date: ' . date('Y-m-d H:i:s') . "\n" . 'User: ' . $user->name);

    if ($grid->getTitle() != '') {
        $sheet->getHeaderFooter()->setDifferentFirst(true);

        $sheet->getHeaderFooter()->addImage($logo, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT);
        $sheet->getHeaderFooter()->setFirstHeader('&L&G&C&"-,Bold"' . "\n\n\n" . $grid->getTitle() . "\n" . $grid->getParameters() . '&RExport date: ' . date('Y-m-d H:i:s') . "\n" . 'User: ' . $user->name);
    }

?>

For the "regular" header, logo and text is all there so everything is OK. For the first page header I have 2 problems:

  1. The logo isn't showing on the first page header (but the text is OK).
  2. Since the centered title will be followed by some text (dynamically loaded with getParameters) I want the first page header to stretch to fit it's content.

How can I do this with PHPExcel?


回答1:


I don't have an answer for why the logo isn't showing on the first page header, but to stretch the height to fit the content you need to manually alter the page margins.

I'm not sure the best way to do it, whether counting newline characters or what. But once you know how many lines you have, you could do something like:

$headerHeight = ( $imageHeight / 72 ) + ( $headerLineCount * $lineHeight );
$objPHPExcel->getActiveSheet()->getPageMargins()->setHeader( $margin );
$objPHPExcel->getActiveSheet()->getPageMargins()->setTop( $margin + $headerHeight );

** The "$imageHeight / 72" clause is just a guess at how to convert your image's screen height into inches.



来源:https://stackoverflow.com/questions/6270039/phpexcel-how-to-insert-an-image-in-the-first-page-header-and-enlarge-it-to-fit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!