Skip to main content
edited title
Link

controller is not overwriting in adminhtml. I have added in di.xml , Thanks in advance

Controller File:

 <?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Controller\ResultFactory;
use Sm\Customerprice\Model\Customerprice;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use \Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Mail\Message;
use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Mail\TransportInterfaceFactory;
use Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice\Mail\Template\TransportBuilder;

require_once BP . '/lib/internal/Phpexcel/PHPExcel.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/IOFactory.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/Writer/Excel2007.php';


$rendererLibrary = 'mPDF5.4';

$rendererLibraryPath = '/lib/internal/MPDF57/.' . $rendererLibrary;

class Email extends \Magento\Backend\App\Action
{

    
    protected $resultForwardFactory;
    private $_transportBuilder;
    
    
    public function __construct(

        \Magento\Backend\App\Action\Context $context,
        //\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
        PageFactory $resultPageFactory,
        CollectionFactory $salesOrderCollectionFactory,
        Customerprice $customerPrice,
        TransportBuilder $transportBuilder
    ) {
        $this->resultPageFactory = $resultPageFactory;
        //$this->_fileFactory = $fileFactory;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->salesOrderCollectionFactory = $salesOrderCollectionFactory;
        $this->customerPrice = $customerPrice;
        $this->_transportBuilder = $transportBuilder;
        parent::__construct($context,$resultForwardFactory);
        
    }

    /**
     * Notify user
     *
     * @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {

        $invoiceId = $this->getRequest()->getParam('invoice_id'); 

        if ($invoiceId) {
            
            $invoice = $this->_objectManager->create('Magento\Sales\Api\InvoiceRepositoryInterface')->get($invoiceId);
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); 
                $base = $dir->getRoot();
                $path = $base."/document/attachment/".$invoice->getIncrementId().'.xlsx';
            if ($invoice) {
            try{                
          
                $excelPath = $this->createExcel($invoice);
                $storeManager = $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface');
                $baseUrl = $storeManager->getStore()->getBaseUrl();
                
                
                $filePath =  $baseUrl . $excelPath[0]; 
                
                //header("Location: $filePath");
                
                if (!$invoice) {
                    return $this->resultForwardFactory->create()->forward('noroute');
                }

                //$this->_objectManager->create('Magento\Sales\Api\InvoiceManagementInterface')->notify($invoice->getEntityId());
            $resource        = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');
            $connection      = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

              $invoiceItemsGrid = $connection->fetchAll("SELECT order_increment_id FROM sales_invoice_grid WHERE entity_id = '".$invoice->getEntityId()."' ");
                
                $templateParams=array('invoice' => $invoice->getIncrementId() , 
                'order' => $invoiceItemsGrid[0]['order_increment_id'] , 
                'BillingAddressFirstName' => $excelPath[1]->getFirstName() ,
                'BillingAddressLastName' => $excelPath[1]->getLastName(),
                'CompanyBillingAddress' => $excelPath[1]->getCompany(),
                'StreetBillingAddress'=> $excelPath[1]['street'],
                'CityBillingAddress'=> $excelPath[1]->getCity(),
                'RegionBillingAddress'=> $excelPath[1]->getRegion(),
                'postCodeBillingAddress'=> $excelPath[1]->getPostCode(),
                'CountryBillingAddress'=> $excelPath[1]->getCountryId(),
                'TelephoneBillingAddress'=> $excelPath[1]->getTelephone(),
                'ShippingAddressFirstName'=> $excelPath[2]->getFirstName(),
                'ShippingAddressLastName'=> $excelPath[2]->getLastName(),
                'CompanyShippingAddress'=> $excelPath[2]->getCompany(),
                'StreetShippingAddress'=> $excelPath[1]['street'],
                'CityShippingAddress'=> $excelPath[2]->getCity(),
                'RegionShippingAddress'=> $excelPath[2]->getRegion(),
                'postCodeShippingAddress'=> $excelPath[2]->getPostCode(),
                'CountryShippingAddress'=> $excelPath[2]->getCountryId(),
                'TelephoneShippingAddress'=> $excelPath[2]->getTelephone()
                );   
                $transport = $this->_transportBuilder;
                    $transport->setTemplateIdentifier('sales_email_invoice_template');
                    $transport->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1));
                    $transport->setTemplateVars($templateParams);
                    $transport->setFrom(array('name' => 'Sales','email' => '[email protected]'));
                    $transport->setReplyTo('[email protected]');
                    $transport->addTo($excelPath[3]);
               
               $transport->addAttachment(file_get_contents($path),'application/octet-stream','attachment','base64',$invoice->getIncrementId().'.xlsx'); 

                 

            $transport->getTransport()->sendMessage();
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);   
            $this->messageManager->addSuccess(__('You sent the message.')); 
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect; 
                    
        }catch(\Exception $e){
            print_r($e->getMessage());exit;
        }   
                
                die();
            
            }
            else 
            {
                return $this->resultForwardFactory->create()->forward('noroute');
            }
        }           

    }
    
    public function createExcel(\Magento\Sales\Model\Order\Invoice $invoice)
    {
            
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load("//var/www/html/magento/app/code/Sm/Templates/KlauzInvoicePdf.xlsx");
        $xlsName = $invoice->getIncrementId().'.xlsx';

        //echo $xlsName;
        
        $orderId = $invoice->getOrderId();


        $invoiceNumber = $invoice->getInvoiceNumber();
        //echo "Invoice number ".$invoiceNumber ;
        $createdAt = $invoice->getCreatedAt();
        //echo "Created datetime ".$createdAt;
        $billingAddress = $invoice->getBillingAddress();
        //echo "billing address";
        //echo "first name ". $billingAddress['firstname'];
        if ($billingAddress){
            $billName = 'M/s '.$billingAddress['firstname']. ' '.$billingAddress['lastname'];
            $billAddr1 = $billingAddress['street']. ' '. $billingAddress['city'];
            $billAddr2 = $billingAddress['region']. ' '. $billingAddress['postcode'];
        }
        
        $shippingAddress = $invoice->getShippingAddress();
        
        if ($shippingAddress){
            $shipName = 'M/s '.$shippingAddress['firstname']. ' '.$shippingAddress['lastname'];
            $shipAddr1 = $shippingAddress['street']. ' '. $shippingAddress['city'];
            $shipAddr2 = $shippingAddress['region']. ' '. $shippingAddress['postcode'];
        }
        //echo "shipping address";
        //echo "lastname ". $shippingAddress['lastname'];
        $order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);

        $dateCreateAt=date_create($createdAt);
        $dateFormatted=date_format($dateCreateAt,"d.m.Y");
        $timeFormatted = date_format($dateCreateAt,"H:i");
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('K3', $invoiceNumber)
                ->setCellValue('I4', "Date: ".date("d.m.Y"))
                ->setCellValue('G6', $dateFormatted)
                ->setCellValue('J6', $timeFormatted)
        ->setCellValue('F11', $billName)
        ->setCellValue('F12', $billAddr1)
        ->setCellValue('F13', $billAddr2)
        ->setCellValue('F16', $shipName)
        ->setCellValue('F17', $shipAddr1)
        ->setCellValue('F18', $shipAddr2);


        if ($order) {

            //echo " get dispatch method ".$order->getdispatchMethod();
            $dispatchMethod = $order->getdispatchMethod();
            //echo " Lorry number ".$order -> getLrNumber();
            $lrNumber = $order -> getLrNumber();
            //echo " CT3 Form number" .$order -> getCtForm();
            //echo " customer id " .$order-> getCustomerId();
            $customerRepository = $this->_objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
            $customerId = $order-> getCustomerId();
            $customer = $customerRepository->getById($order-> getCustomerId());
            $CustomerEmail = $customer->getEmail();
            $cattrValue = $customer->getCustomAttribute('tin_number');
            //print_r($cattrValue);
            if ($cattrValue){
            //echo "tin ".$cattrValue -> getValue();
            $customerTIN = $cattrValue -> getValue();
            }
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('H20', 'Mode of transport')
            ->setCellValue('H21', $lrNumber)
            ->setCellValue('H19', ucwords($dispatchMethod,"_"))
            //->setCellValue('B44', 'CT3 number')
            ->setCellValue('D51',$customerTIN);
            //print the order lines
            $orderItems = $order->getAllItems();
            $productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
            $index = 1;
            $weight = 0;
            $qtyOrdered = 0;
            $productName = "";
            $unitBasePrice = 0;
            
            foreach ($orderItems as $oItem){

                $productType = $oItem->getProductType();

                if ($productType == 'simple'){
                $qtyOrdered = $oItem->getQtyOrdered();

                $productName = $oItem->getName();

                $weight = $oItem->getWeight();

                /*$qtyInKgs = $oItem->getQtyInKgs();
                echo "qtyInKgs ordered" .$qtyInKgs;
                */
                $productId = $oItem->getProductId();

                $_product = $this->_objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
                        $_productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
                $_productParent = $_productCollection -> load($_product[0]);
                $parentProductSku = $_productParent->getSku();
                $productChild = $productCollection->load($productId);
                $optionId = $productChild->getData('packing_box');
                $attribute = $productChild->getResource()->getAttribute('packing_box');
                $packing = $attribute->getSource()->getOptionText($optionId);
                $customerBasePrice = $this->customerPrice->getCollection()->addFieldToFilter('customer_id',$customerId)
                                                                                              ->                    addFieldToFilter('product_sku',$parentProductSku)
                ->addFieldToFilter('start_time',array("lteq" => $createdAt))
                ->addFieldToFilter('end_time',array("gteq" => $createdAt));

                if (sizeof($customerBasePrice) != 0){
                    foreach($customerBasePrice as $customerBasePrice){
                        switch ($packing) {
                        case "1 Kg/ltr":
                            $unitBasePrice = $customerBasePrice->getUnitPriceOne();
                            break;
                        case "5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceFive();
                            break;
                        case "20 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceTwenty();
                            break;
                        case "Brl+5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlFive();
                            break;
                        case "Brl+Brl";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlBrl();
                            break;
                        }
                    }
                }
                }
                //write onto XL


                $totalWeight = $weight * $qtyOrdered;
                $vat55 = $order->getTotalVatOne();
                            $totalAmount = $order->getTotalAmount();
                            $totalBasePrice = $order->getTotalBasePrice();
                            $ctNumber = $order->getCtNumber();
                            $poNumber = $order->getpoNumber();
                //echo "vat55" . strval($vat55);
                //print_r($vat55);
                $vat145 = $order->getTotalVatTwo();
                        //echo "vat145". $vat145;

                $number = $totalAmount;
                $no = round($number);
                $point = round($number - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                                '13' => 'thirteen', '14' => 'fourteen',
                                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                                '60' => 'sixty', '70' => 'seventy',
                                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    
                    if ($number) {
                        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number < 21) ? $words[$number] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number / 10) * 10]
                        . " " . $words[$number % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;                 
                    } 
                    else 
                        $str[] = null;
                }
                
                $str = array_reverse($str);
                $result = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result . "Rupees  " . $points . " Paise";*/




                $objPHPExcel->setActiveSheetIndex(0) 
                ->setCellValue('A32', $index)
                ->setCellValue('B32', $productName)
                ->setCellValue('E32', round($weight) .' Kg x '.round($qtyOrdered))
                ->setCellValue('F32', 'Kg')
                ->setCellValue('H32', round($totalWeight))
                                    ->setCellValue('H43', round($totalWeight))
                ->setCellValue('J32', $unitBasePrice)
                                    //->setCellValue('B44', "C T-3 No:".$ctNumber)
                //->setCellValue('I53', 'Sub Total')
                //->setCellValue('I54', 'VAT 5.5%')
                ->setCellValue('K53', $vat55)
                                    ->setCellValue('K52', $totalBasePrice)
                                    ->setCellValue('K57', round($totalAmount))
                                    ->setCellValue('C57', ucwords($result. "Rupees only "))
                                    ->setCellValue('K32', $totalBasePrice)
                                    //->setCellValue('D51', 'po:')
                                    ->setCellValue('D50',$poNumber)
                //->setCellValue('I55', 'VAT 14.5%')
                ->setCellValue('K54', $vat145);
                //->setCellValue('I49','C.Ex.  12.50 %');


                $centralExcise = $order->getTotalCentralExcise();
                                         
                $number1 = $centralExcise;
                $no = round($number1);
                $point = round($number1 - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                '13' => 'thirteen', '14' => 'fourteen',
                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                '60' => 'sixty', '70' => 'seventy',
                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number1 = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    if ($number1) {
                        $plural = (($counter = count($str)) && $number1 > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number1 < 21) ? $words[$number1] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number1 / 10) * 10]
                        . " " . $words[$number1 % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;
                    } 
                    else 
                        $str[] = null;
                }
                $str = array_reverse($str);
                $result1 = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result1 . "Rupees  " . $points . " Paise";*/

                        
                if ($centralExcise ==0 ){
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('D48', "Nill Against Form CT - 3")
                    ->setCellValue('K49', "Nill");
                } else {
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('K48', $centralExcise)
                                        ->setCellValue('A46', ucwords("Total Excise duty Payable Rs:" . $result1 . "Rupees only", ":"));
                }
            }
        }
        
    
    
    
    $rendererName = \PHPExcel_Settings::PDF_RENDERER_TCPDF;
    $rendererLibraryPath = '/var/www/html/magento/vendor/tecnick.com/tcpdf';
    
    \PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath);
    $path = "document/attachment/".$invoice->getIncrementId().".xlsx";
    //$path = "document/attachment/".$invoice->getIncrementId().".PDF";
    
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    //$objWriter->setSheetIndex(0);
    $objWriter->save($path);
    
    return array($path,$billingAddress,$shippingAddress,$CustomerEmail);

    }    

}
 <?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Controller\ResultFactory;
use Sm\Customerprice\Model\Customerprice;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use \Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Mail\Message;
use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Mail\TransportInterfaceFactory;
use Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice\Mail\Template\TransportBuilder;

require_once BP . '/lib/internal/Phpexcel/PHPExcel.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/IOFactory.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/Writer/Excel2007.php';


$rendererLibrary = 'mPDF5.4';

$rendererLibraryPath = '/lib/internal/MPDF57/.' . $rendererLibrary;

class Email extends \Magento\Backend\App\Action
{

    
    protected $resultForwardFactory;
    private $_transportBuilder;
    
    
    public function __construct(

        \Magento\Backend\App\Action\Context $context,
        //\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
        PageFactory $resultPageFactory,
        CollectionFactory $salesOrderCollectionFactory,
        Customerprice $customerPrice,
        TransportBuilder $transportBuilder
    ) {
        $this->resultPageFactory = $resultPageFactory;
        //$this->_fileFactory = $fileFactory;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->salesOrderCollectionFactory = $salesOrderCollectionFactory;
        $this->customerPrice = $customerPrice;
        $this->_transportBuilder = $transportBuilder;
        parent::__construct($context,$resultForwardFactory);
        
    }

    /**
     * Notify user
     *
     * @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {

        $invoiceId = $this->getRequest()->getParam('invoice_id'); 

        if ($invoiceId) {
            
            $invoice = $this->_objectManager->create('Magento\Sales\Api\InvoiceRepositoryInterface')->get($invoiceId);
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); 
                $base = $dir->getRoot();
                $path = $base."/document/attachment/".$invoice->getIncrementId().'.xlsx';
            if ($invoice) {
            try{                
          
                $excelPath = $this->createExcel($invoice);
                $storeManager = $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface');
                $baseUrl = $storeManager->getStore()->getBaseUrl();
                
                
                $filePath =  $baseUrl . $excelPath[0]; 
                
                //header("Location: $filePath");
                
                if (!$invoice) {
                    return $this->resultForwardFactory->create()->forward('noroute');
                }

                //$this->_objectManager->create('Magento\Sales\Api\InvoiceManagementInterface')->notify($invoice->getEntityId());
            $resource        = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');
            $connection      = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

              $invoiceItemsGrid = $connection->fetchAll("SELECT order_increment_id FROM sales_invoice_grid WHERE entity_id = '".$invoice->getEntityId()."' ");
                
                $templateParams=array('invoice' => $invoice->getIncrementId() , 
                'order' => $invoiceItemsGrid[0]['order_increment_id'] , 
                'BillingAddressFirstName' => $excelPath[1]->getFirstName() ,
                'BillingAddressLastName' => $excelPath[1]->getLastName(),
                'CompanyBillingAddress' => $excelPath[1]->getCompany(),
                'StreetBillingAddress'=> $excelPath[1]['street'],
                'CityBillingAddress'=> $excelPath[1]->getCity(),
                'RegionBillingAddress'=> $excelPath[1]->getRegion(),
                'postCodeBillingAddress'=> $excelPath[1]->getPostCode(),
                'CountryBillingAddress'=> $excelPath[1]->getCountryId(),
                'TelephoneBillingAddress'=> $excelPath[1]->getTelephone(),
                'ShippingAddressFirstName'=> $excelPath[2]->getFirstName(),
                'ShippingAddressLastName'=> $excelPath[2]->getLastName(),
                'CompanyShippingAddress'=> $excelPath[2]->getCompany(),
                'StreetShippingAddress'=> $excelPath[1]['street'],
                'CityShippingAddress'=> $excelPath[2]->getCity(),
                'RegionShippingAddress'=> $excelPath[2]->getRegion(),
                'postCodeShippingAddress'=> $excelPath[2]->getPostCode(),
                'CountryShippingAddress'=> $excelPath[2]->getCountryId(),
                'TelephoneShippingAddress'=> $excelPath[2]->getTelephone()
                );   
                $transport = $this->_transportBuilder;
                    $transport->setTemplateIdentifier('sales_email_invoice_template');
                    $transport->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1));
                    $transport->setTemplateVars($templateParams);
                    $transport->setFrom(array('name' => 'Sales','email' => '[email protected]'));
                    $transport->setReplyTo('[email protected]');
                    $transport->addTo($excelPath[3]);
               
               $transport->addAttachment(file_get_contents($path),'application/octet-stream','attachment','base64',$invoice->getIncrementId().'.xlsx'); 

                 

            $transport->getTransport()->sendMessage();
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);   
            $this->messageManager->addSuccess(__('You sent the message.')); 
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect; 
                    
        }catch(\Exception $e){
            print_r($e->getMessage());exit;
        }   
                
                die();
            
            }
            else 
            {
                return $this->resultForwardFactory->create()->forward('noroute');
            }
        }           

    }
    
    public function createExcel(\Magento\Sales\Model\Order\Invoice $invoice)
    {
            
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load("//var/www/html/magento/app/code/Sm/Templates/KlauzInvoicePdf.xlsx");
        $xlsName = $invoice->getIncrementId().'.xlsx';

        //echo $xlsName;
        
        $orderId = $invoice->getOrderId();


        $invoiceNumber = $invoice->getInvoiceNumber();
        //echo "Invoice number ".$invoiceNumber ;
        $createdAt = $invoice->getCreatedAt();
        //echo "Created datetime ".$createdAt;
        $billingAddress = $invoice->getBillingAddress();
        //echo "billing address";
        //echo "first name ". $billingAddress['firstname'];
        if ($billingAddress){
            $billName = 'M/s '.$billingAddress['firstname']. ' '.$billingAddress['lastname'];
            $billAddr1 = $billingAddress['street']. ' '. $billingAddress['city'];
            $billAddr2 = $billingAddress['region']. ' '. $billingAddress['postcode'];
        }
        
        $shippingAddress = $invoice->getShippingAddress();
        
        if ($shippingAddress){
            $shipName = 'M/s '.$shippingAddress['firstname']. ' '.$shippingAddress['lastname'];
            $shipAddr1 = $shippingAddress['street']. ' '. $shippingAddress['city'];
            $shipAddr2 = $shippingAddress['region']. ' '. $shippingAddress['postcode'];
        }
        //echo "shipping address";
        //echo "lastname ". $shippingAddress['lastname'];
        $order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);

        $dateCreateAt=date_create($createdAt);
        $dateFormatted=date_format($dateCreateAt,"d.m.Y");
        $timeFormatted = date_format($dateCreateAt,"H:i");
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('K3', $invoiceNumber)
                ->setCellValue('I4', "Date: ".date("d.m.Y"))
                ->setCellValue('G6', $dateFormatted)
                ->setCellValue('J6', $timeFormatted)
        ->setCellValue('F11', $billName)
        ->setCellValue('F12', $billAddr1)
        ->setCellValue('F13', $billAddr2)
        ->setCellValue('F16', $shipName)
        ->setCellValue('F17', $shipAddr1)
        ->setCellValue('F18', $shipAddr2);


        if ($order) {

            //echo " get dispatch method ".$order->getdispatchMethod();
            $dispatchMethod = $order->getdispatchMethod();
            //echo " Lorry number ".$order -> getLrNumber();
            $lrNumber = $order -> getLrNumber();
            //echo " CT3 Form number" .$order -> getCtForm();
            //echo " customer id " .$order-> getCustomerId();
            $customerRepository = $this->_objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
            $customerId = $order-> getCustomerId();
            $customer = $customerRepository->getById($order-> getCustomerId());
            $CustomerEmail = $customer->getEmail();
            $cattrValue = $customer->getCustomAttribute('tin_number');
            //print_r($cattrValue);
            if ($cattrValue){
            //echo "tin ".$cattrValue -> getValue();
            $customerTIN = $cattrValue -> getValue();
            }
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('H20', 'Mode of transport')
            ->setCellValue('H21', $lrNumber)
            ->setCellValue('H19', ucwords($dispatchMethod,"_"))
            //->setCellValue('B44', 'CT3 number')
            ->setCellValue('D51',$customerTIN);
            //print the order lines
            $orderItems = $order->getAllItems();
            $productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
            $index = 1;
            $weight = 0;
            $qtyOrdered = 0;
            $productName = "";
            $unitBasePrice = 0;
            
            foreach ($orderItems as $oItem){

                $productType = $oItem->getProductType();

                if ($productType == 'simple'){
                $qtyOrdered = $oItem->getQtyOrdered();

                $productName = $oItem->getName();

                $weight = $oItem->getWeight();

                /*$qtyInKgs = $oItem->getQtyInKgs();
                echo "qtyInKgs ordered" .$qtyInKgs;
                */
                $productId = $oItem->getProductId();

                $_product = $this->_objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
                        $_productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
                $_productParent = $_productCollection -> load($_product[0]);
                $parentProductSku = $_productParent->getSku();
                $productChild = $productCollection->load($productId);
                $optionId = $productChild->getData('packing_box');
                $attribute = $productChild->getResource()->getAttribute('packing_box');
                $packing = $attribute->getSource()->getOptionText($optionId);
                $customerBasePrice = $this->customerPrice->getCollection()->addFieldToFilter('customer_id',$customerId)
                                                                                              ->                    addFieldToFilter('product_sku',$parentProductSku)
                ->addFieldToFilter('start_time',array("lteq" => $createdAt))
                ->addFieldToFilter('end_time',array("gteq" => $createdAt));

                if (sizeof($customerBasePrice) != 0){
                    foreach($customerBasePrice as $customerBasePrice){
                        switch ($packing) {
                        case "1 Kg/ltr":
                            $unitBasePrice = $customerBasePrice->getUnitPriceOne();
                            break;
                        case "5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceFive();
                            break;
                        case "20 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceTwenty();
                            break;
                        case "Brl+5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlFive();
                            break;
                        case "Brl+Brl";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlBrl();
                            break;
                        }
                    }
                }
                }
                //write onto XL


                $totalWeight = $weight * $qtyOrdered;
                $vat55 = $order->getTotalVatOne();
                            $totalAmount = $order->getTotalAmount();
                            $totalBasePrice = $order->getTotalBasePrice();
                            $ctNumber = $order->getCtNumber();
                            $poNumber = $order->getpoNumber();
                //echo "vat55" . strval($vat55);
                //print_r($vat55);
                $vat145 = $order->getTotalVatTwo();
                        //echo "vat145". $vat145;

                $number = $totalAmount;
                $no = round($number);
                $point = round($number - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                                '13' => 'thirteen', '14' => 'fourteen',
                                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                                '60' => 'sixty', '70' => 'seventy',
                                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    
                    if ($number) {
                        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number < 21) ? $words[$number] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number / 10) * 10]
                        . " " . $words[$number % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;                 
                    } 
                    else 
                        $str[] = null;
                }
                
                $str = array_reverse($str);
                $result = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result . "Rupees  " . $points . " Paise";*/




                $objPHPExcel->setActiveSheetIndex(0) 
                ->setCellValue('A32', $index)
                ->setCellValue('B32', $productName)
                ->setCellValue('E32', round($weight) .' Kg x '.round($qtyOrdered))
                ->setCellValue('F32', 'Kg')
                ->setCellValue('H32', round($totalWeight))
                                    ->setCellValue('H43', round($totalWeight))
                ->setCellValue('J32', $unitBasePrice)
                                    //->setCellValue('B44', "C T-3 No:".$ctNumber)
                //->setCellValue('I53', 'Sub Total')
                //->setCellValue('I54', 'VAT 5.5%')
                ->setCellValue('K53', $vat55)
                                    ->setCellValue('K52', $totalBasePrice)
                                    ->setCellValue('K57', round($totalAmount))
                                    ->setCellValue('C57', ucwords($result. "Rupees only "))
                                    ->setCellValue('K32', $totalBasePrice)
                                    //->setCellValue('D51', 'po:')
                                    ->setCellValue('D50',$poNumber)
                //->setCellValue('I55', 'VAT 14.5%')
                ->setCellValue('K54', $vat145);
                //->setCellValue('I49','C.Ex.  12.50 %');


                $centralExcise = $order->getTotalCentralExcise();
                                         
                $number1 = $centralExcise;
                $no = round($number1);
                $point = round($number1 - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                '13' => 'thirteen', '14' => 'fourteen',
                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                '60' => 'sixty', '70' => 'seventy',
                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number1 = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    if ($number1) {
                        $plural = (($counter = count($str)) && $number1 > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number1 < 21) ? $words[$number1] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number1 / 10) * 10]
                        . " " . $words[$number1 % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;
                    } 
                    else 
                        $str[] = null;
                }
                $str = array_reverse($str);
                $result1 = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result1 . "Rupees  " . $points . " Paise";*/

                        
                if ($centralExcise ==0 ){
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('D48', "Nill Against Form CT - 3")
                    ->setCellValue('K49', "Nill");
                } else {
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('K48', $centralExcise)
                                        ->setCellValue('A46', ucwords("Total Excise duty Payable Rs:" . $result1 . "Rupees only", ":"));
                }
            }
        }
        
    
    
    
    $rendererName = \PHPExcel_Settings::PDF_RENDERER_TCPDF;
    $rendererLibraryPath = '/var/www/html/magento/vendor/tecnick.com/tcpdf';
    
    \PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath);
    $path = "document/attachment/".$invoice->getIncrementId().".xlsx";
    //$path = "document/attachment/".$invoice->getIncrementId().".PDF";
    
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    //$objWriter->setSheetIndex(0);
    $objWriter->save($path);
    
    return array($path,$billingAddress,$shippingAddress,$CustomerEmail);

    }    

}

Controller File:

<?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Controller\ResultFactory;
use Sm\Customerprice\Model\Customerprice;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use \Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Mail\Message;
use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Mail\TransportInterfaceFactory;
use Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice\Mail\Template\TransportBuilder;

require_once BP . '/lib/internal/Phpexcel/PHPExcel.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/IOFactory.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/Writer/Excel2007.php';


$rendererLibrary = 'mPDF5.4';

$rendererLibraryPath = '/lib/internal/MPDF57/.' . $rendererLibrary;

class Email extends \Magento\Backend\App\Action
{

    
    protected $resultForwardFactory;
    private $_transportBuilder;
    
    
    public function __construct(

        \Magento\Backend\App\Action\Context $context,
        //\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
        PageFactory $resultPageFactory,
        CollectionFactory $salesOrderCollectionFactory,
        Customerprice $customerPrice,
        TransportBuilder $transportBuilder
    ) {
        $this->resultPageFactory = $resultPageFactory;
        //$this->_fileFactory = $fileFactory;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->salesOrderCollectionFactory = $salesOrderCollectionFactory;
        $this->customerPrice = $customerPrice;
        $this->_transportBuilder = $transportBuilder;
        parent::__construct($context,$resultForwardFactory);
        
    }

    /**
     * Notify user
     *
     * @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {

        $invoiceId = $this->getRequest()->getParam('invoice_id'); 

        if ($invoiceId) {
            
            $invoice = $this->_objectManager->create('Magento\Sales\Api\InvoiceRepositoryInterface')->get($invoiceId);
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); 
                $base = $dir->getRoot();
                $path = $base."/document/attachment/".$invoice->getIncrementId().'.xlsx';
            if ($invoice) {
            try{                
          
                $excelPath = $this->createExcel($invoice);
                $storeManager = $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface');
                $baseUrl = $storeManager->getStore()->getBaseUrl();
                
                
                $filePath =  $baseUrl . $excelPath[0]; 
                
                //header("Location: $filePath");
                
                if (!$invoice) {
                    return $this->resultForwardFactory->create()->forward('noroute');
                }

                //$this->_objectManager->create('Magento\Sales\Api\InvoiceManagementInterface')->notify($invoice->getEntityId());
            $resource        = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');
            $connection      = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

              $invoiceItemsGrid = $connection->fetchAll("SELECT order_increment_id FROM sales_invoice_grid WHERE entity_id = '".$invoice->getEntityId()."' ");
                
                $templateParams=array('invoice' => $invoice->getIncrementId() , 
                'order' => $invoiceItemsGrid[0]['order_increment_id'] , 
                'BillingAddressFirstName' => $excelPath[1]->getFirstName() ,
                'BillingAddressLastName' => $excelPath[1]->getLastName(),
                'CompanyBillingAddress' => $excelPath[1]->getCompany(),
                'StreetBillingAddress'=> $excelPath[1]['street'],
                'CityBillingAddress'=> $excelPath[1]->getCity(),
                'RegionBillingAddress'=> $excelPath[1]->getRegion(),
                'postCodeBillingAddress'=> $excelPath[1]->getPostCode(),
                'CountryBillingAddress'=> $excelPath[1]->getCountryId(),
                'TelephoneBillingAddress'=> $excelPath[1]->getTelephone(),
                'ShippingAddressFirstName'=> $excelPath[2]->getFirstName(),
                'ShippingAddressLastName'=> $excelPath[2]->getLastName(),
                'CompanyShippingAddress'=> $excelPath[2]->getCompany(),
                'StreetShippingAddress'=> $excelPath[1]['street'],
                'CityShippingAddress'=> $excelPath[2]->getCity(),
                'RegionShippingAddress'=> $excelPath[2]->getRegion(),
                'postCodeShippingAddress'=> $excelPath[2]->getPostCode(),
                'CountryShippingAddress'=> $excelPath[2]->getCountryId(),
                'TelephoneShippingAddress'=> $excelPath[2]->getTelephone()
                );   
                $transport = $this->_transportBuilder;
                    $transport->setTemplateIdentifier('sales_email_invoice_template');
                    $transport->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1));
                    $transport->setTemplateVars($templateParams);
                    $transport->setFrom(array('name' => 'Sales','email' => '[email protected]'));
                    $transport->setReplyTo('[email protected]');
                    $transport->addTo($excelPath[3]);
               
               $transport->addAttachment(file_get_contents($path),'application/octet-stream','attachment','base64',$invoice->getIncrementId().'.xlsx'); 

                 

            $transport->getTransport()->sendMessage();
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);   
            $this->messageManager->addSuccess(__('You sent the message.')); 
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect; 
                    
        }catch(\Exception $e){
            print_r($e->getMessage());exit;
        }   
                
                die();
            
            }
            else 
            {
                return $this->resultForwardFactory->create()->forward('noroute');
            }
        }           

    }
    
    public function createExcel(\Magento\Sales\Model\Order\Invoice $invoice)
    {
            
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load("//var/www/html/magento/app/code/Sm/Templates/KlauzInvoicePdf.xlsx");
        $xlsName = $invoice->getIncrementId().'.xlsx';

        //echo $xlsName;
        
        $orderId = $invoice->getOrderId();


        $invoiceNumber = $invoice->getInvoiceNumber();
        //echo "Invoice number ".$invoiceNumber ;
        $createdAt = $invoice->getCreatedAt();
        //echo "Created datetime ".$createdAt;
        $billingAddress = $invoice->getBillingAddress();
        //echo "billing address";
        //echo "first name ". $billingAddress['firstname'];
        if ($billingAddress){
            $billName = 'M/s '.$billingAddress['firstname']. ' '.$billingAddress['lastname'];
            $billAddr1 = $billingAddress['street']. ' '. $billingAddress['city'];
            $billAddr2 = $billingAddress['region']. ' '. $billingAddress['postcode'];
        }
        
        $shippingAddress = $invoice->getShippingAddress();
        
        if ($shippingAddress){
            $shipName = 'M/s '.$shippingAddress['firstname']. ' '.$shippingAddress['lastname'];
            $shipAddr1 = $shippingAddress['street']. ' '. $shippingAddress['city'];
            $shipAddr2 = $shippingAddress['region']. ' '. $shippingAddress['postcode'];
        }
        //echo "shipping address";
        //echo "lastname ". $shippingAddress['lastname'];
        $order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);

        $dateCreateAt=date_create($createdAt);
        $dateFormatted=date_format($dateCreateAt,"d.m.Y");
        $timeFormatted = date_format($dateCreateAt,"H:i");
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('K3', $invoiceNumber)
                ->setCellValue('I4', "Date: ".date("d.m.Y"))
                ->setCellValue('G6', $dateFormatted)
                ->setCellValue('J6', $timeFormatted)
        ->setCellValue('F11', $billName)
        ->setCellValue('F12', $billAddr1)
        ->setCellValue('F13', $billAddr2)
        ->setCellValue('F16', $shipName)
        ->setCellValue('F17', $shipAddr1)
        ->setCellValue('F18', $shipAddr2);


        if ($order) {

            //echo " get dispatch method ".$order->getdispatchMethod();
            $dispatchMethod = $order->getdispatchMethod();
            //echo " Lorry number ".$order -> getLrNumber();
            $lrNumber = $order -> getLrNumber();
            //echo " CT3 Form number" .$order -> getCtForm();
            //echo " customer id " .$order-> getCustomerId();
            $customerRepository = $this->_objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
            $customerId = $order-> getCustomerId();
            $customer = $customerRepository->getById($order-> getCustomerId());
            $CustomerEmail = $customer->getEmail();
            $cattrValue = $customer->getCustomAttribute('tin_number');
            //print_r($cattrValue);
            if ($cattrValue){
            //echo "tin ".$cattrValue -> getValue();
            $customerTIN = $cattrValue -> getValue();
            }
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('H20', 'Mode of transport')
            ->setCellValue('H21', $lrNumber)
            ->setCellValue('H19', ucwords($dispatchMethod,"_"))
            //->setCellValue('B44', 'CT3 number')
            ->setCellValue('D51',$customerTIN);
            //print the order lines
            $orderItems = $order->getAllItems();
            $productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
            $index = 1;
            $weight = 0;
            $qtyOrdered = 0;
            $productName = "";
            $unitBasePrice = 0;
            
            foreach ($orderItems as $oItem){

                $productType = $oItem->getProductType();

                if ($productType == 'simple'){
                $qtyOrdered = $oItem->getQtyOrdered();

                $productName = $oItem->getName();

                $weight = $oItem->getWeight();

                /*$qtyInKgs = $oItem->getQtyInKgs();
                echo "qtyInKgs ordered" .$qtyInKgs;
                */
                $productId = $oItem->getProductId();

                $_product = $this->_objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
                        $_productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
                $_productParent = $_productCollection -> load($_product[0]);
                $parentProductSku = $_productParent->getSku();
                $productChild = $productCollection->load($productId);
                $optionId = $productChild->getData('packing_box');
                $attribute = $productChild->getResource()->getAttribute('packing_box');
                $packing = $attribute->getSource()->getOptionText($optionId);
                $customerBasePrice = $this->customerPrice->getCollection()->addFieldToFilter('customer_id',$customerId)
                                                                                              ->                    addFieldToFilter('product_sku',$parentProductSku)
                ->addFieldToFilter('start_time',array("lteq" => $createdAt))
                ->addFieldToFilter('end_time',array("gteq" => $createdAt));

                if (sizeof($customerBasePrice) != 0){
                    foreach($customerBasePrice as $customerBasePrice){
                        switch ($packing) {
                        case "1 Kg/ltr":
                            $unitBasePrice = $customerBasePrice->getUnitPriceOne();
                            break;
                        case "5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceFive();
                            break;
                        case "20 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceTwenty();
                            break;
                        case "Brl+5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlFive();
                            break;
                        case "Brl+Brl";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlBrl();
                            break;
                        }
                    }
                }
                }
                //write onto XL


                $totalWeight = $weight * $qtyOrdered;
                $vat55 = $order->getTotalVatOne();
                            $totalAmount = $order->getTotalAmount();
                            $totalBasePrice = $order->getTotalBasePrice();
                            $ctNumber = $order->getCtNumber();
                            $poNumber = $order->getpoNumber();
                //echo "vat55" . strval($vat55);
                //print_r($vat55);
                $vat145 = $order->getTotalVatTwo();
                        //echo "vat145". $vat145;

                $number = $totalAmount;
                $no = round($number);
                $point = round($number - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                                '13' => 'thirteen', '14' => 'fourteen',
                                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                                '60' => 'sixty', '70' => 'seventy',
                                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    
                    if ($number) {
                        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number < 21) ? $words[$number] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number / 10) * 10]
                        . " " . $words[$number % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;                 
                    } 
                    else 
                        $str[] = null;
                }
                
                $str = array_reverse($str);
                $result = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result . "Rupees  " . $points . " Paise";*/




                $objPHPExcel->setActiveSheetIndex(0) 
                ->setCellValue('A32', $index)
                ->setCellValue('B32', $productName)
                ->setCellValue('E32', round($weight) .' Kg x '.round($qtyOrdered))
                ->setCellValue('F32', 'Kg')
                ->setCellValue('H32', round($totalWeight))
                                    ->setCellValue('H43', round($totalWeight))
                ->setCellValue('J32', $unitBasePrice)
                                    //->setCellValue('B44', "C T-3 No:".$ctNumber)
                //->setCellValue('I53', 'Sub Total')
                //->setCellValue('I54', 'VAT 5.5%')
                ->setCellValue('K53', $vat55)
                                    ->setCellValue('K52', $totalBasePrice)
                                    ->setCellValue('K57', round($totalAmount))
                                    ->setCellValue('C57', ucwords($result. "Rupees only "))
                                    ->setCellValue('K32', $totalBasePrice)
                                    //->setCellValue('D51', 'po:')
                                    ->setCellValue('D50',$poNumber)
                //->setCellValue('I55', 'VAT 14.5%')
                ->setCellValue('K54', $vat145);
                //->setCellValue('I49','C.Ex.  12.50 %');


                $centralExcise = $order->getTotalCentralExcise();
                                         
                $number1 = $centralExcise;
                $no = round($number1);
                $point = round($number1 - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                '13' => 'thirteen', '14' => 'fourteen',
                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                '60' => 'sixty', '70' => 'seventy',
                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number1 = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    if ($number1) {
                        $plural = (($counter = count($str)) && $number1 > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number1 < 21) ? $words[$number1] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number1 / 10) * 10]
                        . " " . $words[$number1 % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;
                    } 
                    else 
                        $str[] = null;
                }
                $str = array_reverse($str);
                $result1 = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result1 . "Rupees  " . $points . " Paise";*/

                        
                if ($centralExcise ==0 ){
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('D48', "Nill Against Form CT - 3")
                    ->setCellValue('K49', "Nill");
                } else {
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('K48', $centralExcise)
                                        ->setCellValue('A46', ucwords("Total Excise duty Payable Rs:" . $result1 . "Rupees only", ":"));
                }
            }
        }
        
    
    
    
    $rendererName = \PHPExcel_Settings::PDF_RENDERER_TCPDF;
    $rendererLibraryPath = '/var/www/html/magento/vendor/tecnick.com/tcpdf';
    
    \PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath);
    $path = "document/attachment/".$invoice->getIncrementId().".xlsx";
    //$path = "document/attachment/".$invoice->getIncrementId().".PDF";
    
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    //$objWriter->setSheetIndex(0);
    $objWriter->save($path);
    
    return array($path,$billingAddress,$shippingAddress,$CustomerEmail);

    }    

}
changes in body information
Source Link
Manthan Dave
  • 9.9k
  • 2
  • 33
  • 54
resultPageFactory = $resultPageFactory;//$this->_fileFactory = $fileFactory;$this->resultForwardFactory = $resultForwardFactory;$this->salesOrderCollectionFactory = $salesOrderCollectionFactory;$this->customerPrice = $customerPrice;$this->_transportBuilder = $transportBuilder;parent::__construct($context,$resultForwardFactory);}/*** Notify user** @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect*/public function execute(){$invoiceId = $this->getRequest()->getParam('invoice_id');if($invoiceId){$invoice = $this->_objectManager->create('Magento\Sales\Api\InvoiceRepositoryInterface')->get($invoiceId);$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');$base = $dir->getRoot();$path = $base."/document/attachment/".$invoice->getIncrementId().'.xlsx';if($invoice){try{$excelPath = $this->createExcel($invoice);$storeManager = $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface');$baseUrl = $storeManager->getStore()->getBaseUrl();$filePath = $baseUrl. $excelPath[0];//header("Location: $filePath");if(!$invoice){return $this->resultForwardFactory->create()->forward('noroute');}//$this->_objectManager->create('Magento\Sales\Api\InvoiceManagementInterface')->notify($invoice->getEntityId());$resource = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');$connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);$invoiceItemsGrid = $connection->fetchAll("SELECT order_increment_id FROM sales_invoice_grid WHERE entity_id = '".$invoice->getEntityId()."' ");$templateParams=array('invoice' => $invoice->getIncrementId(),'order' => $invoiceItemsGrid[0]['order_increment_id'],'BillingAddressFirstName' => $excelPath[1]->getFirstName(),'BillingAddressLastName' => $excelPath[1]->getLastName(),'CompanyBillingAddress' => $excelPath[1]->getCompany(),'StreetBillingAddress'=> $excelPath[1]['street'],'CityBillingAddress'=> $excelPath[1]->getCity(),'RegionBillingAddress'=> $excelPath[1]->getRegion(),'postCodeBillingAddress'=> $excelPath[1]->getPostCode(),'CountryBillingAddress'=> $excelPath[1]->getCountryId(),'TelephoneBillingAddress'=> $excelPath[1]->getTelephone(),'ShippingAddressFirstName'=> $excelPath[2]->getFirstName(),'ShippingAddressLastName'=> $excelPath[2]->getLastName(),'CompanyShippingAddress'=> $excelPath[2]->getCompany(),'StreetShippingAddress'=> $excelPath[1]['street'],'CityShippingAddress'=> $excelPath[2]->getCity(),'RegionShippingAddress'=> $excelPath[2]->getRegion(),'postCodeShippingAddress'=> $excelPath[2]->getPostCode(),'CountryShippingAddress'=> $excelPath[2]->getCountryId(),'TelephoneShippingAddress'=> $excelPath[2]->getTelephone());$transport = $this->_transportBuilder;$transport->setTemplateIdentifier('sales_email_invoice_template');$transport->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1));$transport->setTemplateVars($templateParams);$transport->setFrom(array('name' => 'Sales','email' => '[email protected]'));$transport->setReplyTo('[email protected]');$transport->addTo($excelPath[3]);$transport->addAttachment(file_get_contents($path),'application/octet-stream','attachment','base64',$invoice->getIncrementId().'.xlsx');$transport->getTransport()->sendMessage();$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);$this->messageManager->addSuccess(__('You sent the message.'));$resultRedirect->setUrl($this->_redirect->getRefererUrl());return $resultRedirect;}catch(\Exception $e){print_r($e->getMessage());exit;}die();}else{return $this->resultForwardFactory->create()->forward('noroute');}}}public function createExcel(\Magento\Sales\Model\Order\Invoice $invoice){$objReader = \PHPExcel_IOFactory::createReader('Excel2007');$objPHPExcel = $objReader->load("//var/www/html/magento/app/code/Sm/Templates/KlauzInvoicePdf.xlsx");$xlsName = $invoice->getIncrementId().'.xlsx';//echo $xlsName;$orderId = $invoice->getOrderId();$invoiceNumber = $invoice->getInvoiceNumber();//echo "Invoice number ".$invoiceNumber ;$createdAt = $invoice->getCreatedAt();//echo "Created datetime ".$createdAt;$billingAddress = $invoice->getBillingAddress();//echo "billing address";//echo "first name ". $billingAddress['firstname'];if($billingAddress){$billName = 'M/s '.$billingAddress['firstname']. ' '.$billingAddress['lastname'];$billAddr1 = $billingAddress['street']. ' '. $billingAddress['city'];$billAddr2 = $billingAddress['region']. ' '. $billingAddress['postcode'];}$shippingAddress = $invoice->getShippingAddress();if($shippingAddress){$shipName = 'M/s '.$shippingAddress['firstname']. ' '.$shippingAddress['lastname'];$shipAddr1 = $shippingAddress['street']. ' '. $shippingAddress['city'];$shipAddr2 = $shippingAddress['region']. ' '. $shippingAddress['postcode'];}//echo "shipping address";//echo "lastname ". $shippingAddress['lastname'];$order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);$dateCreateAt=date_create($createdAt);$dateFormatted=date_format($dateCreateAt,"d.m.Y");$timeFormatted = date_format($dateCreateAt,"H:i");$objPHPExcel->setActiveSheetIndex(0)->setCellValue('K3', $invoiceNumber)->setCellValue('I4', "Date: ".date("d.m.Y"))->setCellValue('G6', $dateFormatted)->setCellValue('J6', $timeFormatted)->setCellValue('F11', $billName)->setCellValue('F12', $billAddr1)->setCellValue('F13', $billAddr2)->setCellValue('F16', $shipName)->setCellValue('F17', $shipAddr1)->setCellValue('F18', $shipAddr2);if($order){//echo " get dispatch method ".$order->getdispatchMethod();$dispatchMethod = $order->getdispatchMethod();//echo " Lorry number ".$order-> getLrNumber();$lrNumber = $order-> getLrNumber();//echo " CT3 Form number".$order-> getCtForm();//echo " customer id ".$order-> getCustomerId();$customerRepository = $this->_objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');$customerId = $order-> getCustomerId();$customer = $customerRepository->getById($order-> getCustomerId());$CustomerEmail = $customer->getEmail();$cattrValue = $customer->getCustomAttribute('tin_number');//print_r($cattrValue);if($cattrValue){//echo "tin ".$cattrValue-> getValue();$customerTIN = $cattrValue-> getValue();}$objPHPExcel->setActiveSheetIndex(0)->setCellValue('H20', 'Mode of transport')->setCellValue('H21', $lrNumber)->setCellValue('H19', ucwords($dispatchMethod,"_"))//->setCellValue('B44', 'CT3 number')->setCellValue('D51',$customerTIN);//print the order lines$orderItems = $order->getAllItems();$productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');$index = 1;$weight = 0;$qtyOrdered = 0;$productName = "";$unitBasePrice = 0;foreach($orderItems as $oItem){$productType = $oItem->getProductType();if($productType == 'simple'){$qtyOrdered = $oItem->getQtyOrdered();$productName = $oItem->getName();$weight = $oItem->getWeight();/*$qtyInKgs = $oItem->getQtyInKgs();echo "qtyInKgs ordered".$qtyInKgs;*/$productId = $oItem->getProductId();$_product = $this->_objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);$_productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');$_productParent = $_productCollection-> load($_product[0]);$parentProductSku = $_productParent->getSku();$productChild = $productCollection->load($productId);$optionId = $productChild->getData('packing_box');$attribute = $productChild->getResource()->getAttribute('packing_box');$packing = $attribute->getSource()->getOptionText($optionId);$customerBasePrice = $this->customerPrice->getCollection()->addFieldToFilter('customer_id',$customerId)-> addFieldToFilter('product_sku',$parentProductSku)->addFieldToFilter('start_time',array("lteq" => $createdAt))->addFieldToFilter('end_time',array("gteq" => $createdAt));if(sizeof($customerBasePrice)!= 0){foreach($customerBasePrice as $customerBasePrice){switch($packing){case "1 Kg/ltr":$unitBasePrice = $customerBasePrice->getUnitPriceOne();break;case "5 Kg";$unitBasePrice = $customerBasePrice->getUnitPriceFive();break;case "20 Kg";$unitBasePrice = $customerBasePrice->getUnitPriceTwenty();break;case "Brl+5 Kg";$unitBasePrice = $customerBasePrice->getUnitPriceBrlFive();break;case "Brl+Brl";$unitBasePrice = $customerBasePrice->getUnitPriceBrlBrl();break;}}}}//write onto XL$totalWeight = $weight * $qtyOrdered;$vat55 = $order->getTotalVatOne();$totalAmount = $order->getTotalAmount();$totalBasePrice = $order->getTotalBasePrice();$ctNumber = $order->getCtNumber();$poNumber = $order->getpoNumber();//echo "vat55". strval($vat55);//print_r($vat55);$vat145 = $order->getTotalVatTwo();//echo "vat145". $vat145;$number = $totalAmount;$no = round($number);$point = round($number- $no, 2) * 100;$hundred = null;$digits_1 = strlen($no);$i = 0;$str = array();$words = array('0' => '', '1' => 'one', '2' => 'two','3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six','7' => 'seven', '8' => 'eight', '9' => 'nine','10' => 'ten', '11' => 'eleven', '12' => 'twelve','13' => 'thirteen', '14' => 'fourteen','15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen','18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty','30' => 'thirty', '40' => 'forty', '50' => 'fifty','60' => 'sixty', '70' => 'seventy','80' => 'eighty', '90' => 'ninety');$digits = array('', 'hundred', 'thousand', 'lakh', 'crore');while($i 9)? 's': null;$hundred =($counter == 1 && $str[0])? ' and ': null;$str [] =($number setActiveSheetIndex(0)->setCellValue('A32', $index)->setCellValue('B32', $productName)->setCellValue('E32', round($weight).' Kg x '.round($qtyOrdered))->setCellValue('F32', 'Kg')->setCellValue('H32', round($totalWeight))->setCellValue('H43', round($totalWeight))->setCellValue('J32', $unitBasePrice)//->setCellValue('B44', "C T-3 No:".$ctNumber)//->setCellValue('I53', 'Sub Total')//->setCellValue('I54', 'VAT 5.5%')->setCellValue('K53', $vat55)->setCellValue('K52', $totalBasePrice)->setCellValue('K57', round($totalAmount))->setCellValue('C57', ucwords($result. "Rupees only "))->setCellValue('K32', $totalBasePrice)//->setCellValue('D51', 'po:')->setCellValue('D50',$poNumber)//->setCellValue('I55', 'VAT 14.5%')->setCellValue('K54', $vat145);//->setCellValue('I49','C.Ex. 12.50 %');$centralExcise = $order->getTotalCentralExcise();$number1 = $centralExcise;$no = round($number1);$point = round($number1- $no, 2) * 100;$hundred = null;$digits_1 = strlen($no);$i = 0;$str = array();$words = array('0' => '', '1' => 'one', '2' => 'two','3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six','7' => 'seven', '8' => 'eight', '9' => 'nine','10' => 'ten', '11' => 'eleven', '12' => 'twelve','13' => 'thirteen', '14' => 'fourteen','15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen','18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty','30' => 'thirty', '40' => 'forty', '50' => 'fifty','60' => 'sixty', '70' => 'seventy','80' => 'eighty', '90' => 'ninety');$digits = array('', 'hundred', 'thousand', 'lakh', 'crore');while($i 9)? 's': null;$hundred =($counter == 1 && $str[0])? ' and ': null;$str [] =($number1 setActiveSheetIndex(0)->setCellValue('D48', "Nill Against Form CT- 3")->setCellValue('K49', "Nill");} else{$objPHPExcel->setActiveSheetIndex(0)->setCellValue('K48', $centralExcise)->setCellValue('A46', ucwords("Total Excise duty Payable Rs:". $result1. "Rupees only", ":"));}}}$rendererName = \PHPExcel_Settings::PDF_RENDERER_TCPDF;$rendererLibraryPath = '/var/www/html/magento/vendor/tecnick.com/tcpdf';\PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath);$path = "document/attachment/".$invoice->getIncrementId().".xlsx";//$path = "document/attachment/".$invoice->getIncrementId().".PDF";$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');//$objWriter->setSheetIndex(0);$objWriter->save($path);return array($path,$billingAddress,$shippingAddress,$CustomerEmail);}}di.xml
 <?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Controller\ResultFactory;
use Sm\Customerprice\Model\Customerprice;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use \Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Mail\Message;
use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Mail\TransportInterfaceFactory;
use Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice\Mail\Template\TransportBuilder;

require_once BP . '/lib/internal/Phpexcel/PHPExcel.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/IOFactory.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/Writer/Excel2007.php';


$rendererLibrary = 'mPDF5.4';

$rendererLibraryPath = '/lib/internal/MPDF57/.' . $rendererLibrary;

class Email extends \Magento\Backend\App\Action
{

    
    protected $resultForwardFactory;
    private $_transportBuilder;
    
    
    public function __construct(

        \Magento\Backend\App\Action\Context $context,
        //\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
        PageFactory $resultPageFactory,
        CollectionFactory $salesOrderCollectionFactory,
        Customerprice $customerPrice,
        TransportBuilder $transportBuilder
    ) {
        $this->resultPageFactory = $resultPageFactory;
        //$this->_fileFactory = $fileFactory;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->salesOrderCollectionFactory = $salesOrderCollectionFactory;
        $this->customerPrice = $customerPrice;
        $this->_transportBuilder = $transportBuilder;
        parent::__construct($context,$resultForwardFactory);
        
    }

    /**
     * Notify user
     *
     * @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {

        $invoiceId = $this->getRequest()->getParam('invoice_id'); 

        if ($invoiceId) {
            
            $invoice = $this->_objectManager->create('Magento\Sales\Api\InvoiceRepositoryInterface')->get($invoiceId);
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); 
                $base = $dir->getRoot();
                $path = $base."/document/attachment/".$invoice->getIncrementId().'.xlsx';
            if ($invoice) {
            try{                
          
                $excelPath = $this->createExcel($invoice);
                $storeManager = $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface');
                $baseUrl = $storeManager->getStore()->getBaseUrl();
                
                
                $filePath =  $baseUrl . $excelPath[0]; 
                
                //header("Location: $filePath");
                
                if (!$invoice) {
                    return $this->resultForwardFactory->create()->forward('noroute');
                }

                //$this->_objectManager->create('Magento\Sales\Api\InvoiceManagementInterface')->notify($invoice->getEntityId());
            $resource        = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');
            $connection      = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

              $invoiceItemsGrid = $connection->fetchAll("SELECT order_increment_id FROM sales_invoice_grid WHERE entity_id = '".$invoice->getEntityId()."' ");
                
                $templateParams=array('invoice' => $invoice->getIncrementId() , 
                'order' => $invoiceItemsGrid[0]['order_increment_id'] , 
                'BillingAddressFirstName' => $excelPath[1]->getFirstName() ,
                'BillingAddressLastName' => $excelPath[1]->getLastName(),
                'CompanyBillingAddress' => $excelPath[1]->getCompany(),
                'StreetBillingAddress'=> $excelPath[1]['street'],
                'CityBillingAddress'=> $excelPath[1]->getCity(),
                'RegionBillingAddress'=> $excelPath[1]->getRegion(),
                'postCodeBillingAddress'=> $excelPath[1]->getPostCode(),
                'CountryBillingAddress'=> $excelPath[1]->getCountryId(),
                'TelephoneBillingAddress'=> $excelPath[1]->getTelephone(),
                'ShippingAddressFirstName'=> $excelPath[2]->getFirstName(),
                'ShippingAddressLastName'=> $excelPath[2]->getLastName(),
                'CompanyShippingAddress'=> $excelPath[2]->getCompany(),
                'StreetShippingAddress'=> $excelPath[1]['street'],
                'CityShippingAddress'=> $excelPath[2]->getCity(),
                'RegionShippingAddress'=> $excelPath[2]->getRegion(),
                'postCodeShippingAddress'=> $excelPath[2]->getPostCode(),
                'CountryShippingAddress'=> $excelPath[2]->getCountryId(),
                'TelephoneShippingAddress'=> $excelPath[2]->getTelephone()
                );   
                $transport = $this->_transportBuilder;
                    $transport->setTemplateIdentifier('sales_email_invoice_template');
                    $transport->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1));
                    $transport->setTemplateVars($templateParams);
                    $transport->setFrom(array('name' => 'Sales','email' => '[email protected]'));
                    $transport->setReplyTo('[email protected]');
                    $transport->addTo($excelPath[3]);
               
               $transport->addAttachment(file_get_contents($path),'application/octet-stream','attachment','base64',$invoice->getIncrementId().'.xlsx'); 

                 

            $transport->getTransport()->sendMessage();
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);   
            $this->messageManager->addSuccess(__('You sent the message.')); 
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect; 
                    
        }catch(\Exception $e){
            print_r($e->getMessage());exit;
        }   
                
                die();
            
            }
            else 
            {
                return $this->resultForwardFactory->create()->forward('noroute');
            }
        }           

    }
    
    public function createExcel(\Magento\Sales\Model\Order\Invoice $invoice)
    {
            
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load("//var/www/html/magento/app/code/Sm/Templates/KlauzInvoicePdf.xlsx");
        $xlsName = $invoice->getIncrementId().'.xlsx';

        //echo $xlsName;
        
        $orderId = $invoice->getOrderId();


        $invoiceNumber = $invoice->getInvoiceNumber();
        //echo "Invoice number ".$invoiceNumber ;
        $createdAt = $invoice->getCreatedAt();
        //echo "Created datetime ".$createdAt;
        $billingAddress = $invoice->getBillingAddress();
        //echo "billing address";
        //echo "first name ". $billingAddress['firstname'];
        if ($billingAddress){
            $billName = 'M/s '.$billingAddress['firstname']. ' '.$billingAddress['lastname'];
            $billAddr1 = $billingAddress['street']. ' '. $billingAddress['city'];
            $billAddr2 = $billingAddress['region']. ' '. $billingAddress['postcode'];
        }
        
        $shippingAddress = $invoice->getShippingAddress();
        
        if ($shippingAddress){
            $shipName = 'M/s '.$shippingAddress['firstname']. ' '.$shippingAddress['lastname'];
            $shipAddr1 = $shippingAddress['street']. ' '. $shippingAddress['city'];
            $shipAddr2 = $shippingAddress['region']. ' '. $shippingAddress['postcode'];
        }
        //echo "shipping address";
        //echo "lastname ". $shippingAddress['lastname'];
        $order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);

        $dateCreateAt=date_create($createdAt);
        $dateFormatted=date_format($dateCreateAt,"d.m.Y");
        $timeFormatted = date_format($dateCreateAt,"H:i");
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('K3', $invoiceNumber)
                ->setCellValue('I4', "Date: ".date("d.m.Y"))
                ->setCellValue('G6', $dateFormatted)
                ->setCellValue('J6', $timeFormatted)
        ->setCellValue('F11', $billName)
        ->setCellValue('F12', $billAddr1)
        ->setCellValue('F13', $billAddr2)
        ->setCellValue('F16', $shipName)
        ->setCellValue('F17', $shipAddr1)
        ->setCellValue('F18', $shipAddr2);


        if ($order) {

            //echo " get dispatch method ".$order->getdispatchMethod();
            $dispatchMethod = $order->getdispatchMethod();
            //echo " Lorry number ".$order -> getLrNumber();
            $lrNumber = $order -> getLrNumber();
            //echo " CT3 Form number" .$order -> getCtForm();
            //echo " customer id " .$order-> getCustomerId();
            $customerRepository = $this->_objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
            $customerId = $order-> getCustomerId();
            $customer = $customerRepository->getById($order-> getCustomerId());
            $CustomerEmail = $customer->getEmail();
            $cattrValue = $customer->getCustomAttribute('tin_number');
            //print_r($cattrValue);
            if ($cattrValue){
            //echo "tin ".$cattrValue -> getValue();
            $customerTIN = $cattrValue -> getValue();
            }
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('H20', 'Mode of transport')
            ->setCellValue('H21', $lrNumber)
            ->setCellValue('H19', ucwords($dispatchMethod,"_"))
            //->setCellValue('B44', 'CT3 number')
            ->setCellValue('D51',$customerTIN);
            //print the order lines
            $orderItems = $order->getAllItems();
            $productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
            $index = 1;
            $weight = 0;
            $qtyOrdered = 0;
            $productName = "";
            $unitBasePrice = 0;
            
            foreach ($orderItems as $oItem){

                $productType = $oItem->getProductType();

                if ($productType == 'simple'){
                $qtyOrdered = $oItem->getQtyOrdered();

                $productName = $oItem->getName();

                $weight = $oItem->getWeight();

                /*$qtyInKgs = $oItem->getQtyInKgs();
                echo "qtyInKgs ordered" .$qtyInKgs;
                */
                $productId = $oItem->getProductId();

                $_product = $this->_objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
                        $_productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
                $_productParent = $_productCollection -> load($_product[0]);
                $parentProductSku = $_productParent->getSku();
                $productChild = $productCollection->load($productId);
                $optionId = $productChild->getData('packing_box');
                $attribute = $productChild->getResource()->getAttribute('packing_box');
                $packing = $attribute->getSource()->getOptionText($optionId);
                $customerBasePrice = $this->customerPrice->getCollection()->addFieldToFilter('customer_id',$customerId)
                                                                                              ->                    addFieldToFilter('product_sku',$parentProductSku)
                ->addFieldToFilter('start_time',array("lteq" => $createdAt))
                ->addFieldToFilter('end_time',array("gteq" => $createdAt));

                if (sizeof($customerBasePrice) != 0){
                    foreach($customerBasePrice as $customerBasePrice){
                        switch ($packing) {
                        case "1 Kg/ltr":
                            $unitBasePrice = $customerBasePrice->getUnitPriceOne();
                            break;
                        case "5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceFive();
                            break;
                        case "20 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceTwenty();
                            break;
                        case "Brl+5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlFive();
                            break;
                        case "Brl+Brl";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlBrl();
                            break;
                        }
                    }
                }
                }
                //write onto XL


                $totalWeight = $weight * $qtyOrdered;
                $vat55 = $order->getTotalVatOne();
                            $totalAmount = $order->getTotalAmount();
                            $totalBasePrice = $order->getTotalBasePrice();
                            $ctNumber = $order->getCtNumber();
                            $poNumber = $order->getpoNumber();
                //echo "vat55" . strval($vat55);
                //print_r($vat55);
                $vat145 = $order->getTotalVatTwo();
                        //echo "vat145". $vat145;

                $number = $totalAmount;
                $no = round($number);
                $point = round($number - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                                '13' => 'thirteen', '14' => 'fourteen',
                                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                                '60' => 'sixty', '70' => 'seventy',
                                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    
                    if ($number) {
                        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number < 21) ? $words[$number] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number / 10) * 10]
                        . " " . $words[$number % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;                 
                    } 
                    else 
                        $str[] = null;
                }
                
                $str = array_reverse($str);
                $result = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result . "Rupees  " . $points . " Paise";*/




                $objPHPExcel->setActiveSheetIndex(0) 
                ->setCellValue('A32', $index)
                ->setCellValue('B32', $productName)
                ->setCellValue('E32', round($weight) .' Kg x '.round($qtyOrdered))
                ->setCellValue('F32', 'Kg')
                ->setCellValue('H32', round($totalWeight))
                                    ->setCellValue('H43', round($totalWeight))
                ->setCellValue('J32', $unitBasePrice)
                                    //->setCellValue('B44', "C T-3 No:".$ctNumber)
                //->setCellValue('I53', 'Sub Total')
                //->setCellValue('I54', 'VAT 5.5%')
                ->setCellValue('K53', $vat55)
                                    ->setCellValue('K52', $totalBasePrice)
                                    ->setCellValue('K57', round($totalAmount))
                                    ->setCellValue('C57', ucwords($result. "Rupees only "))
                                    ->setCellValue('K32', $totalBasePrice)
                                    //->setCellValue('D51', 'po:')
                                    ->setCellValue('D50',$poNumber)
                //->setCellValue('I55', 'VAT 14.5%')
                ->setCellValue('K54', $vat145);
                //->setCellValue('I49','C.Ex.  12.50 %');


                $centralExcise = $order->getTotalCentralExcise();
                                         
                $number1 = $centralExcise;
                $no = round($number1);
                $point = round($number1 - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                '13' => 'thirteen', '14' => 'fourteen',
                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                '60' => 'sixty', '70' => 'seventy',
                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number1 = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    if ($number1) {
                        $plural = (($counter = count($str)) && $number1 > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number1 < 21) ? $words[$number1] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number1 / 10) * 10]
                        . " " . $words[$number1 % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;
                    } 
                    else 
                        $str[] = null;
                }
                $str = array_reverse($str);
                $result1 = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result1 . "Rupees  " . $points . " Paise";*/

                        
                if ($centralExcise ==0 ){
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('D48', "Nill Against Form CT - 3")
                    ->setCellValue('K49', "Nill");
                } else {
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('K48', $centralExcise)
                                        ->setCellValue('A46', ucwords("Total Excise duty Payable Rs:" . $result1 . "Rupees only", ":"));
                }
            }
        }
        
    
    
    
    $rendererName = \PHPExcel_Settings::PDF_RENDERER_TCPDF;
    $rendererLibraryPath = '/var/www/html/magento/vendor/tecnick.com/tcpdf';
    
    \PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath);
    $path = "document/attachment/".$invoice->getIncrementId().".xlsx";
    //$path = "document/attachment/".$invoice->getIncrementId().".PDF";
    
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    //$objWriter->setSheetIndex(0);
    $objWriter->save($path);
    
    return array($path,$billingAddress,$shippingAddress,$CustomerEmail);

    }    

}

di.xml

<preference for="Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice\Email" type="Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice\Email" />
resultPageFactory = $resultPageFactory;//$this->_fileFactory = $fileFactory;$this->resultForwardFactory = $resultForwardFactory;$this->salesOrderCollectionFactory = $salesOrderCollectionFactory;$this->customerPrice = $customerPrice;$this->_transportBuilder = $transportBuilder;parent::__construct($context,$resultForwardFactory);}/*** Notify user** @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect*/public function execute(){$invoiceId = $this->getRequest()->getParam('invoice_id');if($invoiceId){$invoice = $this->_objectManager->create('Magento\Sales\Api\InvoiceRepositoryInterface')->get($invoiceId);$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');$base = $dir->getRoot();$path = $base."/document/attachment/".$invoice->getIncrementId().'.xlsx';if($invoice){try{$excelPath = $this->createExcel($invoice);$storeManager = $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface');$baseUrl = $storeManager->getStore()->getBaseUrl();$filePath = $baseUrl. $excelPath[0];//header("Location: $filePath");if(!$invoice){return $this->resultForwardFactory->create()->forward('noroute');}//$this->_objectManager->create('Magento\Sales\Api\InvoiceManagementInterface')->notify($invoice->getEntityId());$resource = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');$connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);$invoiceItemsGrid = $connection->fetchAll("SELECT order_increment_id FROM sales_invoice_grid WHERE entity_id = '".$invoice->getEntityId()."' ");$templateParams=array('invoice' => $invoice->getIncrementId(),'order' => $invoiceItemsGrid[0]['order_increment_id'],'BillingAddressFirstName' => $excelPath[1]->getFirstName(),'BillingAddressLastName' => $excelPath[1]->getLastName(),'CompanyBillingAddress' => $excelPath[1]->getCompany(),'StreetBillingAddress'=> $excelPath[1]['street'],'CityBillingAddress'=> $excelPath[1]->getCity(),'RegionBillingAddress'=> $excelPath[1]->getRegion(),'postCodeBillingAddress'=> $excelPath[1]->getPostCode(),'CountryBillingAddress'=> $excelPath[1]->getCountryId(),'TelephoneBillingAddress'=> $excelPath[1]->getTelephone(),'ShippingAddressFirstName'=> $excelPath[2]->getFirstName(),'ShippingAddressLastName'=> $excelPath[2]->getLastName(),'CompanyShippingAddress'=> $excelPath[2]->getCompany(),'StreetShippingAddress'=> $excelPath[1]['street'],'CityShippingAddress'=> $excelPath[2]->getCity(),'RegionShippingAddress'=> $excelPath[2]->getRegion(),'postCodeShippingAddress'=> $excelPath[2]->getPostCode(),'CountryShippingAddress'=> $excelPath[2]->getCountryId(),'TelephoneShippingAddress'=> $excelPath[2]->getTelephone());$transport = $this->_transportBuilder;$transport->setTemplateIdentifier('sales_email_invoice_template');$transport->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1));$transport->setTemplateVars($templateParams);$transport->setFrom(array('name' => 'Sales','email' => '[email protected]'));$transport->setReplyTo('[email protected]');$transport->addTo($excelPath[3]);$transport->addAttachment(file_get_contents($path),'application/octet-stream','attachment','base64',$invoice->getIncrementId().'.xlsx');$transport->getTransport()->sendMessage();$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);$this->messageManager->addSuccess(__('You sent the message.'));$resultRedirect->setUrl($this->_redirect->getRefererUrl());return $resultRedirect;}catch(\Exception $e){print_r($e->getMessage());exit;}die();}else{return $this->resultForwardFactory->create()->forward('noroute');}}}public function createExcel(\Magento\Sales\Model\Order\Invoice $invoice){$objReader = \PHPExcel_IOFactory::createReader('Excel2007');$objPHPExcel = $objReader->load("//var/www/html/magento/app/code/Sm/Templates/KlauzInvoicePdf.xlsx");$xlsName = $invoice->getIncrementId().'.xlsx';//echo $xlsName;$orderId = $invoice->getOrderId();$invoiceNumber = $invoice->getInvoiceNumber();//echo "Invoice number ".$invoiceNumber ;$createdAt = $invoice->getCreatedAt();//echo "Created datetime ".$createdAt;$billingAddress = $invoice->getBillingAddress();//echo "billing address";//echo "first name ". $billingAddress['firstname'];if($billingAddress){$billName = 'M/s '.$billingAddress['firstname']. ' '.$billingAddress['lastname'];$billAddr1 = $billingAddress['street']. ' '. $billingAddress['city'];$billAddr2 = $billingAddress['region']. ' '. $billingAddress['postcode'];}$shippingAddress = $invoice->getShippingAddress();if($shippingAddress){$shipName = 'M/s '.$shippingAddress['firstname']. ' '.$shippingAddress['lastname'];$shipAddr1 = $shippingAddress['street']. ' '. $shippingAddress['city'];$shipAddr2 = $shippingAddress['region']. ' '. $shippingAddress['postcode'];}//echo "shipping address";//echo "lastname ". $shippingAddress['lastname'];$order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);$dateCreateAt=date_create($createdAt);$dateFormatted=date_format($dateCreateAt,"d.m.Y");$timeFormatted = date_format($dateCreateAt,"H:i");$objPHPExcel->setActiveSheetIndex(0)->setCellValue('K3', $invoiceNumber)->setCellValue('I4', "Date: ".date("d.m.Y"))->setCellValue('G6', $dateFormatted)->setCellValue('J6', $timeFormatted)->setCellValue('F11', $billName)->setCellValue('F12', $billAddr1)->setCellValue('F13', $billAddr2)->setCellValue('F16', $shipName)->setCellValue('F17', $shipAddr1)->setCellValue('F18', $shipAddr2);if($order){//echo " get dispatch method ".$order->getdispatchMethod();$dispatchMethod = $order->getdispatchMethod();//echo " Lorry number ".$order-> getLrNumber();$lrNumber = $order-> getLrNumber();//echo " CT3 Form number".$order-> getCtForm();//echo " customer id ".$order-> getCustomerId();$customerRepository = $this->_objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');$customerId = $order-> getCustomerId();$customer = $customerRepository->getById($order-> getCustomerId());$CustomerEmail = $customer->getEmail();$cattrValue = $customer->getCustomAttribute('tin_number');//print_r($cattrValue);if($cattrValue){//echo "tin ".$cattrValue-> getValue();$customerTIN = $cattrValue-> getValue();}$objPHPExcel->setActiveSheetIndex(0)->setCellValue('H20', 'Mode of transport')->setCellValue('H21', $lrNumber)->setCellValue('H19', ucwords($dispatchMethod,"_"))//->setCellValue('B44', 'CT3 number')->setCellValue('D51',$customerTIN);//print the order lines$orderItems = $order->getAllItems();$productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');$index = 1;$weight = 0;$qtyOrdered = 0;$productName = "";$unitBasePrice = 0;foreach($orderItems as $oItem){$productType = $oItem->getProductType();if($productType == 'simple'){$qtyOrdered = $oItem->getQtyOrdered();$productName = $oItem->getName();$weight = $oItem->getWeight();/*$qtyInKgs = $oItem->getQtyInKgs();echo "qtyInKgs ordered".$qtyInKgs;*/$productId = $oItem->getProductId();$_product = $this->_objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);$_productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');$_productParent = $_productCollection-> load($_product[0]);$parentProductSku = $_productParent->getSku();$productChild = $productCollection->load($productId);$optionId = $productChild->getData('packing_box');$attribute = $productChild->getResource()->getAttribute('packing_box');$packing = $attribute->getSource()->getOptionText($optionId);$customerBasePrice = $this->customerPrice->getCollection()->addFieldToFilter('customer_id',$customerId)-> addFieldToFilter('product_sku',$parentProductSku)->addFieldToFilter('start_time',array("lteq" => $createdAt))->addFieldToFilter('end_time',array("gteq" => $createdAt));if(sizeof($customerBasePrice)!= 0){foreach($customerBasePrice as $customerBasePrice){switch($packing){case "1 Kg/ltr":$unitBasePrice = $customerBasePrice->getUnitPriceOne();break;case "5 Kg";$unitBasePrice = $customerBasePrice->getUnitPriceFive();break;case "20 Kg";$unitBasePrice = $customerBasePrice->getUnitPriceTwenty();break;case "Brl+5 Kg";$unitBasePrice = $customerBasePrice->getUnitPriceBrlFive();break;case "Brl+Brl";$unitBasePrice = $customerBasePrice->getUnitPriceBrlBrl();break;}}}}//write onto XL$totalWeight = $weight * $qtyOrdered;$vat55 = $order->getTotalVatOne();$totalAmount = $order->getTotalAmount();$totalBasePrice = $order->getTotalBasePrice();$ctNumber = $order->getCtNumber();$poNumber = $order->getpoNumber();//echo "vat55". strval($vat55);//print_r($vat55);$vat145 = $order->getTotalVatTwo();//echo "vat145". $vat145;$number = $totalAmount;$no = round($number);$point = round($number- $no, 2) * 100;$hundred = null;$digits_1 = strlen($no);$i = 0;$str = array();$words = array('0' => '', '1' => 'one', '2' => 'two','3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six','7' => 'seven', '8' => 'eight', '9' => 'nine','10' => 'ten', '11' => 'eleven', '12' => 'twelve','13' => 'thirteen', '14' => 'fourteen','15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen','18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty','30' => 'thirty', '40' => 'forty', '50' => 'fifty','60' => 'sixty', '70' => 'seventy','80' => 'eighty', '90' => 'ninety');$digits = array('', 'hundred', 'thousand', 'lakh', 'crore');while($i 9)? 's': null;$hundred =($counter == 1 && $str[0])? ' and ': null;$str [] =($number setActiveSheetIndex(0)->setCellValue('A32', $index)->setCellValue('B32', $productName)->setCellValue('E32', round($weight).' Kg x '.round($qtyOrdered))->setCellValue('F32', 'Kg')->setCellValue('H32', round($totalWeight))->setCellValue('H43', round($totalWeight))->setCellValue('J32', $unitBasePrice)//->setCellValue('B44', "C T-3 No:".$ctNumber)//->setCellValue('I53', 'Sub Total')//->setCellValue('I54', 'VAT 5.5%')->setCellValue('K53', $vat55)->setCellValue('K52', $totalBasePrice)->setCellValue('K57', round($totalAmount))->setCellValue('C57', ucwords($result. "Rupees only "))->setCellValue('K32', $totalBasePrice)//->setCellValue('D51', 'po:')->setCellValue('D50',$poNumber)//->setCellValue('I55', 'VAT 14.5%')->setCellValue('K54', $vat145);//->setCellValue('I49','C.Ex. 12.50 %');$centralExcise = $order->getTotalCentralExcise();$number1 = $centralExcise;$no = round($number1);$point = round($number1- $no, 2) * 100;$hundred = null;$digits_1 = strlen($no);$i = 0;$str = array();$words = array('0' => '', '1' => 'one', '2' => 'two','3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six','7' => 'seven', '8' => 'eight', '9' => 'nine','10' => 'ten', '11' => 'eleven', '12' => 'twelve','13' => 'thirteen', '14' => 'fourteen','15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen','18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty','30' => 'thirty', '40' => 'forty', '50' => 'fifty','60' => 'sixty', '70' => 'seventy','80' => 'eighty', '90' => 'ninety');$digits = array('', 'hundred', 'thousand', 'lakh', 'crore');while($i 9)? 's': null;$hundred =($counter == 1 && $str[0])? ' and ': null;$str [] =($number1 setActiveSheetIndex(0)->setCellValue('D48', "Nill Against Form CT- 3")->setCellValue('K49', "Nill");} else{$objPHPExcel->setActiveSheetIndex(0)->setCellValue('K48', $centralExcise)->setCellValue('A46', ucwords("Total Excise duty Payable Rs:". $result1. "Rupees only", ":"));}}}$rendererName = \PHPExcel_Settings::PDF_RENDERER_TCPDF;$rendererLibraryPath = '/var/www/html/magento/vendor/tecnick.com/tcpdf';\PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath);$path = "document/attachment/".$invoice->getIncrementId().".xlsx";//$path = "document/attachment/".$invoice->getIncrementId().".PDF";$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');//$objWriter->setSheetIndex(0);$objWriter->save($path);return array($path,$billingAddress,$shippingAddress,$CustomerEmail);}}di.xml
 <?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Controller\ResultFactory;
use Sm\Customerprice\Model\Customerprice;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use \Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Mail\Message;
use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Mail\TransportInterfaceFactory;
use Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice\Mail\Template\TransportBuilder;

require_once BP . '/lib/internal/Phpexcel/PHPExcel.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/IOFactory.php';
require_once BP . '/lib/internal/Phpexcel/PHPExcel/Writer/Excel2007.php';


$rendererLibrary = 'mPDF5.4';

$rendererLibraryPath = '/lib/internal/MPDF57/.' . $rendererLibrary;

class Email extends \Magento\Backend\App\Action
{

    
    protected $resultForwardFactory;
    private $_transportBuilder;
    
    
    public function __construct(

        \Magento\Backend\App\Action\Context $context,
        //\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
        PageFactory $resultPageFactory,
        CollectionFactory $salesOrderCollectionFactory,
        Customerprice $customerPrice,
        TransportBuilder $transportBuilder
    ) {
        $this->resultPageFactory = $resultPageFactory;
        //$this->_fileFactory = $fileFactory;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->salesOrderCollectionFactory = $salesOrderCollectionFactory;
        $this->customerPrice = $customerPrice;
        $this->_transportBuilder = $transportBuilder;
        parent::__construct($context,$resultForwardFactory);
        
    }

    /**
     * Notify user
     *
     * @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {

        $invoiceId = $this->getRequest()->getParam('invoice_id'); 

        if ($invoiceId) {
            
            $invoice = $this->_objectManager->create('Magento\Sales\Api\InvoiceRepositoryInterface')->get($invoiceId);
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); 
                $base = $dir->getRoot();
                $path = $base."/document/attachment/".$invoice->getIncrementId().'.xlsx';
            if ($invoice) {
            try{                
          
                $excelPath = $this->createExcel($invoice);
                $storeManager = $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface');
                $baseUrl = $storeManager->getStore()->getBaseUrl();
                
                
                $filePath =  $baseUrl . $excelPath[0]; 
                
                //header("Location: $filePath");
                
                if (!$invoice) {
                    return $this->resultForwardFactory->create()->forward('noroute');
                }

                //$this->_objectManager->create('Magento\Sales\Api\InvoiceManagementInterface')->notify($invoice->getEntityId());
            $resource        = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');
            $connection      = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

              $invoiceItemsGrid = $connection->fetchAll("SELECT order_increment_id FROM sales_invoice_grid WHERE entity_id = '".$invoice->getEntityId()."' ");
                
                $templateParams=array('invoice' => $invoice->getIncrementId() , 
                'order' => $invoiceItemsGrid[0]['order_increment_id'] , 
                'BillingAddressFirstName' => $excelPath[1]->getFirstName() ,
                'BillingAddressLastName' => $excelPath[1]->getLastName(),
                'CompanyBillingAddress' => $excelPath[1]->getCompany(),
                'StreetBillingAddress'=> $excelPath[1]['street'],
                'CityBillingAddress'=> $excelPath[1]->getCity(),
                'RegionBillingAddress'=> $excelPath[1]->getRegion(),
                'postCodeBillingAddress'=> $excelPath[1]->getPostCode(),
                'CountryBillingAddress'=> $excelPath[1]->getCountryId(),
                'TelephoneBillingAddress'=> $excelPath[1]->getTelephone(),
                'ShippingAddressFirstName'=> $excelPath[2]->getFirstName(),
                'ShippingAddressLastName'=> $excelPath[2]->getLastName(),
                'CompanyShippingAddress'=> $excelPath[2]->getCompany(),
                'StreetShippingAddress'=> $excelPath[1]['street'],
                'CityShippingAddress'=> $excelPath[2]->getCity(),
                'RegionShippingAddress'=> $excelPath[2]->getRegion(),
                'postCodeShippingAddress'=> $excelPath[2]->getPostCode(),
                'CountryShippingAddress'=> $excelPath[2]->getCountryId(),
                'TelephoneShippingAddress'=> $excelPath[2]->getTelephone()
                );   
                $transport = $this->_transportBuilder;
                    $transport->setTemplateIdentifier('sales_email_invoice_template');
                    $transport->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1));
                    $transport->setTemplateVars($templateParams);
                    $transport->setFrom(array('name' => 'Sales','email' => '[email protected]'));
                    $transport->setReplyTo('[email protected]');
                    $transport->addTo($excelPath[3]);
               
               $transport->addAttachment(file_get_contents($path),'application/octet-stream','attachment','base64',$invoice->getIncrementId().'.xlsx'); 

                 

            $transport->getTransport()->sendMessage();
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);   
            $this->messageManager->addSuccess(__('You sent the message.')); 
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect; 
                    
        }catch(\Exception $e){
            print_r($e->getMessage());exit;
        }   
                
                die();
            
            }
            else 
            {
                return $this->resultForwardFactory->create()->forward('noroute');
            }
        }           

    }
    
    public function createExcel(\Magento\Sales\Model\Order\Invoice $invoice)
    {
            
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load("//var/www/html/magento/app/code/Sm/Templates/KlauzInvoicePdf.xlsx");
        $xlsName = $invoice->getIncrementId().'.xlsx';

        //echo $xlsName;
        
        $orderId = $invoice->getOrderId();


        $invoiceNumber = $invoice->getInvoiceNumber();
        //echo "Invoice number ".$invoiceNumber ;
        $createdAt = $invoice->getCreatedAt();
        //echo "Created datetime ".$createdAt;
        $billingAddress = $invoice->getBillingAddress();
        //echo "billing address";
        //echo "first name ". $billingAddress['firstname'];
        if ($billingAddress){
            $billName = 'M/s '.$billingAddress['firstname']. ' '.$billingAddress['lastname'];
            $billAddr1 = $billingAddress['street']. ' '. $billingAddress['city'];
            $billAddr2 = $billingAddress['region']. ' '. $billingAddress['postcode'];
        }
        
        $shippingAddress = $invoice->getShippingAddress();
        
        if ($shippingAddress){
            $shipName = 'M/s '.$shippingAddress['firstname']. ' '.$shippingAddress['lastname'];
            $shipAddr1 = $shippingAddress['street']. ' '. $shippingAddress['city'];
            $shipAddr2 = $shippingAddress['region']. ' '. $shippingAddress['postcode'];
        }
        //echo "shipping address";
        //echo "lastname ". $shippingAddress['lastname'];
        $order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);

        $dateCreateAt=date_create($createdAt);
        $dateFormatted=date_format($dateCreateAt,"d.m.Y");
        $timeFormatted = date_format($dateCreateAt,"H:i");
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('K3', $invoiceNumber)
                ->setCellValue('I4', "Date: ".date("d.m.Y"))
                ->setCellValue('G6', $dateFormatted)
                ->setCellValue('J6', $timeFormatted)
        ->setCellValue('F11', $billName)
        ->setCellValue('F12', $billAddr1)
        ->setCellValue('F13', $billAddr2)
        ->setCellValue('F16', $shipName)
        ->setCellValue('F17', $shipAddr1)
        ->setCellValue('F18', $shipAddr2);


        if ($order) {

            //echo " get dispatch method ".$order->getdispatchMethod();
            $dispatchMethod = $order->getdispatchMethod();
            //echo " Lorry number ".$order -> getLrNumber();
            $lrNumber = $order -> getLrNumber();
            //echo " CT3 Form number" .$order -> getCtForm();
            //echo " customer id " .$order-> getCustomerId();
            $customerRepository = $this->_objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
            $customerId = $order-> getCustomerId();
            $customer = $customerRepository->getById($order-> getCustomerId());
            $CustomerEmail = $customer->getEmail();
            $cattrValue = $customer->getCustomAttribute('tin_number');
            //print_r($cattrValue);
            if ($cattrValue){
            //echo "tin ".$cattrValue -> getValue();
            $customerTIN = $cattrValue -> getValue();
            }
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('H20', 'Mode of transport')
            ->setCellValue('H21', $lrNumber)
            ->setCellValue('H19', ucwords($dispatchMethod,"_"))
            //->setCellValue('B44', 'CT3 number')
            ->setCellValue('D51',$customerTIN);
            //print the order lines
            $orderItems = $order->getAllItems();
            $productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
            $index = 1;
            $weight = 0;
            $qtyOrdered = 0;
            $productName = "";
            $unitBasePrice = 0;
            
            foreach ($orderItems as $oItem){

                $productType = $oItem->getProductType();

                if ($productType == 'simple'){
                $qtyOrdered = $oItem->getQtyOrdered();

                $productName = $oItem->getName();

                $weight = $oItem->getWeight();

                /*$qtyInKgs = $oItem->getQtyInKgs();
                echo "qtyInKgs ordered" .$qtyInKgs;
                */
                $productId = $oItem->getProductId();

                $_product = $this->_objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
                        $_productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
                $_productParent = $_productCollection -> load($_product[0]);
                $parentProductSku = $_productParent->getSku();
                $productChild = $productCollection->load($productId);
                $optionId = $productChild->getData('packing_box');
                $attribute = $productChild->getResource()->getAttribute('packing_box');
                $packing = $attribute->getSource()->getOptionText($optionId);
                $customerBasePrice = $this->customerPrice->getCollection()->addFieldToFilter('customer_id',$customerId)
                                                                                              ->                    addFieldToFilter('product_sku',$parentProductSku)
                ->addFieldToFilter('start_time',array("lteq" => $createdAt))
                ->addFieldToFilter('end_time',array("gteq" => $createdAt));

                if (sizeof($customerBasePrice) != 0){
                    foreach($customerBasePrice as $customerBasePrice){
                        switch ($packing) {
                        case "1 Kg/ltr":
                            $unitBasePrice = $customerBasePrice->getUnitPriceOne();
                            break;
                        case "5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceFive();
                            break;
                        case "20 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceTwenty();
                            break;
                        case "Brl+5 Kg";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlFive();
                            break;
                        case "Brl+Brl";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlBrl();
                            break;
                        }
                    }
                }
                }
                //write onto XL


                $totalWeight = $weight * $qtyOrdered;
                $vat55 = $order->getTotalVatOne();
                            $totalAmount = $order->getTotalAmount();
                            $totalBasePrice = $order->getTotalBasePrice();
                            $ctNumber = $order->getCtNumber();
                            $poNumber = $order->getpoNumber();
                //echo "vat55" . strval($vat55);
                //print_r($vat55);
                $vat145 = $order->getTotalVatTwo();
                        //echo "vat145". $vat145;

                $number = $totalAmount;
                $no = round($number);
                $point = round($number - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                                '13' => 'thirteen', '14' => 'fourteen',
                                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                                '60' => 'sixty', '70' => 'seventy',
                                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    
                    if ($number) {
                        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number < 21) ? $words[$number] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number / 10) * 10]
                        . " " . $words[$number % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;                 
                    } 
                    else 
                        $str[] = null;
                }
                
                $str = array_reverse($str);
                $result = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result . "Rupees  " . $points . " Paise";*/




                $objPHPExcel->setActiveSheetIndex(0) 
                ->setCellValue('A32', $index)
                ->setCellValue('B32', $productName)
                ->setCellValue('E32', round($weight) .' Kg x '.round($qtyOrdered))
                ->setCellValue('F32', 'Kg')
                ->setCellValue('H32', round($totalWeight))
                                    ->setCellValue('H43', round($totalWeight))
                ->setCellValue('J32', $unitBasePrice)
                                    //->setCellValue('B44', "C T-3 No:".$ctNumber)
                //->setCellValue('I53', 'Sub Total')
                //->setCellValue('I54', 'VAT 5.5%')
                ->setCellValue('K53', $vat55)
                                    ->setCellValue('K52', $totalBasePrice)
                                    ->setCellValue('K57', round($totalAmount))
                                    ->setCellValue('C57', ucwords($result. "Rupees only "))
                                    ->setCellValue('K32', $totalBasePrice)
                                    //->setCellValue('D51', 'po:')
                                    ->setCellValue('D50',$poNumber)
                //->setCellValue('I55', 'VAT 14.5%')
                ->setCellValue('K54', $vat145);
                //->setCellValue('I49','C.Ex.  12.50 %');


                $centralExcise = $order->getTotalCentralExcise();
                                         
                $number1 = $centralExcise;
                $no = round($number1);
                $point = round($number1 - $no, 2) * 100;
                $hundred = null;
                $digits_1 = strlen($no);
                $i = 0;
                $str = array();
                $words = array('0' => '', '1' => 'one', '2' => 'two',
                '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
                '7' => 'seven', '8' => 'eight', '9' => 'nine',
                '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
                '13' => 'thirteen', '14' => 'fourteen',
                '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
                '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
                '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
                '60' => 'sixty', '70' => 'seventy',
                '80' => 'eighty', '90' => 'ninety');
                $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
                while ($i < $digits_1) {
                    $divider = ($i == 2) ? 10 : 100;
                    $number1 = floor($no % $divider);
                    $no = floor($no / $divider);
                    $i += ($divider == 10) ? 1 : 2;
                    if ($number1) {
                        $plural = (($counter = count($str)) && $number1 > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number1 < 21) ? $words[$number1] .
                        " " . $digits[$counter] . $plural . " " . $hundred
                        :
                        $words[floor($number1 / 10) * 10]
                        . " " . $words[$number1 % 10] . " "
                        . $digits[$counter] . $plural . " " . $hundred;
                    } 
                    else 
                        $str[] = null;
                }
                $str = array_reverse($str);
                $result1 = implode('', $str);
                /*$points = ($point) ?
                 "." . $words[$point / 10] . " " . 
                $words[$point = $point % 10] : '';
                $result1 . "Rupees  " . $points . " Paise";*/

                        
                if ($centralExcise ==0 ){
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('D48', "Nill Against Form CT - 3")
                    ->setCellValue('K49', "Nill");
                } else {
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('K48', $centralExcise)
                                        ->setCellValue('A46', ucwords("Total Excise duty Payable Rs:" . $result1 . "Rupees only", ":"));
                }
            }
        }
        
    
    
    
    $rendererName = \PHPExcel_Settings::PDF_RENDERER_TCPDF;
    $rendererLibraryPath = '/var/www/html/magento/vendor/tecnick.com/tcpdf';
    
    \PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath);
    $path = "document/attachment/".$invoice->getIncrementId().".xlsx";
    //$path = "document/attachment/".$invoice->getIncrementId().".PDF";
    
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    //$objWriter->setSheetIndex(0);
    $objWriter->save($path);
    
    return array($path,$billingAddress,$shippingAddress,$CustomerEmail);

    }    

}

di.xml

<preference for="Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice\Email" type="Sm\Ordertype\Controller\Adminhtml\Invoice\AbstractInvoice\Email" />
Source Link
Loading