1 回答
TA贡献1824条经验 获得超5个赞
表单事件的实现可能相当混乱,很难找到示例,所以当我看到这样的帖子时,我会尝试伸出援手。首先,我会说您真的应该查看这些附加功能的PHPSpreadsheet 文档。在这里您可以找到所需的重要信息。然后你可以翻译你在Laravel Excel中使用的内容。
PHPSpreadsheet:在单元格上设置数据验证 https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#setting-data-validation-on-a-cell
这是一个基于您现有文件的示例。我还加入了一些额外的格式来自动调整列宽——我认为这是必须的。
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
class ActionItemExport implements FromCollection, WithHeadings, WithEvents, WithStrictNullComparison
{
protected $results;
public function collection()
{
// store the results for later use
$this->results = $this->getActionItems();
return $this->results;
}
// ...
public function registerEvents(): array
{
return [
// handle by a closure.
AfterSheet::class => function(AfterSheet $event) {
// get layout counts (add 1 to rows for heading row)
$row_count = $this->results->count() + 1;
$column_count = count($this->results[0]->toArray());
// set dropdown column
$drop_column = 'A';
// set dropdown options
$options = [
'option 1',
'option 2',
'option 3',
];
// set dropdown list for first data row
$validation = $event->sheet->getCell("{$drop_column}2")->getDataValidation();
$validation->setType(DataValidation::TYPE_LIST );
$validation->setErrorStyle(DataValidation::STYLE_INFORMATION );
$validation->setAllowBlank(false);
$validation->setShowInputMessage(true);
$validation->setShowErrorMessage(true);
$validation->setShowDropDown(true);
$validation->setErrorTitle('Input error');
$validation->setError('Value is not in list.');
$validation->setPromptTitle('Pick from list');
$validation->setPrompt('Please pick a value from the drop-down list.');
$validation->setFormula1(sprintf('"%s"',implode(',',$options)));
// clone validation to remaining rows
for ($i = 3; $i <= $row_count; $i++) {
$event->sheet->getCell("{$drop_column}{$i}")->setDataValidation(clone $validation);
}
// set columns to autosize
for ($i = 1; $i <= $column_count; $i++) {
$column = Coordinate::stringFromColumnIndex($i);
$event->sheet->getColumnDimension($column)->setAutoSize(true);
}
},
];
}
}
- 1 回答
- 0 关注
- 441 浏览
添加回答
举报
