Magento 2: Display Image in exported excel file from custom gridExport products from wp Ecommerce and import into magentoMagento 2 : add pager in custom grid at frontendMagento 2: Data Migration From Non Magento Database to Magento DatabaseMagento 2 Exported file format Doesn't work for “configurable_variations” field when importMagento 2export customer grid in excel formatData value is appearing instead of data label in grid exportHide Custom Grid Mass Action for non administrator userhow to Show custom column in Product Grid magento 2Magento2 Admin Grid Image DisplayExport Custom Gird CSV and Excel file not working

Lengthened voiced stops and the airstream through the nose

Loading military units into ships optimally, using backtracking

What does the phrase "pull off sick wheelies and flips" mean here?

Why aren't rainbows blurred-out into nothing after they are produced?

Is there a command to install basic applications on Ubuntu 16.04?

Is it okay for a ticket seller in the USA to refuse to give you your change, keep it for themselves and claim it's a tip?

Is it legal for a company to enter an agreement not to hire employees from another company?

What ability do tools use?

0xF1 opcode-prefix on i80286

How to assign many blockers at the same time?

The cat ate your input again!

How can Radagast come across Gandalf and Thorin's company?

Are employers legally allowed to pay employees in goods and services equal to or greater than the minimum wage?

How to describe accents?

If "more guns less crime", how do gun advocates explain that the EU has less crime than the US?

How to divide item stack in MC PE?

Understanding this peak detector circuit

Does the Fireball spell damage objects?

Is God unknowable?

Can a PC use the Levitate spell to avoid movement speed reduction from exhaustion?

Normalization constant of a planar wave

What gave Harry Potter the idea of writing in Tom Riddle's diary?

Super Duper Vdd stiffening required on 555 timer, what is the best way?

How can this older-style irrigation tee be replaced?



Magento 2: Display Image in exported excel file from custom grid


Export products from wp Ecommerce and import into magentoMagento 2 : add pager in custom grid at frontendMagento 2: Data Migration From Non Magento Database to Magento DatabaseMagento 2 Exported file format Doesn't work for “configurable_variations” field when importMagento 2export customer grid in excel formatData value is appearing instead of data label in grid exportHide Custom Grid Mass Action for non administrator userhow to Show custom column in Product Grid magento 2Magento2 Admin Grid Image DisplayExport Custom Gird CSV and Excel file not working






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am creating a custom admin grid (using Bock not UI Component) with custom collection.
In that grid, I have a column of product image.



Please see below screenshot:



enter image description here



There are two way to export grid data(Excel and CSV), When I export the grid data into excel format(file.xlsx), It's showing whole image tag(like: <img src="http://127.0.0.1/poserp/pub/media/catalog/product/1/2/124.png" width="67" height = "67" />) in product image column.



Please see below screenshot:



enter image description here



Here, I want to display real image in exported Excel file only as it's shown below screenshot:



enter image description here



Here I am using default magento excel functionality for exporting the grid data into excel format in my controller file(exportExcel.php).



public function execute() 
$fileName = 'file.xlsx';

$content = $this->_view->getLayout()->createBlock(
VendornameModulenameBlockAdminhtmlReportGrid::class
)->getExcelFile();

return $this->fileFactory->create($fileName, $content, DirectoryList::VAR_DIR);



Please give me an idea that how can I achieve it.
Any help will be appreciated.










share|improve this question
























  • If you use default product import function then got proper image in product grid page.

    – Soundararajan m
    Aug 1 at 13:19











  • @Soundararajanm I am asking about export the data not import.

    – Faisal Sheikh
    Aug 1 at 13:22

















0















I am creating a custom admin grid (using Bock not UI Component) with custom collection.
In that grid, I have a column of product image.



Please see below screenshot:



enter image description here



There are two way to export grid data(Excel and CSV), When I export the grid data into excel format(file.xlsx), It's showing whole image tag(like: <img src="http://127.0.0.1/poserp/pub/media/catalog/product/1/2/124.png" width="67" height = "67" />) in product image column.



Please see below screenshot:



enter image description here



Here, I want to display real image in exported Excel file only as it's shown below screenshot:



enter image description here



Here I am using default magento excel functionality for exporting the grid data into excel format in my controller file(exportExcel.php).



public function execute() 
$fileName = 'file.xlsx';

$content = $this->_view->getLayout()->createBlock(
VendornameModulenameBlockAdminhtmlReportGrid::class
)->getExcelFile();

return $this->fileFactory->create($fileName, $content, DirectoryList::VAR_DIR);



Please give me an idea that how can I achieve it.
Any help will be appreciated.










share|improve this question
























  • If you use default product import function then got proper image in product grid page.

    – Soundararajan m
    Aug 1 at 13:19











  • @Soundararajanm I am asking about export the data not import.

    – Faisal Sheikh
    Aug 1 at 13:22













0












0








0








I am creating a custom admin grid (using Bock not UI Component) with custom collection.
In that grid, I have a column of product image.



Please see below screenshot:



enter image description here



There are two way to export grid data(Excel and CSV), When I export the grid data into excel format(file.xlsx), It's showing whole image tag(like: <img src="http://127.0.0.1/poserp/pub/media/catalog/product/1/2/124.png" width="67" height = "67" />) in product image column.



Please see below screenshot:



enter image description here



Here, I want to display real image in exported Excel file only as it's shown below screenshot:



enter image description here



Here I am using default magento excel functionality for exporting the grid data into excel format in my controller file(exportExcel.php).



public function execute() 
$fileName = 'file.xlsx';

$content = $this->_view->getLayout()->createBlock(
VendornameModulenameBlockAdminhtmlReportGrid::class
)->getExcelFile();

return $this->fileFactory->create($fileName, $content, DirectoryList::VAR_DIR);



Please give me an idea that how can I achieve it.
Any help will be appreciated.










share|improve this question














I am creating a custom admin grid (using Bock not UI Component) with custom collection.
In that grid, I have a column of product image.



Please see below screenshot:



enter image description here



There are two way to export grid data(Excel and CSV), When I export the grid data into excel format(file.xlsx), It's showing whole image tag(like: <img src="http://127.0.0.1/poserp/pub/media/catalog/product/1/2/124.png" width="67" height = "67" />) in product image column.



Please see below screenshot:



enter image description here



Here, I want to display real image in exported Excel file only as it's shown below screenshot:



enter image description here



Here I am using default magento excel functionality for exporting the grid data into excel format in my controller file(exportExcel.php).



public function execute() 
$fileName = 'file.xlsx';

$content = $this->_view->getLayout()->createBlock(
VendornameModulenameBlockAdminhtmlReportGrid::class
)->getExcelFile();

return $this->fileFactory->create($fileName, $content, DirectoryList::VAR_DIR);



Please give me an idea that how can I achieve it.
Any help will be appreciated.







magento2 importexport custom-grid






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Aug 1 at 12:13









Faisal SheikhFaisal Sheikh

4071 silver badge12 bronze badges




4071 silver badge12 bronze badges















  • If you use default product import function then got proper image in product grid page.

    – Soundararajan m
    Aug 1 at 13:19











  • @Soundararajanm I am asking about export the data not import.

    – Faisal Sheikh
    Aug 1 at 13:22

















  • If you use default product import function then got proper image in product grid page.

    – Soundararajan m
    Aug 1 at 13:19











  • @Soundararajanm I am asking about export the data not import.

    – Faisal Sheikh
    Aug 1 at 13:22
















If you use default product import function then got proper image in product grid page.

– Soundararajan m
Aug 1 at 13:19





If you use default product import function then got proper image in product grid page.

– Soundararajan m
Aug 1 at 13:19













@Soundararajanm I am asking about export the data not import.

– Faisal Sheikh
Aug 1 at 13:22





@Soundararajanm I am asking about export the data not import.

– Faisal Sheikh
Aug 1 at 13:22










2 Answers
2






active

oldest

votes


















1














I think you need to override vendor/magento/module-backend/Block/Widget/Grid/Export.php this File and check getExcelFile function



And also see this exmple for adding image in Excel File



Adding Image to the Excel






share|improve this answer



























  • After implementing this code, images are still not showing in excel file.

    – Faisal Sheikh
    Aug 1 at 13:40











  • please check answer

    – Rk Rathod
    Aug 1 at 13:59











  • Now I am able to get image in exported excel file. Thank you for the suggestion.

    – Faisal Sheikh
    Aug 2 at 12:40












  • if you dont mind please attach code.. most welcome.. happy coding.. :)

    – Rk Rathod
    Aug 2 at 12:54











  • I have posted, you can see now.

    – Faisal Sheikh
    Aug 2 at 13:18


















0














Finally, I got the image in my exported Excel file.
Here is my exportExcel.php (Controller) code:



<?php

namespace VendornameModulenameControllerAdminhtmlReport;

use MagentoFrameworkAppFilesystemDirectoryList;

class exportExcel extends MagentoBackendAppAction

/**
* @var MagentoBackendModelSession
*/
protected $_adminSession;

/**
* @var VendornameModulenameBlockAdminhtmlReportGrid
*/
protected $_gridData;
protected $resultPageFactory;
protected $fileFactory;
protected $_resultFactory;
protected $_xlsx;
protected $resultPage;


/**
*
* @param MagentoBackendAppActionContext $context
* @param MagentoFrameworkViewResultPageFactory $resultPageFactory
*/
public function __construct(
MagentoBackendAppActionContext $context,
VendornameModulenameBlockAdminhtmlReportGrid $gridData,
MagentoBackendModelSession $adminSession,
MagentoFrameworkViewResultPageFactory $resultPageFactory,
MagentoFrameworkControllerResultFactory $resultFactory,
MagentoFrameworkAppResponseHttpFileFactory $fileFactory,
MagentoFrameworkFilesystemDirectoryList $directoryList,
MagentoFrameworkFilesystem $filesystem,
MagentoFrameworkDataCollectionFactory $collectionFactory,
PhpOfficePhpSpreadsheetWriterXlsx $xlsx,
MagentoCatalogModelProductRepository $productRepository,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoCatalogHelperImage $productImageHelper
)
parent::__construct($context);
$this->_gridData = $gridData;
$this->_adminSession = $adminSession;
$this->resultPageFactory = $resultPageFactory;
$this->_fileFactory = $fileFactory;
$this->_directoryList = $directoryList;
$this->_filesystem = $filesystem;
$this->_collectionFactory = $collectionFactory;
$this->_xlsx = $xlsx;
$this->_productRepository = $productRepository;
$this->_storeManager = $storeManager;
$this->_productImageHelper = $productImageHelper;
$this->_resultFactory = $resultFactory;
DEFINE('DS', DIRECTORY_SEPARATOR);


/**
*
* @return type
*/
public function execute()

try
$websiteId = 0;
$productIds = [];
$resultRedirect = $this->_resultFactory->create(MagentoFrameworkControllerResultFactory::TYPE_REDIRECT);
$dataArray = $this->_adminSession->getData('ExportArray');
$totalData = [];
$i = 0;
foreach($dataArray as $item)

$totalData[$i]['image'] = '';
$totalData[$i]['id'] = $item['id'];
$totalData[$i]['name'] = $item['name'];
$totalData[$i]['barcode'] = $item['barcode'];
$totalData[$i]['retailprice'] = $item['retailprice'];
$totalData[$i]['sku'] = $item['sku'];
$totalData[$i]['store'] = $item['store'];
$totalData[$i]['minqty'] = $item['minqty'];
$totalData[$i]['maxqty'] = $item['maxqty'];
$totalData[$i]['availqty'] = $item['availqty'];
$i++;


$headerColumns = array('0' => array('Product Image', 'Product ID', 'Product Name', 'Barcode', 'Retail Price', 'SKU', 'Store', 'Min QTY', 'Max QTY', 'Available QTY'));

if (count($lowStockExportArray) == 0)
$this->messageManager->addNoticeMessage(__('There is no data to export!'));
$resultRedirect->setUrl($this->_redirect->getRefererUrl());
return $resultRedirect;

$excelData = array_merge($headerColumns, $totalData);
$productIds = $this->getProductIds();
$imageData = $this->processDataForXlsxImage($websiteId, $productIds);
$xlsxFileName = 'file.xlsx';
$xlsxFilePath = $this->getFilePath($xlsxFileName);
$this->generateXlsx($excelData, $xlsxFilePath);
$this->addImageToXlsx($imageData, $xlsxFilePath);
$this->downloadXlsx($xlsxFilePath);
catch (Exception $ex)
$this->messageManager->addErrorMessage($ex->getMessage());



public function getFilePath($fileName)
return $this->_directoryList->getPath(MagentoFrameworkAppFilesystemDirectoryList::VAR_DIR) . "/folder_name/" . $fileName;


public function generateXlsx($excelData, $filePath)
$spreadsheet = new PhpOfficePhpSpreadsheetSpreadsheet();
$sheet = $spreadsheet->getActiveSheet();

$sheet->setTitle('Excel File');
$sheet->fromArray($excelData);
$writer = $this->_xlsx->setSpreadsheet($spreadsheet);
$writer->save($filePath);


public function downloadXlsx($xlsxFilePath)
if (file_exists($xlsxFilePath))
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename=' . basename($xlsxFilePath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($xlsxFilePath));
ob_clean();
flush();
readfile($xlsxFilePath);



public function getProductIds()
$data = [];
$arrayExport = $this->_adminSession->getData('ExportArray');
if (count($arrayExport) > 0)
foreach ($arrayExport as $value)
$data[] = $value['id'];

return $data;

return $data;


public function processDataForXlsxImage($store, $productIds)
$result = [];
$mediaDirectory = $this->getMediaPath();
foreach ($productIds as $productId)
$product = $this->_productRepository->getById($productId);
$imageUrl = $this->_productImageHelper->init($product, 'product_page_image_thumbnail')->setImageFile($product->getThumbnail())->resize(70, 70)->getUrl();
$result[] = $this->getImagePath($imageUrl, $mediaDirectory);

return $result;


public function addImageToXlsx($imageData, $xlsxFilePath)
if (count($imageData))
$reader = PhpOfficePhpSpreadsheetIOFactory::createReaderForFile($xlsxFilePath);
$inputFileType = PhpOfficePhpSpreadsheetIOFactory::identify($xlsxFilePath);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($xlsxFilePath);
$cellNo = 1;
foreach ($imageData as $image)
if ($cellNo >= 1 && $image != '') $extension == 'jpeg')
$gdImage = imagecreatefromjpeg($image);

if ($extension == 'gif')
$gdImage = imagecreatefromgif($image);

$this->drawImage($gdImage, $xlsxFilePath, $spreadsheet, $inputFileType, $cellNo);

$cellNo++;




public function getImagePath($imageUrl, $mediaDirectory)
if ($imageUrl != '')
if ($this->fileExists($imageUrl))
return $imageUrl;
else
return $mediaDirectory . 'catalog/product/placeholder/' . $this->getPlaceholderImage();


return '';


public function getPlaceholderImage()
return $this->_storeManager->getStore()->getConfig('catalog/placeholder/image_placeholder');


public function fileExists($url)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($code == 200)
$status = true;
else
$status = false;

curl_close($ch);
return $status;


public function drawImage($gdImage, $filePath, $spreadsheet, $inputFileType, $cellNo)
$cellNo = $cellNo + 1;
$writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, $inputFileType);
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
$objDrawing = new PhpOfficePhpSpreadsheetWorksheetMemoryDrawing();
$objDrawing->setImageResource($gdImage);
$objDrawing->setRenderingFunction(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::RENDERING_PNG);
$objDrawing->setMimeType(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setCoordinates('A' . $cellNo);
$objDrawing->setOffsetX(0);
$objDrawing->setOffsetY(0);
$objDrawing->setHeight(96);
$objDrawing->setWidth(96);
if (empty((array) $objDrawing->getWorksheet()))
$objDrawing->setWorksheet($activeSheet);

$activeSheet->getRowDimension($cellNo)->setRowHeight(72);
$activeSheet->getColumnDimension('A')->setWidth(13.18);
$activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setVertical(PhpOfficePhpSpreadsheetStyleAlignment::VERTICAL_TOP);
$activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setHorizontal(PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_LEFT);
$activeSheet->getColumnDimension('B')->setAutoSize(TRUE);
foreach (range('C', 'J') as $columnID)
$activeSheet->getColumnDimension($columnID)->setAutoSize(false);
$activeSheet->getColumnDimension($columnID)->setWidth(15);
$activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setWrapText(true);


$writer->save($filePath);


public function getMediaPath()
return $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);








share|improve this answer



























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f284088%2fmagento-2-display-image-in-exported-excel-file-from-custom-grid%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I think you need to override vendor/magento/module-backend/Block/Widget/Grid/Export.php this File and check getExcelFile function



    And also see this exmple for adding image in Excel File



    Adding Image to the Excel






    share|improve this answer



























    • After implementing this code, images are still not showing in excel file.

      – Faisal Sheikh
      Aug 1 at 13:40











    • please check answer

      – Rk Rathod
      Aug 1 at 13:59











    • Now I am able to get image in exported excel file. Thank you for the suggestion.

      – Faisal Sheikh
      Aug 2 at 12:40












    • if you dont mind please attach code.. most welcome.. happy coding.. :)

      – Rk Rathod
      Aug 2 at 12:54











    • I have posted, you can see now.

      – Faisal Sheikh
      Aug 2 at 13:18















    1














    I think you need to override vendor/magento/module-backend/Block/Widget/Grid/Export.php this File and check getExcelFile function



    And also see this exmple for adding image in Excel File



    Adding Image to the Excel






    share|improve this answer



























    • After implementing this code, images are still not showing in excel file.

      – Faisal Sheikh
      Aug 1 at 13:40











    • please check answer

      – Rk Rathod
      Aug 1 at 13:59











    • Now I am able to get image in exported excel file. Thank you for the suggestion.

      – Faisal Sheikh
      Aug 2 at 12:40












    • if you dont mind please attach code.. most welcome.. happy coding.. :)

      – Rk Rathod
      Aug 2 at 12:54











    • I have posted, you can see now.

      – Faisal Sheikh
      Aug 2 at 13:18













    1












    1








    1







    I think you need to override vendor/magento/module-backend/Block/Widget/Grid/Export.php this File and check getExcelFile function



    And also see this exmple for adding image in Excel File



    Adding Image to the Excel






    share|improve this answer















    I think you need to override vendor/magento/module-backend/Block/Widget/Grid/Export.php this File and check getExcelFile function



    And also see this exmple for adding image in Excel File



    Adding Image to the Excel







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Aug 1 at 13:59

























    answered Aug 1 at 13:28









    Rk RathodRk Rathod

    2,8833 silver badges24 bronze badges




    2,8833 silver badges24 bronze badges















    • After implementing this code, images are still not showing in excel file.

      – Faisal Sheikh
      Aug 1 at 13:40











    • please check answer

      – Rk Rathod
      Aug 1 at 13:59











    • Now I am able to get image in exported excel file. Thank you for the suggestion.

      – Faisal Sheikh
      Aug 2 at 12:40












    • if you dont mind please attach code.. most welcome.. happy coding.. :)

      – Rk Rathod
      Aug 2 at 12:54











    • I have posted, you can see now.

      – Faisal Sheikh
      Aug 2 at 13:18

















    • After implementing this code, images are still not showing in excel file.

      – Faisal Sheikh
      Aug 1 at 13:40











    • please check answer

      – Rk Rathod
      Aug 1 at 13:59











    • Now I am able to get image in exported excel file. Thank you for the suggestion.

      – Faisal Sheikh
      Aug 2 at 12:40












    • if you dont mind please attach code.. most welcome.. happy coding.. :)

      – Rk Rathod
      Aug 2 at 12:54











    • I have posted, you can see now.

      – Faisal Sheikh
      Aug 2 at 13:18
















    After implementing this code, images are still not showing in excel file.

    – Faisal Sheikh
    Aug 1 at 13:40





    After implementing this code, images are still not showing in excel file.

    – Faisal Sheikh
    Aug 1 at 13:40













    please check answer

    – Rk Rathod
    Aug 1 at 13:59





    please check answer

    – Rk Rathod
    Aug 1 at 13:59













    Now I am able to get image in exported excel file. Thank you for the suggestion.

    – Faisal Sheikh
    Aug 2 at 12:40






    Now I am able to get image in exported excel file. Thank you for the suggestion.

    – Faisal Sheikh
    Aug 2 at 12:40














    if you dont mind please attach code.. most welcome.. happy coding.. :)

    – Rk Rathod
    Aug 2 at 12:54





    if you dont mind please attach code.. most welcome.. happy coding.. :)

    – Rk Rathod
    Aug 2 at 12:54













    I have posted, you can see now.

    – Faisal Sheikh
    Aug 2 at 13:18





    I have posted, you can see now.

    – Faisal Sheikh
    Aug 2 at 13:18













    0














    Finally, I got the image in my exported Excel file.
    Here is my exportExcel.php (Controller) code:



    <?php

    namespace VendornameModulenameControllerAdminhtmlReport;

    use MagentoFrameworkAppFilesystemDirectoryList;

    class exportExcel extends MagentoBackendAppAction

    /**
    * @var MagentoBackendModelSession
    */
    protected $_adminSession;

    /**
    * @var VendornameModulenameBlockAdminhtmlReportGrid
    */
    protected $_gridData;
    protected $resultPageFactory;
    protected $fileFactory;
    protected $_resultFactory;
    protected $_xlsx;
    protected $resultPage;


    /**
    *
    * @param MagentoBackendAppActionContext $context
    * @param MagentoFrameworkViewResultPageFactory $resultPageFactory
    */
    public function __construct(
    MagentoBackendAppActionContext $context,
    VendornameModulenameBlockAdminhtmlReportGrid $gridData,
    MagentoBackendModelSession $adminSession,
    MagentoFrameworkViewResultPageFactory $resultPageFactory,
    MagentoFrameworkControllerResultFactory $resultFactory,
    MagentoFrameworkAppResponseHttpFileFactory $fileFactory,
    MagentoFrameworkFilesystemDirectoryList $directoryList,
    MagentoFrameworkFilesystem $filesystem,
    MagentoFrameworkDataCollectionFactory $collectionFactory,
    PhpOfficePhpSpreadsheetWriterXlsx $xlsx,
    MagentoCatalogModelProductRepository $productRepository,
    MagentoStoreModelStoreManagerInterface $storeManager,
    MagentoCatalogHelperImage $productImageHelper
    )
    parent::__construct($context);
    $this->_gridData = $gridData;
    $this->_adminSession = $adminSession;
    $this->resultPageFactory = $resultPageFactory;
    $this->_fileFactory = $fileFactory;
    $this->_directoryList = $directoryList;
    $this->_filesystem = $filesystem;
    $this->_collectionFactory = $collectionFactory;
    $this->_xlsx = $xlsx;
    $this->_productRepository = $productRepository;
    $this->_storeManager = $storeManager;
    $this->_productImageHelper = $productImageHelper;
    $this->_resultFactory = $resultFactory;
    DEFINE('DS', DIRECTORY_SEPARATOR);


    /**
    *
    * @return type
    */
    public function execute()

    try
    $websiteId = 0;
    $productIds = [];
    $resultRedirect = $this->_resultFactory->create(MagentoFrameworkControllerResultFactory::TYPE_REDIRECT);
    $dataArray = $this->_adminSession->getData('ExportArray');
    $totalData = [];
    $i = 0;
    foreach($dataArray as $item)

    $totalData[$i]['image'] = '';
    $totalData[$i]['id'] = $item['id'];
    $totalData[$i]['name'] = $item['name'];
    $totalData[$i]['barcode'] = $item['barcode'];
    $totalData[$i]['retailprice'] = $item['retailprice'];
    $totalData[$i]['sku'] = $item['sku'];
    $totalData[$i]['store'] = $item['store'];
    $totalData[$i]['minqty'] = $item['minqty'];
    $totalData[$i]['maxqty'] = $item['maxqty'];
    $totalData[$i]['availqty'] = $item['availqty'];
    $i++;


    $headerColumns = array('0' => array('Product Image', 'Product ID', 'Product Name', 'Barcode', 'Retail Price', 'SKU', 'Store', 'Min QTY', 'Max QTY', 'Available QTY'));

    if (count($lowStockExportArray) == 0)
    $this->messageManager->addNoticeMessage(__('There is no data to export!'));
    $resultRedirect->setUrl($this->_redirect->getRefererUrl());
    return $resultRedirect;

    $excelData = array_merge($headerColumns, $totalData);
    $productIds = $this->getProductIds();
    $imageData = $this->processDataForXlsxImage($websiteId, $productIds);
    $xlsxFileName = 'file.xlsx';
    $xlsxFilePath = $this->getFilePath($xlsxFileName);
    $this->generateXlsx($excelData, $xlsxFilePath);
    $this->addImageToXlsx($imageData, $xlsxFilePath);
    $this->downloadXlsx($xlsxFilePath);
    catch (Exception $ex)
    $this->messageManager->addErrorMessage($ex->getMessage());



    public function getFilePath($fileName)
    return $this->_directoryList->getPath(MagentoFrameworkAppFilesystemDirectoryList::VAR_DIR) . "/folder_name/" . $fileName;


    public function generateXlsx($excelData, $filePath)
    $spreadsheet = new PhpOfficePhpSpreadsheetSpreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    $sheet->setTitle('Excel File');
    $sheet->fromArray($excelData);
    $writer = $this->_xlsx->setSpreadsheet($spreadsheet);
    $writer->save($filePath);


    public function downloadXlsx($xlsxFilePath)
    if (file_exists($xlsxFilePath))
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename=' . basename($xlsxFilePath));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($xlsxFilePath));
    ob_clean();
    flush();
    readfile($xlsxFilePath);



    public function getProductIds()
    $data = [];
    $arrayExport = $this->_adminSession->getData('ExportArray');
    if (count($arrayExport) > 0)
    foreach ($arrayExport as $value)
    $data[] = $value['id'];

    return $data;

    return $data;


    public function processDataForXlsxImage($store, $productIds)
    $result = [];
    $mediaDirectory = $this->getMediaPath();
    foreach ($productIds as $productId)
    $product = $this->_productRepository->getById($productId);
    $imageUrl = $this->_productImageHelper->init($product, 'product_page_image_thumbnail')->setImageFile($product->getThumbnail())->resize(70, 70)->getUrl();
    $result[] = $this->getImagePath($imageUrl, $mediaDirectory);

    return $result;


    public function addImageToXlsx($imageData, $xlsxFilePath)
    if (count($imageData))
    $reader = PhpOfficePhpSpreadsheetIOFactory::createReaderForFile($xlsxFilePath);
    $inputFileType = PhpOfficePhpSpreadsheetIOFactory::identify($xlsxFilePath);
    $reader->setReadDataOnly(true);
    $spreadsheet = $reader->load($xlsxFilePath);
    $cellNo = 1;
    foreach ($imageData as $image)
    if ($cellNo >= 1 && $image != '') $extension == 'jpeg')
    $gdImage = imagecreatefromjpeg($image);

    if ($extension == 'gif')
    $gdImage = imagecreatefromgif($image);

    $this->drawImage($gdImage, $xlsxFilePath, $spreadsheet, $inputFileType, $cellNo);

    $cellNo++;




    public function getImagePath($imageUrl, $mediaDirectory)
    if ($imageUrl != '')
    if ($this->fileExists($imageUrl))
    return $imageUrl;
    else
    return $mediaDirectory . 'catalog/product/placeholder/' . $this->getPlaceholderImage();


    return '';


    public function getPlaceholderImage()
    return $this->_storeManager->getStore()->getConfig('catalog/placeholder/image_placeholder');


    public function fileExists($url)
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 200)
    $status = true;
    else
    $status = false;

    curl_close($ch);
    return $status;


    public function drawImage($gdImage, $filePath, $spreadsheet, $inputFileType, $cellNo)
    $cellNo = $cellNo + 1;
    $writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, $inputFileType);
    $spreadsheet->setActiveSheetIndex(0);
    $activeSheet = $spreadsheet->getActiveSheet();
    $objDrawing = new PhpOfficePhpSpreadsheetWorksheetMemoryDrawing();
    $objDrawing->setImageResource($gdImage);
    $objDrawing->setRenderingFunction(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::RENDERING_PNG);
    $objDrawing->setMimeType(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::MIMETYPE_DEFAULT);
    $objDrawing->setCoordinates('A' . $cellNo);
    $objDrawing->setOffsetX(0);
    $objDrawing->setOffsetY(0);
    $objDrawing->setHeight(96);
    $objDrawing->setWidth(96);
    if (empty((array) $objDrawing->getWorksheet()))
    $objDrawing->setWorksheet($activeSheet);

    $activeSheet->getRowDimension($cellNo)->setRowHeight(72);
    $activeSheet->getColumnDimension('A')->setWidth(13.18);
    $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setVertical(PhpOfficePhpSpreadsheetStyleAlignment::VERTICAL_TOP);
    $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setHorizontal(PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_LEFT);
    $activeSheet->getColumnDimension('B')->setAutoSize(TRUE);
    foreach (range('C', 'J') as $columnID)
    $activeSheet->getColumnDimension($columnID)->setAutoSize(false);
    $activeSheet->getColumnDimension($columnID)->setWidth(15);
    $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setWrapText(true);


    $writer->save($filePath);


    public function getMediaPath()
    return $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);








    share|improve this answer





























      0














      Finally, I got the image in my exported Excel file.
      Here is my exportExcel.php (Controller) code:



      <?php

      namespace VendornameModulenameControllerAdminhtmlReport;

      use MagentoFrameworkAppFilesystemDirectoryList;

      class exportExcel extends MagentoBackendAppAction

      /**
      * @var MagentoBackendModelSession
      */
      protected $_adminSession;

      /**
      * @var VendornameModulenameBlockAdminhtmlReportGrid
      */
      protected $_gridData;
      protected $resultPageFactory;
      protected $fileFactory;
      protected $_resultFactory;
      protected $_xlsx;
      protected $resultPage;


      /**
      *
      * @param MagentoBackendAppActionContext $context
      * @param MagentoFrameworkViewResultPageFactory $resultPageFactory
      */
      public function __construct(
      MagentoBackendAppActionContext $context,
      VendornameModulenameBlockAdminhtmlReportGrid $gridData,
      MagentoBackendModelSession $adminSession,
      MagentoFrameworkViewResultPageFactory $resultPageFactory,
      MagentoFrameworkControllerResultFactory $resultFactory,
      MagentoFrameworkAppResponseHttpFileFactory $fileFactory,
      MagentoFrameworkFilesystemDirectoryList $directoryList,
      MagentoFrameworkFilesystem $filesystem,
      MagentoFrameworkDataCollectionFactory $collectionFactory,
      PhpOfficePhpSpreadsheetWriterXlsx $xlsx,
      MagentoCatalogModelProductRepository $productRepository,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoCatalogHelperImage $productImageHelper
      )
      parent::__construct($context);
      $this->_gridData = $gridData;
      $this->_adminSession = $adminSession;
      $this->resultPageFactory = $resultPageFactory;
      $this->_fileFactory = $fileFactory;
      $this->_directoryList = $directoryList;
      $this->_filesystem = $filesystem;
      $this->_collectionFactory = $collectionFactory;
      $this->_xlsx = $xlsx;
      $this->_productRepository = $productRepository;
      $this->_storeManager = $storeManager;
      $this->_productImageHelper = $productImageHelper;
      $this->_resultFactory = $resultFactory;
      DEFINE('DS', DIRECTORY_SEPARATOR);


      /**
      *
      * @return type
      */
      public function execute()

      try
      $websiteId = 0;
      $productIds = [];
      $resultRedirect = $this->_resultFactory->create(MagentoFrameworkControllerResultFactory::TYPE_REDIRECT);
      $dataArray = $this->_adminSession->getData('ExportArray');
      $totalData = [];
      $i = 0;
      foreach($dataArray as $item)

      $totalData[$i]['image'] = '';
      $totalData[$i]['id'] = $item['id'];
      $totalData[$i]['name'] = $item['name'];
      $totalData[$i]['barcode'] = $item['barcode'];
      $totalData[$i]['retailprice'] = $item['retailprice'];
      $totalData[$i]['sku'] = $item['sku'];
      $totalData[$i]['store'] = $item['store'];
      $totalData[$i]['minqty'] = $item['minqty'];
      $totalData[$i]['maxqty'] = $item['maxqty'];
      $totalData[$i]['availqty'] = $item['availqty'];
      $i++;


      $headerColumns = array('0' => array('Product Image', 'Product ID', 'Product Name', 'Barcode', 'Retail Price', 'SKU', 'Store', 'Min QTY', 'Max QTY', 'Available QTY'));

      if (count($lowStockExportArray) == 0)
      $this->messageManager->addNoticeMessage(__('There is no data to export!'));
      $resultRedirect->setUrl($this->_redirect->getRefererUrl());
      return $resultRedirect;

      $excelData = array_merge($headerColumns, $totalData);
      $productIds = $this->getProductIds();
      $imageData = $this->processDataForXlsxImage($websiteId, $productIds);
      $xlsxFileName = 'file.xlsx';
      $xlsxFilePath = $this->getFilePath($xlsxFileName);
      $this->generateXlsx($excelData, $xlsxFilePath);
      $this->addImageToXlsx($imageData, $xlsxFilePath);
      $this->downloadXlsx($xlsxFilePath);
      catch (Exception $ex)
      $this->messageManager->addErrorMessage($ex->getMessage());



      public function getFilePath($fileName)
      return $this->_directoryList->getPath(MagentoFrameworkAppFilesystemDirectoryList::VAR_DIR) . "/folder_name/" . $fileName;


      public function generateXlsx($excelData, $filePath)
      $spreadsheet = new PhpOfficePhpSpreadsheetSpreadsheet();
      $sheet = $spreadsheet->getActiveSheet();

      $sheet->setTitle('Excel File');
      $sheet->fromArray($excelData);
      $writer = $this->_xlsx->setSpreadsheet($spreadsheet);
      $writer->save($filePath);


      public function downloadXlsx($xlsxFilePath)
      if (file_exists($xlsxFilePath))
      header('Content-Description: File Transfer');
      header('Content-Type: application/vnd.ms-excel');
      header('Content-Disposition: attachment; filename=' . basename($xlsxFilePath));
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($xlsxFilePath));
      ob_clean();
      flush();
      readfile($xlsxFilePath);



      public function getProductIds()
      $data = [];
      $arrayExport = $this->_adminSession->getData('ExportArray');
      if (count($arrayExport) > 0)
      foreach ($arrayExport as $value)
      $data[] = $value['id'];

      return $data;

      return $data;


      public function processDataForXlsxImage($store, $productIds)
      $result = [];
      $mediaDirectory = $this->getMediaPath();
      foreach ($productIds as $productId)
      $product = $this->_productRepository->getById($productId);
      $imageUrl = $this->_productImageHelper->init($product, 'product_page_image_thumbnail')->setImageFile($product->getThumbnail())->resize(70, 70)->getUrl();
      $result[] = $this->getImagePath($imageUrl, $mediaDirectory);

      return $result;


      public function addImageToXlsx($imageData, $xlsxFilePath)
      if (count($imageData))
      $reader = PhpOfficePhpSpreadsheetIOFactory::createReaderForFile($xlsxFilePath);
      $inputFileType = PhpOfficePhpSpreadsheetIOFactory::identify($xlsxFilePath);
      $reader->setReadDataOnly(true);
      $spreadsheet = $reader->load($xlsxFilePath);
      $cellNo = 1;
      foreach ($imageData as $image)
      if ($cellNo >= 1 && $image != '') $extension == 'jpeg')
      $gdImage = imagecreatefromjpeg($image);

      if ($extension == 'gif')
      $gdImage = imagecreatefromgif($image);

      $this->drawImage($gdImage, $xlsxFilePath, $spreadsheet, $inputFileType, $cellNo);

      $cellNo++;




      public function getImagePath($imageUrl, $mediaDirectory)
      if ($imageUrl != '')
      if ($this->fileExists($imageUrl))
      return $imageUrl;
      else
      return $mediaDirectory . 'catalog/product/placeholder/' . $this->getPlaceholderImage();


      return '';


      public function getPlaceholderImage()
      return $this->_storeManager->getStore()->getConfig('catalog/placeholder/image_placeholder');


      public function fileExists($url)
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_NOBODY, true);
      curl_exec($ch);
      $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      if ($code == 200)
      $status = true;
      else
      $status = false;

      curl_close($ch);
      return $status;


      public function drawImage($gdImage, $filePath, $spreadsheet, $inputFileType, $cellNo)
      $cellNo = $cellNo + 1;
      $writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, $inputFileType);
      $spreadsheet->setActiveSheetIndex(0);
      $activeSheet = $spreadsheet->getActiveSheet();
      $objDrawing = new PhpOfficePhpSpreadsheetWorksheetMemoryDrawing();
      $objDrawing->setImageResource($gdImage);
      $objDrawing->setRenderingFunction(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::RENDERING_PNG);
      $objDrawing->setMimeType(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::MIMETYPE_DEFAULT);
      $objDrawing->setCoordinates('A' . $cellNo);
      $objDrawing->setOffsetX(0);
      $objDrawing->setOffsetY(0);
      $objDrawing->setHeight(96);
      $objDrawing->setWidth(96);
      if (empty((array) $objDrawing->getWorksheet()))
      $objDrawing->setWorksheet($activeSheet);

      $activeSheet->getRowDimension($cellNo)->setRowHeight(72);
      $activeSheet->getColumnDimension('A')->setWidth(13.18);
      $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setVertical(PhpOfficePhpSpreadsheetStyleAlignment::VERTICAL_TOP);
      $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setHorizontal(PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_LEFT);
      $activeSheet->getColumnDimension('B')->setAutoSize(TRUE);
      foreach (range('C', 'J') as $columnID)
      $activeSheet->getColumnDimension($columnID)->setAutoSize(false);
      $activeSheet->getColumnDimension($columnID)->setWidth(15);
      $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setWrapText(true);


      $writer->save($filePath);


      public function getMediaPath()
      return $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);








      share|improve this answer



























        0












        0








        0







        Finally, I got the image in my exported Excel file.
        Here is my exportExcel.php (Controller) code:



        <?php

        namespace VendornameModulenameControllerAdminhtmlReport;

        use MagentoFrameworkAppFilesystemDirectoryList;

        class exportExcel extends MagentoBackendAppAction

        /**
        * @var MagentoBackendModelSession
        */
        protected $_adminSession;

        /**
        * @var VendornameModulenameBlockAdminhtmlReportGrid
        */
        protected $_gridData;
        protected $resultPageFactory;
        protected $fileFactory;
        protected $_resultFactory;
        protected $_xlsx;
        protected $resultPage;


        /**
        *
        * @param MagentoBackendAppActionContext $context
        * @param MagentoFrameworkViewResultPageFactory $resultPageFactory
        */
        public function __construct(
        MagentoBackendAppActionContext $context,
        VendornameModulenameBlockAdminhtmlReportGrid $gridData,
        MagentoBackendModelSession $adminSession,
        MagentoFrameworkViewResultPageFactory $resultPageFactory,
        MagentoFrameworkControllerResultFactory $resultFactory,
        MagentoFrameworkAppResponseHttpFileFactory $fileFactory,
        MagentoFrameworkFilesystemDirectoryList $directoryList,
        MagentoFrameworkFilesystem $filesystem,
        MagentoFrameworkDataCollectionFactory $collectionFactory,
        PhpOfficePhpSpreadsheetWriterXlsx $xlsx,
        MagentoCatalogModelProductRepository $productRepository,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoCatalogHelperImage $productImageHelper
        )
        parent::__construct($context);
        $this->_gridData = $gridData;
        $this->_adminSession = $adminSession;
        $this->resultPageFactory = $resultPageFactory;
        $this->_fileFactory = $fileFactory;
        $this->_directoryList = $directoryList;
        $this->_filesystem = $filesystem;
        $this->_collectionFactory = $collectionFactory;
        $this->_xlsx = $xlsx;
        $this->_productRepository = $productRepository;
        $this->_storeManager = $storeManager;
        $this->_productImageHelper = $productImageHelper;
        $this->_resultFactory = $resultFactory;
        DEFINE('DS', DIRECTORY_SEPARATOR);


        /**
        *
        * @return type
        */
        public function execute()

        try
        $websiteId = 0;
        $productIds = [];
        $resultRedirect = $this->_resultFactory->create(MagentoFrameworkControllerResultFactory::TYPE_REDIRECT);
        $dataArray = $this->_adminSession->getData('ExportArray');
        $totalData = [];
        $i = 0;
        foreach($dataArray as $item)

        $totalData[$i]['image'] = '';
        $totalData[$i]['id'] = $item['id'];
        $totalData[$i]['name'] = $item['name'];
        $totalData[$i]['barcode'] = $item['barcode'];
        $totalData[$i]['retailprice'] = $item['retailprice'];
        $totalData[$i]['sku'] = $item['sku'];
        $totalData[$i]['store'] = $item['store'];
        $totalData[$i]['minqty'] = $item['minqty'];
        $totalData[$i]['maxqty'] = $item['maxqty'];
        $totalData[$i]['availqty'] = $item['availqty'];
        $i++;


        $headerColumns = array('0' => array('Product Image', 'Product ID', 'Product Name', 'Barcode', 'Retail Price', 'SKU', 'Store', 'Min QTY', 'Max QTY', 'Available QTY'));

        if (count($lowStockExportArray) == 0)
        $this->messageManager->addNoticeMessage(__('There is no data to export!'));
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;

        $excelData = array_merge($headerColumns, $totalData);
        $productIds = $this->getProductIds();
        $imageData = $this->processDataForXlsxImage($websiteId, $productIds);
        $xlsxFileName = 'file.xlsx';
        $xlsxFilePath = $this->getFilePath($xlsxFileName);
        $this->generateXlsx($excelData, $xlsxFilePath);
        $this->addImageToXlsx($imageData, $xlsxFilePath);
        $this->downloadXlsx($xlsxFilePath);
        catch (Exception $ex)
        $this->messageManager->addErrorMessage($ex->getMessage());



        public function getFilePath($fileName)
        return $this->_directoryList->getPath(MagentoFrameworkAppFilesystemDirectoryList::VAR_DIR) . "/folder_name/" . $fileName;


        public function generateXlsx($excelData, $filePath)
        $spreadsheet = new PhpOfficePhpSpreadsheetSpreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->setTitle('Excel File');
        $sheet->fromArray($excelData);
        $writer = $this->_xlsx->setSpreadsheet($spreadsheet);
        $writer->save($filePath);


        public function downloadXlsx($xlsxFilePath)
        if (file_exists($xlsxFilePath))
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename=' . basename($xlsxFilePath));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($xlsxFilePath));
        ob_clean();
        flush();
        readfile($xlsxFilePath);



        public function getProductIds()
        $data = [];
        $arrayExport = $this->_adminSession->getData('ExportArray');
        if (count($arrayExport) > 0)
        foreach ($arrayExport as $value)
        $data[] = $value['id'];

        return $data;

        return $data;


        public function processDataForXlsxImage($store, $productIds)
        $result = [];
        $mediaDirectory = $this->getMediaPath();
        foreach ($productIds as $productId)
        $product = $this->_productRepository->getById($productId);
        $imageUrl = $this->_productImageHelper->init($product, 'product_page_image_thumbnail')->setImageFile($product->getThumbnail())->resize(70, 70)->getUrl();
        $result[] = $this->getImagePath($imageUrl, $mediaDirectory);

        return $result;


        public function addImageToXlsx($imageData, $xlsxFilePath)
        if (count($imageData))
        $reader = PhpOfficePhpSpreadsheetIOFactory::createReaderForFile($xlsxFilePath);
        $inputFileType = PhpOfficePhpSpreadsheetIOFactory::identify($xlsxFilePath);
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($xlsxFilePath);
        $cellNo = 1;
        foreach ($imageData as $image)
        if ($cellNo >= 1 && $image != '') $extension == 'jpeg')
        $gdImage = imagecreatefromjpeg($image);

        if ($extension == 'gif')
        $gdImage = imagecreatefromgif($image);

        $this->drawImage($gdImage, $xlsxFilePath, $spreadsheet, $inputFileType, $cellNo);

        $cellNo++;




        public function getImagePath($imageUrl, $mediaDirectory)
        if ($imageUrl != '')
        if ($this->fileExists($imageUrl))
        return $imageUrl;
        else
        return $mediaDirectory . 'catalog/product/placeholder/' . $this->getPlaceholderImage();


        return '';


        public function getPlaceholderImage()
        return $this->_storeManager->getStore()->getConfig('catalog/placeholder/image_placeholder');


        public function fileExists($url)
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($code == 200)
        $status = true;
        else
        $status = false;

        curl_close($ch);
        return $status;


        public function drawImage($gdImage, $filePath, $spreadsheet, $inputFileType, $cellNo)
        $cellNo = $cellNo + 1;
        $writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, $inputFileType);
        $spreadsheet->setActiveSheetIndex(0);
        $activeSheet = $spreadsheet->getActiveSheet();
        $objDrawing = new PhpOfficePhpSpreadsheetWorksheetMemoryDrawing();
        $objDrawing->setImageResource($gdImage);
        $objDrawing->setRenderingFunction(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::RENDERING_PNG);
        $objDrawing->setMimeType(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::MIMETYPE_DEFAULT);
        $objDrawing->setCoordinates('A' . $cellNo);
        $objDrawing->setOffsetX(0);
        $objDrawing->setOffsetY(0);
        $objDrawing->setHeight(96);
        $objDrawing->setWidth(96);
        if (empty((array) $objDrawing->getWorksheet()))
        $objDrawing->setWorksheet($activeSheet);

        $activeSheet->getRowDimension($cellNo)->setRowHeight(72);
        $activeSheet->getColumnDimension('A')->setWidth(13.18);
        $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setVertical(PhpOfficePhpSpreadsheetStyleAlignment::VERTICAL_TOP);
        $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setHorizontal(PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_LEFT);
        $activeSheet->getColumnDimension('B')->setAutoSize(TRUE);
        foreach (range('C', 'J') as $columnID)
        $activeSheet->getColumnDimension($columnID)->setAutoSize(false);
        $activeSheet->getColumnDimension($columnID)->setWidth(15);
        $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setWrapText(true);


        $writer->save($filePath);


        public function getMediaPath()
        return $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);








        share|improve this answer













        Finally, I got the image in my exported Excel file.
        Here is my exportExcel.php (Controller) code:



        <?php

        namespace VendornameModulenameControllerAdminhtmlReport;

        use MagentoFrameworkAppFilesystemDirectoryList;

        class exportExcel extends MagentoBackendAppAction

        /**
        * @var MagentoBackendModelSession
        */
        protected $_adminSession;

        /**
        * @var VendornameModulenameBlockAdminhtmlReportGrid
        */
        protected $_gridData;
        protected $resultPageFactory;
        protected $fileFactory;
        protected $_resultFactory;
        protected $_xlsx;
        protected $resultPage;


        /**
        *
        * @param MagentoBackendAppActionContext $context
        * @param MagentoFrameworkViewResultPageFactory $resultPageFactory
        */
        public function __construct(
        MagentoBackendAppActionContext $context,
        VendornameModulenameBlockAdminhtmlReportGrid $gridData,
        MagentoBackendModelSession $adminSession,
        MagentoFrameworkViewResultPageFactory $resultPageFactory,
        MagentoFrameworkControllerResultFactory $resultFactory,
        MagentoFrameworkAppResponseHttpFileFactory $fileFactory,
        MagentoFrameworkFilesystemDirectoryList $directoryList,
        MagentoFrameworkFilesystem $filesystem,
        MagentoFrameworkDataCollectionFactory $collectionFactory,
        PhpOfficePhpSpreadsheetWriterXlsx $xlsx,
        MagentoCatalogModelProductRepository $productRepository,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoCatalogHelperImage $productImageHelper
        )
        parent::__construct($context);
        $this->_gridData = $gridData;
        $this->_adminSession = $adminSession;
        $this->resultPageFactory = $resultPageFactory;
        $this->_fileFactory = $fileFactory;
        $this->_directoryList = $directoryList;
        $this->_filesystem = $filesystem;
        $this->_collectionFactory = $collectionFactory;
        $this->_xlsx = $xlsx;
        $this->_productRepository = $productRepository;
        $this->_storeManager = $storeManager;
        $this->_productImageHelper = $productImageHelper;
        $this->_resultFactory = $resultFactory;
        DEFINE('DS', DIRECTORY_SEPARATOR);


        /**
        *
        * @return type
        */
        public function execute()

        try
        $websiteId = 0;
        $productIds = [];
        $resultRedirect = $this->_resultFactory->create(MagentoFrameworkControllerResultFactory::TYPE_REDIRECT);
        $dataArray = $this->_adminSession->getData('ExportArray');
        $totalData = [];
        $i = 0;
        foreach($dataArray as $item)

        $totalData[$i]['image'] = '';
        $totalData[$i]['id'] = $item['id'];
        $totalData[$i]['name'] = $item['name'];
        $totalData[$i]['barcode'] = $item['barcode'];
        $totalData[$i]['retailprice'] = $item['retailprice'];
        $totalData[$i]['sku'] = $item['sku'];
        $totalData[$i]['store'] = $item['store'];
        $totalData[$i]['minqty'] = $item['minqty'];
        $totalData[$i]['maxqty'] = $item['maxqty'];
        $totalData[$i]['availqty'] = $item['availqty'];
        $i++;


        $headerColumns = array('0' => array('Product Image', 'Product ID', 'Product Name', 'Barcode', 'Retail Price', 'SKU', 'Store', 'Min QTY', 'Max QTY', 'Available QTY'));

        if (count($lowStockExportArray) == 0)
        $this->messageManager->addNoticeMessage(__('There is no data to export!'));
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;

        $excelData = array_merge($headerColumns, $totalData);
        $productIds = $this->getProductIds();
        $imageData = $this->processDataForXlsxImage($websiteId, $productIds);
        $xlsxFileName = 'file.xlsx';
        $xlsxFilePath = $this->getFilePath($xlsxFileName);
        $this->generateXlsx($excelData, $xlsxFilePath);
        $this->addImageToXlsx($imageData, $xlsxFilePath);
        $this->downloadXlsx($xlsxFilePath);
        catch (Exception $ex)
        $this->messageManager->addErrorMessage($ex->getMessage());



        public function getFilePath($fileName)
        return $this->_directoryList->getPath(MagentoFrameworkAppFilesystemDirectoryList::VAR_DIR) . "/folder_name/" . $fileName;


        public function generateXlsx($excelData, $filePath)
        $spreadsheet = new PhpOfficePhpSpreadsheetSpreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->setTitle('Excel File');
        $sheet->fromArray($excelData);
        $writer = $this->_xlsx->setSpreadsheet($spreadsheet);
        $writer->save($filePath);


        public function downloadXlsx($xlsxFilePath)
        if (file_exists($xlsxFilePath))
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename=' . basename($xlsxFilePath));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($xlsxFilePath));
        ob_clean();
        flush();
        readfile($xlsxFilePath);



        public function getProductIds()
        $data = [];
        $arrayExport = $this->_adminSession->getData('ExportArray');
        if (count($arrayExport) > 0)
        foreach ($arrayExport as $value)
        $data[] = $value['id'];

        return $data;

        return $data;


        public function processDataForXlsxImage($store, $productIds)
        $result = [];
        $mediaDirectory = $this->getMediaPath();
        foreach ($productIds as $productId)
        $product = $this->_productRepository->getById($productId);
        $imageUrl = $this->_productImageHelper->init($product, 'product_page_image_thumbnail')->setImageFile($product->getThumbnail())->resize(70, 70)->getUrl();
        $result[] = $this->getImagePath($imageUrl, $mediaDirectory);

        return $result;


        public function addImageToXlsx($imageData, $xlsxFilePath)
        if (count($imageData))
        $reader = PhpOfficePhpSpreadsheetIOFactory::createReaderForFile($xlsxFilePath);
        $inputFileType = PhpOfficePhpSpreadsheetIOFactory::identify($xlsxFilePath);
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($xlsxFilePath);
        $cellNo = 1;
        foreach ($imageData as $image)
        if ($cellNo >= 1 && $image != '') $extension == 'jpeg')
        $gdImage = imagecreatefromjpeg($image);

        if ($extension == 'gif')
        $gdImage = imagecreatefromgif($image);

        $this->drawImage($gdImage, $xlsxFilePath, $spreadsheet, $inputFileType, $cellNo);

        $cellNo++;




        public function getImagePath($imageUrl, $mediaDirectory)
        if ($imageUrl != '')
        if ($this->fileExists($imageUrl))
        return $imageUrl;
        else
        return $mediaDirectory . 'catalog/product/placeholder/' . $this->getPlaceholderImage();


        return '';


        public function getPlaceholderImage()
        return $this->_storeManager->getStore()->getConfig('catalog/placeholder/image_placeholder');


        public function fileExists($url)
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($code == 200)
        $status = true;
        else
        $status = false;

        curl_close($ch);
        return $status;


        public function drawImage($gdImage, $filePath, $spreadsheet, $inputFileType, $cellNo)
        $cellNo = $cellNo + 1;
        $writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, $inputFileType);
        $spreadsheet->setActiveSheetIndex(0);
        $activeSheet = $spreadsheet->getActiveSheet();
        $objDrawing = new PhpOfficePhpSpreadsheetWorksheetMemoryDrawing();
        $objDrawing->setImageResource($gdImage);
        $objDrawing->setRenderingFunction(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::RENDERING_PNG);
        $objDrawing->setMimeType(PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::MIMETYPE_DEFAULT);
        $objDrawing->setCoordinates('A' . $cellNo);
        $objDrawing->setOffsetX(0);
        $objDrawing->setOffsetY(0);
        $objDrawing->setHeight(96);
        $objDrawing->setWidth(96);
        if (empty((array) $objDrawing->getWorksheet()))
        $objDrawing->setWorksheet($activeSheet);

        $activeSheet->getRowDimension($cellNo)->setRowHeight(72);
        $activeSheet->getColumnDimension('A')->setWidth(13.18);
        $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setVertical(PhpOfficePhpSpreadsheetStyleAlignment::VERTICAL_TOP);
        $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setHorizontal(PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_LEFT);
        $activeSheet->getColumnDimension('B')->setAutoSize(TRUE);
        foreach (range('C', 'J') as $columnID)
        $activeSheet->getColumnDimension($columnID)->setAutoSize(false);
        $activeSheet->getColumnDimension($columnID)->setWidth(15);
        $activeSheet->getStyle('B1:J' . $spreadsheet->setActiveSheetIndex(0)->getHighestRow())->getAlignment()->setWrapText(true);


        $writer->save($filePath);


        public function getMediaPath()
        return $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);









        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Aug 2 at 13:17









        Faisal SheikhFaisal Sheikh

        4071 silver badge12 bronze badges




        4071 silver badge12 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f284088%2fmagento-2-display-image-in-exported-excel-file-from-custom-grid%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form