7

How to include third party library like php xlsx library in Magento 2?

Since last 7 days I am browsing in google and I could not found any information.

Magento 2 give default framework module like parser, logger etc, I need to add export report in xlsx format in this case how to do it?

4
  • 1
    you want to add js library or php library? Feb 8, 2016 at 10:40
  • @shaheer ali php library Feb 8, 2016 at 11:14
  • place your php lib files into lib folder of the magetno or in your module folder and then include in your module file using require_once('path_to_your_lib_file'); Feb 8, 2016 at 11:25
  • @shaheer ,let me clarify :-i am creating custom libraries, for example take framework , we can extend \Magento\Framework\App\Action\Action right, in that way only i need to extend lib files like Magento\Framework\custom_library\library.(using require_once is different in this case) Feb 8, 2016 at 11:33

4 Answers 4

5

below is the steps to create custom lib

in this i will take PHpexcel lib

  1. download the lib https://github.com/PHPOffice/PHPExcel/tree/1.8/Classes

  2. keep the folder in lib/internal

  3. open PHPExcel.php and change the class name to Phpexcel_PHPExcel

  4. in side PHPExcel folder lot of function initialization PHPExcel change it to Phpexcel_PHPExcel else it ill through error ex lib\internal\Phpexcel\PHPExcel\Calculation.php __construct and getInstance function all PHPExcel change to Phpexcel_PHPExcel like this change in all place

  5. where ever your using use like

    use Phpexcel_PHPExcel;
    use Phpexcel_PHPExcel_IOFactory;   
    

    and inside __construct

    Phpexcel_PHPExcel $xlsx,
    $this->excelFactory = $excelFactory;
    

    as like example you can build xlsx file

    public function getXlsxFile(){
    
        $component = $this->filter->getComponent();
    
        $name = md5(microtime());
        $file = 'export/'. $component->getName() . $name . '.xml';
    
        $this->filter->prepareComponent($component);
        $this->filter->applySelectionOnTargetProvider();
    
        /** @var SearchResultInterface $searchResult */
        $component->getContext()->getDataProvider()->setLimit(0, 999999);
        $searchResult = $component->getContext()->getDataProvider()->getSearchResult();
    
        $this->prepareItems($component->getName(), $searchResult->getItems());
    
        /** @var SearchResultIterator $searchResultIterator */
        $searchResultIterator = $this->iteratorFactory->create(['items' => $searchResult->getItems()]);
        $filterDataArr = '';
        foreach($searchResultIterator as $dataRow){
            $filterDataArr[]= $dataRow->getData();
        }
    
        $excelDataArray = '';
        $sheetTitle = 'export';
        $HeadersArray = $this->metadataProvider->getHeaders($component);     
        $FieldsArray = $this->metadataProvider->getFields($component);
        if(($key = array_search('actions', $FieldsArray)) !== false) {
            unset($FieldsArray[$key]);
        }
    
        if($component->getData('worksheetlabel')){
             $sheetTitle = $component->getData('worksheetlabel');
        }
    
        $hPos = 0;
        foreach($HeadersArray as $key =>$value){
            $excelDataArray[$hPos][$key] = $value;
        }
    
        $dPos = 1;
        if(count($filterDataArr) > 1){
            foreach($filterDataArr as $Filterdata){
                foreach($FieldsArray as $key=>$value){
                        $excelDataArray[$dPos][$key] = $Filterdata[$value];
                }
                $dPos++;
            }
        }
    
        $this->_Xlsx->getActiveSheet()->fromArray($excelDataArray, null, 'A1' );
    
        $this->_Xlsx->getActiveSheet()->setTitle($sheetTitle);
        $this->_Xlsx->setActiveSheetIndex(0);
        $callStartTime = microtime(true);
    
        $name = md5(microtime());
        $file = '/export/'. $component->getName() . $name . '.xlsx';
    
        $this->directory->create('export');
        $objWriter = Phpexcel_PHPExcel_IOFactory::createWriter($this->_Xlsx, 'Excel2007');
        $filepath = $this->directory->getAbsolutePath($file);
        $objWriter->save($filepath);
    
        return [
            'type' => 'filename',
            'value' => $file,
            'rm' => true  // can delete file after use
        ];
    }
    
2
  • 1
    In my opinion, lib/internal should not be touched. You can create lib/external instead.
    – MagePsycho
    Mar 21, 2017 at 8:45
  • Hello @peadeep , I want to add fPDF lib but not working fpdf.org as you told. Please suggest me proper way. Aug 16, 2017 at 3:52
2

what library exactly do you want to install?

The first result on google searching for php xlsx library gave me this: https://github.com/PHPOffice/PHPExcel

Since its registered on packagist https://packagist.org/packages/phpoffice/phpexcel

you can easily install it into your magento2 instance with the following shell command (from your magento2 root dir):

composer require phpoffice/phpexcel

If you are using it in a Magento Extension you should require the library in your Modules composer.json File, so it always is automatically installed when your Extension is installed.

The Autoloading will be handled by composer then

4
  • i want to include this library phpexcel.codeplex.com Feb 8, 2016 at 12:11
  • github.com/PHPOffice/PHPExcel actually looks like a modernized, composer compliant version of this :o. maybe you try it out? Feb 8, 2016 at 12:16
  • @DavidVerholen :- once we download the xlxs lib and save in lib folder now how to use it in controller or model file, is it right way include file model as Shaheer Ali told or write our own framework module as logger framework module is created Feb 9, 2016 at 3:51
  • you don't have to download it manually. just install it with composer and you are good. you can then get an instance of the library as easy as any other magento class with the constructor dependency injection Feb 9, 2016 at 7:08
1

Place your php library files in lib folder of magento e.g your_magento/lib/phpxls Now on top of your module file include the lib file using the below code

$object_manager = Magento\Core\Model\ObjectManager::getInstance();
$dir = $object_manager->get('Magento\App\Dir');            
$base = $dir->getDir();
$lib_file = $base.'lib/phpxls/your_lib_file.php'
require_once($lib_file);

Edit Create a file in your module helper folder e.g Mycustomlib.php Now put the above code in start of Mycustomlib.php file looks like

$object_manager = Magento\Core\Model\ObjectManager::getInstance();
$dir = $object_manager->get('Magento\App\Dir');            
$base = $dir->getDir();
$lib_file = $base.'lib/phpxls/your_lib_file.php'
require_once($lib_file);
namespace Yournamespace\Module\Helper;

class Mycustomlib extends Yourlibclass
{ 
}

you can extend the Mycustomlib where you want in your module

6
  • 1
    but in this case we need to include in every files in which file needed this .but magento 2 libraries are loaded automatically that way we need to configure right.. i want to load custom libraries at config level or auto load level. Feb 8, 2016 at 11:39
  • you can use another approach . you can extend your model/helper file from your lib files and then you can use your model/helper file Feb 8, 2016 at 11:51
  • if you don't mind, can you explain clearly. because i am new to magento 2 Feb 8, 2016 at 11:55
  • 1
    check my answer now Feb 8, 2016 at 12:04
  • 1
    This will not work. namespace should be first line in code file.
    – Arvind07
    Aug 25, 2016 at 12:44
1

Magento 2 supports composer installation for both modules and 3rd Party packages.

PhpExcel is deprecated now and the new PhpSpreadsheet should be use.

For installation via composer:

composer require phpoffice/phpspreadsheet

For Reference: phpspreadsheet.readthedocs.io

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.