Hyperf 框架中使用phpspreadsheet库导出excel
Hyperf结合phpspreadsheet库可以非常方便的导出excel文档,鉴于网上当前文档较少,特写下此blog,若有不足之处,欢迎指正。
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class ExportExcelHandle
{
private $sheet;
private $spreadsheet;
private $row;
public function __construct()
{
// Create new Spreadsheet object
$this->spreadsheet = new Spreadsheet();
// Set document properties
$this->spreadsheet->getProperties()->setCreator('Maarten Balliauw')
->setLastModifiedBy('Maarten Balliauw')
->setTitle('Office 2007 XLSX Test Document')
->setSubject('Office 2007 XLSX Test Document')
->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.')
->setKeywords('office 2007 openxml php')
->setCategory('Test result file');
// Add some data
$this->spreadsheet->setActiveSheetIndex(0);
$this->sheet = $this->spreadsheet->getActiveSheet();
// Rename worksheet
$this->spreadsheet->getActiveSheet()->setTitle('Sheet1');
}
public function setHeader($title)
{
foreach ($title as $key => $item) {
$this->sheet->setCellValue(chr($key + 65) . '1', $item);
}
$this->row = 2; // 从第二行开始
return $this;
}
public function addData($data)
{
foreach ($data as $item) {
$dataCol = 'A';
foreach ($item as $value) {
// 单元格内容写入
$this->sheet->setCellValue($dataCol . $this->row, $value);
$dataCol++;
}
$this->row++;
}
return $this;
}
public function save($fileName)
{
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$this->spreadsheet->setActiveSheetIndex(0);
$fileName = $fileName . '.xlsx';
$url = '/storage/export_excel/' . $fileName;
$outFilename = BASE_PATH . $url;
$writer = IOFactory::createWriter($this->spreadsheet, 'Xlsx');
$writer->save($outFilename);
$this->spreadsheet->disconnectWorksheets();
unset($this->spreadsheet);
return ['path'=>$outFilename,'filename'=>$fileName];
}
}
该类调用方法:
$exportService = new ExportExcelHandle();
//$title 表头 $data 数据 $fileName 保存的文件名
$exportService->setHeader($title)->addData($data)->save($fileName);
控制器中导出下载文件
return $this->response->download($result['path'], $result['filename']);