本文主要是介绍使用PhpOffice\PhpSpreadsheet生成Excel表格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、安装PhpOffice\PhpSpreadsheet
composer require phpoffice/phpspreadsheet
2、引入
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
3、使用
set_time_limit(0);$spreadsheet = new Spreadsheet();//合并单元格$spreadsheet->getActiveSheet()->mergeCells('A1:E1');//设置自动高度$spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);//设置宽度$spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(100);//设置字体为粗体$spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);//设置表头$spreadsheet->getActiveSheet()->getCell('A1')->setValue('销售汇总单(' . $date . ')');//设置自动换行$spreadsheet->getActiveSheet()->getStyle('A3:I20')->getAlignment()->setWrapText(true);//设置水平、垂直居中$styleArray = ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,],];$worksheet = $spreadsheet->getActiveSheet();$worksheet->getStyle('A1:E100')->applyFromArray($styleArray);$title = ['序号', '商品名称', '规格'];foreach ($title as $index => $item) {$worksheet->setCellValueByColumnAndRow($index + 1, 2, $item);}$data = [['no' => 1, 'product_name' => '苹果', 'package' => '1斤'],['no' => 2, 'product_name' => '香蕉', 'package' => '2斤']]$row = 2; // 从第二行开始foreach ($data as $item) {$column = 1;foreach ($item as $value) {// 单元格内容写入$worksheet->setCellValueByColumnAndRow($column, $row, $value);$column++;}$row++;}header('Content-Type: application/vnd.ms-excel');header('Content-Disposition: attachment;filename="销售汇总单('. date('Y-m-d') .')'.'.xlsx"');header('Cache-Control: max-age=0');$writer = new Xlsx($spreadsheet);$writer->save('php://output');
这篇关于使用PhpOffice\PhpSpreadsheet生成Excel表格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!