微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 maatawebsite/excel 3.1 版获取下拉列表中的数据

如何解决如何使用 maatawebsite/excel 3.1 版获取下拉列表中的数据

我有 PHP 版本 7.3 和 Laravel 版本 ID >=5.5。我需要将模板数据从数据库导出到 excel。为此,我使用了 "maatwebsite/excel": "^3.1"。 我必须在 drop-down list显示类别,以便用户在导入时可以从中进行选择。 在这里,我附上了 image

如何使用 3.1 版实现此目的?

示例代码

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeSheet;
use App\Models\CategoryMaster;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\Withheadings;

class CompanyExport implements  WithEvents{

use Exportable;

protected $request;
protected $results;

function __construct($request){
    $this->request = $request;
}

public function collection()
{
    // store the results for later use
    $this->results = CategoryMaster::get();

    return $this->results;
}

public function registerEvents(): array
{
    return [
        BeforeSheet::class => function(BeforeSheet $event) {
            
            $sheet = $event->sheet;
            $sheet->append(['name','category']);
            $cntCat = CategoryMaster::count();
            
            $income = CategoryMaster::where('level',1)->get();
                           

            $generateCell = function($accounts,$sheet,&$row) use(&$generateCell)
            {
                foreach ($accounts as $account) 
                {
                    $sheet->append([$account->name],'A'.$row++);
                    
                }
                return $sheet;
            };
            $row = 1;
            $sheet->append(['Income'],'A'.$row++);
            $sheet = $generateCell($income,$row);
    
        },AfterSheet::class => function(AfterSheet $event){
             $sheet = $event->sheet;
            $objValidation = $sheet->getCell('A2')->getDataValidation();
            $objValidation->setType(DataValidation::TYPE_LIST );
            $objValidation->setErrorStyle(DataValidation::STYLE_informatION );
            $objValidation->setAllowBlank(false);
            $objValidation->setShowInputMessage(true);
            $objValidation->setShowErrorMessage(true);
            $objValidation->setShowDropDown(true);
            $objValidation->setErrorTitle('Input error');
            $objValidation->setError('Value is not in list.');
            $objValidation->setPromptTitle('Pick from list');
            $objValidation->setPrompt('Please pick a value from the drop-down list.');
            $options = [
                'option 1','option 2','option 3',];
            $objValidation->setFormula1(sprintf('"%s"',implode(',',$options)));
            for ($i = 3; $i <= 200; $i++) {
                $sheet->getCell("C{$i}")->setDataValidation(clone $objValidation);
            }
         }
     ];
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。