namespace eq;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Excel{
/**
* @description: 使用例子
* @return {*}
*/
public static function demo()
{
$fields=[
['name'=>'名称','field'=>'name'],
['name'=>'性别','field'=>'sex']
];
$list=[
['name'=>'张三','sex'=>'男'],
['name'=>'李四','sex'=>'女']
];
$name='测试demo下载'.date('YmdHis');
self::downXlsx($name,$fields,$list);
}
/**
* @description: 下载Excel文档
* @param {*} $name 生成文件名称
* @param {*} $list 数据列表
* @param {*} $fields 字段列表 [['name'=>'名称','field'=>'name'],['name'=>'手机','field'=>'phone']]
* @return {*}
*/
public static function downXlsx($name, $fields = [], $list = [])
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$letter_all=[];
$letter=['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'];
// 通过fields数量生成Excel A-Z
$item=0;
foreach($fields as $k => $v){
if($item==26){
$item=0;
}
$n=ceil(($k+1)/26);
if($n==1){
array_push($letter_all,$letter[$item]);
}else{
$n=$n-2;
array_push($letter_all,$letter[$n].$letter[$item]);
}
$item++;
}
# 生成首行标题
foreach($fields as $k => $v){
$sheet->setCellValue($letter_all[$k].'1', $v['name']);
}
// 通过传入数据生成Excel
foreach($list as $k => $v){
foreach($fields as $kk => $vv){
switch($vv['field']){
default:$value=$v[$vv['field']];;
}
$sheet->setCellValue($letter_all[$kk].($k+2), $value);
}
}
$names = $name;
//utf-8转unicode格式
$name = iconv('UTF-8', 'UCS-2BE', $name);
$len = strlen($name);
$str = '';
for ($i = 0; $i < $len - 1; $i = $i + 2) {
$c = $name[$i];
$c2 = $name[$i + 1];
if (ord($c) > 0) {
$str .= '\u' . base_convert(ord($c), 10, 16) . str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
} else {
$str .= '\u' . str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);
}
}
// header('Content-Type: application/vnd.ms-excel');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Data-Type: binary');
//前端导出数据根据这个unicode格式解析为中文
header('Data-Filename: ' . $str);
header('Content-Disposition: attachment;filename="' . $names . '.xlsx"');
header('Cache-Control: max-age=0');
header('Access-Control-Expose-Headers:Data-Type,Data-Filename');
//header('Content-Type: application/vnd.ms-excel');
//header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
//header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;
}
}