php Spreadsheet 导出,PhpSpreadsheet 导出Excel

/**

* Excel 助手

* sudo composer require phpoffice/phpspreadsheet

*/

namespace CommonUtil;

use PhpOfficePhpSpreadsheetSpreadsheet;

use PhpOfficePhpSpreadsheetWriterXlsx;

use PhpOfficePhpSpreadsheetStyleAlignment;

use PhpOfficePhpSpreadsheetStyleColor;

class ExcelUtil extends CommonUtil

{

public function __construct()

{

parent::__construct();

}

/**

* 导出数据

*/

public function exportExcel($expTitle, $expCellName, $expTableData)

{

$fileName = $expTitle;

$spreadsheet = new Spreadsheet();

// 获取活动的工作空间

$worksheet = $spreadsheet->getActiveSheet();

$cellNum = count($expCellName);

$dataNum = count($expTableData);

$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

// 合并单元格

$worksheet->mergeCells('A1:'.$cellName[$cellNum - 1] . '1');

// 设置第一格的内容

$worksheet->setCellValue('A1', $expTitle);

// 设置加粗

$worksheet->getStyle('A1')->getFont()->setBold(true);

// 设置居中

$styleArray = [

'alignment' => [

'horizontal' => Alignment::HORIZONTAL_CENTER,

],

];

$worksheet->getStyle('A1')->applyFromArray($styleArray);

// 设置颜色

$worksheet->getStyle('A1')->getFont()->getColor()->setARGB(Color::COLOR_DARKRED);

// 设置标题

$worksheet->setTitle($expTitle);

// 设置表格菜单

for ($i = 0; $i < $cellNum; $i++) {

$worksheet->setCellValue($cellName[$i] . (+2), $expCellName[$i][1]);

$worksheet->getStyle($cellName[$i] . (+2))->getFont()->setBold(true);

// 自动宽度

$worksheet->getColumnDimension($cellName[$i])->setAutoSize(true);

}

// 设置表格内容

for ($i = 0; $i < $dataNum; $i++) {

for ($j = 0; $j < $cellNum; $j++) {

$worksheet->setCellValue($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);

// 支持换行

if ($expCellName[$j][2] == 1) {

$worksheet->getStyle($cellName[$j] . ($i + 3))->getAlignment()->setWrapText(true);

}

}

}

// 设置列宽为自动

// $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);

// $worksheet->getDefaultColumnDimension()->setAutoSize(true);

// 设置行高

$worksheet->getDefaultRowDimension()->setRowHeight(20);

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件

//header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件

header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');//告诉浏览器输出浏览器名称

header('Cache-Control: max-age=0');//禁止缓存

$writer = new Xlsx($spreadsheet);

$writer->save('php://output');

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值