exceedone / exment

Exment is open source software for managing information assets on the Web. / Exmentは、情報資産をWeb上で管理するための、オープンソースソフトウェアです。
https://exment.net/docs/#
GNU General Public License v3.0
267 stars 67 forks source link

ページブラグインから、ExcelシートをExportしたい。 #1302

Open m-hagane opened 1 year ago

m-hagane commented 1 year ago

Exment Plugin の PagePlugin を使って、Excel シートを Export したい。

... /exment/vendor/exceedone/exment/src/Services/Plugin/ 内に PluginPageExportExcel.php を作成

内容は、次の通り、で実現できます。 よろしくお願いします。

m-hagane commented 1 year ago

<?php


namespace Exceedone\Exment\Services\Plugin;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * Plugin (Page) base class for excel
 */
abstract class PluginPageExportExcel extends PluginPageBase
{

    /**
     * Initialize excel
     *
     * @param string $templateFileName If read template file, set filename
     * @return \PhpOffice\PhpSpreadsheet\Spreadsheet
     */
    protected function initializeExcel($templateFileName = null)
    {
        $reader = IOFactory::createReader('Xlsx');

        if (isset($templateFileName)) {
            $reader = IOFactory::createReader('Xlsx');

            $filePath = $this->plugin->getFullPath($templateFileName);
            if (!\File::exists($filePath)) {
                //TODO:template file not found
                throw new \Exception();
            }

            $spreadsheet = $reader->load($filePath);
            return $spreadsheet;
        }

        return new Spreadsheet();
    }

    /**
     * Get result
     *
     * @param \PhpOffice\PhpSpreadsheet\Spreadsheet $spreadsheet
     * @return string tmp file name.
     */
    protected function getExcelResult($spreadsheet)
    {
        // output excel
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->setIncludeCharts(true);
        //$writer->setPreCalculateFormulas(true);
        $writer->save($this->getTmpFullPath());

        return $this->getTmpFullPath();
    }

    /**
     * get Directory full path from root
     * @return string File path
     */
    public function getTmpFullPath()
    {
        if (isset($this->tmpFullPath)) {
            return $this->tmpFullPath;
        }

        $file = make_uuid();
        $this->tmpFullPath = getFullpath($file, Define::DISKNAME_ADMIN_TMP);
        return $this->tmpFullPath;
    }
}