public function export($file = '') { if (empty($file)) { $file = static::generateFile(); } $this->_phpExcel = new \PHPExcel(); $this->_worksheet = $this->_phpExcel->setActiveSheetIndex(0); $file = str_ireplace(['{categoryId}'], [$this->categoryId], $file); $templateItem = new Item(); $templateSeo = new SeoText(); $export = $this->getExport(); $this->_worksheet->setTitle($this->_category->title); // Пишем заголовки foreach ($export as $exportIndex => $exportValue) { $columnIndex = \PHPExcel_Cell::stringFromColumnIndex($exportIndex) . '1'; if (isset($exportValue[2]) && is_array($exportValue[2]) && isset($exportValue[2]['label'])) { $label = $exportValue[2]['label']; } else { switch ($exportValue[0]) { case static::TYPE_ATTRIBUTE: $label = $templateItem->getAttributeLabel($exportValue[1]); break; case static::TYPE_FIELD: $field = $this->_category->getFieldByName($exportValue[1]); $label = $field->title; break; case static::TYPE_SEO: $label = $templateSeo->getAttributeLabel($exportValue[1]); break; case static::TYPE_CUSTOM: $label = $exportValue[2]['label']; break; } } $this->_worksheet->setCellValue($columnIndex, $label); } $items = $this->_category->getItems()->all(); foreach ($items as $itemIndex => $item) { foreach ($export as $exportIndex => $exportValue) { $value = ''; switch ($exportValue[0]) { case static::TYPE_FIELD: $value = ArrayHelper::getValue($item->data, $exportValue[1]); break; case static::TYPE_ATTRIBUTE: $value = $item->{$exportValue[1]}; break; case static::TYPE_CUSTOM: $value = $exportValue[2]['get']($item); break; case static::TYPE_SEO: $value = $item->seo->{$exportValue[1]}; break; } $this->_worksheet->setCellValue(\PHPExcel_Cell::stringFromColumnIndex($exportIndex) . ($itemIndex + 2), $value); if (isset($exportValue[2]['type'])) { switch ($exportValue[2]['type']) { case static::CELL_TYPE_HYPERLINK: $this->_worksheet->getCell(\PHPExcel_Cell::stringFromColumnIndex($exportIndex) . ($itemIndex + 2))->getHyperlink()->setUrl('"' . $value . '"'); break; } } if (isset($exportValue[2]['width'])) { $this->_worksheet->getColumnDimension(\PHPExcel_Cell::stringFromColumnIndex($exportIndex))->setWidth($exportValue[2]['width']); } } } $writer = \PHPExcel_IOFactory::createWriter($this->_phpExcel, 'Excel2007'); @\yii\helpers\FileHelper::createDirectory(dirname($file)); $writer->save($file); return $file; header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="' . basename($file) . '"'); header('Cache-Control: max-age=0'); readfile($file); exit; }