directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); } protected function getHeaders() { return [ 'Lab Id', 'PI SAP Id', '订货账户', '经销商', '销售', ]; } protected function getRowFields() { return [ 'lab_code', 'pi_sap_id', 'booking_account', 'customer_name', 'salesperson_name' ]; } /** * @param Lab\Collection $data * @return array * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ public function write(Lab\Collection $data) { $styles = [ 'alignment' => [ 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, ], ]; $spreadSheet = new Spreadsheet(); $writer = IOFactory::createWriter($spreadSheet, 'Xlsx'); $worksheet = $spreadSheet->getActiveSheet(); $columnIndex = 'A'; foreach ($this->getHeaders() as $row) { $cell = $worksheet->getCell($columnIndex.'1'); $cell->getAppliedStyle()->applyFromArray($styles); $cell->setValue($row); $columnIndex++; } $worksheet->getRowDimension(1)->setRowHeight(20); $rowIndex = 2; foreach ($data as $lab) { $columnIndex = 'A'; /* @var $lab \Stemcell\Customer\Model\Lab */ foreach ($this->getRowFields() as $field) { $worksheet->getColumnDimension($columnIndex)->setWidth(15); $worksheet->getRowDimension($rowIndex)->setRowHeight(20); $cell = $worksheet->getCell($columnIndex.$rowIndex); $cell->getAppliedStyle()->applyFromArray($styles); $cell->setValue($lab->getData($field)); $columnIndex++; } $rowIndex++; } $this->directory->create('export'); $file = $this->directory->getAbsolutePath('export/lab-'.date('YmdHis').'.xlsx'); $writer->save($file); return [ 'type' => 'filename', 'value' => $file, 'rm' => true // can delete file after use ]; } }