TP5使用Composer安装phpoffice/phpspreadsheet,导出Excel文件
TP5使用Composer安装phpoffice/phpspreadsheet,导出Excel文件
1、composer安装:
https://getcomposer.org/download/ 下载Composer
composer require phpoffice/phpspreadsheet
2.点击导出按钮,触发控制器里面的方法 wdjzdc()
- 在控制中引入
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
复制代码
//wdjzdc数据导出
public function wdjzdc()
{
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
//设置工作表标题名称
$worksheet->setTitle(‘wdjz客户表’);
//表头
//设置单元格内容
$worksheet->setCellValueByColumnAndRow(1, 1, ‘wdjz无毒样板客户表’);
$worksheet->setCellValueByColumnAndRow(1, 2, ‘name’);
$worksheet->setCellValueByColumnAndRow(2, 2, ‘phone’);
$worksheet->setCellValueByColumnAndRow(3, 2, ‘radio1’);
$worksheet->setCellValueByColumnAndRow(4, 2, ‘style’);
$worksheet->setCellValueByColumnAndRow(5, 2, ‘time’);
//合并单元格
$worksheet->mergeCells(‘A1:E1’);
$styleArray = [
'font' => [
'bold' => true
],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
],
];
//设置单元格样式
w
o
r
k
s
h
e
e
t
−
>
g
e
t
S
t
y
l
e
(
′
A
1
′
)
−
>
a
p
p
l
y
F
r
o
m
A
r
r
a
y
(
worksheet->getStyle('A1')->applyFromArray(
worksheet−>getStyle(′A1′)−>applyFromArray(styleArray)->getFont()->setSize(28);
$worksheet->getStyle('A2:E2')->applyFromArray($styleArray)->getFont()->setSize(14);
;
$jzInfo = db('wdjz')->select();
$len = count($jzInfo);
$j = 0;
for ($i=0; $i < $len; $i++) {
$j = $i + 3; //从表格第3行开始
$worksheet->setCellValueByColumnAndRow(1, $j, $jzInfo[$i]['name']);
$worksheet->setCellValueByColumnAndRow(2, $j, $jzInfo[$i]['phone']);
$worksheet->setCellValueByColumnAndRow(3, $j, $jzInfo[$i]['radio1']);
$worksheet->setCellValueByColumnAndRow(4, $j, $jzInfo[$i]['style']);
$worksheet->setCellValueByColumnAndRow(5, $j, $jzInfo[$i]['time']);
}
$styleArrayBody = [
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => ['argb' => '666666'],
],
],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
],
];
$total_jzInfo = $len + 2;
//添加所有边框/居中
w
o
r
k
s
h
e
e
t
−
>
g
e
t
S
t
y
l
e
(
′
A
1
:
C
′
.
worksheet->getStyle('A1:C'.
worksheet−>getStyle(′A1:C′.total_jzInfo)->applyFromArray($styleArrayBody);
$filename = 'wdjz无毒样板客户表.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
}