问题描述
我有 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 (将#修改为@)