«

如何使用ThinkPHP8实现导出Excel数据表格功能案例

腾逍技术 发布于 阅读:376 PHP


这篇文章主要为大家详细介绍了如何使用ThinkPHP8导出Excel数据表格功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

1、开发版本

Think PHP8.0、PHP8.0,并非低版不能用,仅因本人当前版本如此。

部分参数需自行进行修改,具体查看执行代码.

Excel有默认的表格样式,如需修改,根据实际应用场景进行设置即可。

2、实现原理

1.安装Spreadsheet

1
composer require phpoffice/phpspreadsheet

2.确定数据表头

1
2
3
4
5
$header = [
  ['key' => 'index', 'title' => '序号'],
  ['key' => 'activity_title', 'title' => '列1名称'],
  ['key' => 'room_name', 'title' => '列2名称'],
];

3.确定数据列

1
$list = [];  //    定义数据内容,根据实际应用场景来写即可。

4.调用封装类,导出数据

3、核心代码

1.调用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//  表头
$header = [
  ['key' => 'index', 'title' => '序号'],
  ['key' => 'activity_title', 'title' => '列1名称'],
  ['key' => 'room_name', 'title' => '列2名称'],
];
$list = [];
//  实例化excel
$sheet = new Spreadsheet();
//  实例化导出类
$export = new Excel($sheet, 0);
//  设置单元格表头
$export->setHeader($header);
//  设置单元格数据
$export->setContent($list, $header);
//  导出:文件名称、sheet名称,返回结果为本地文件存储路径
$res = $export->export($fileName, $sheetName);

2.Excel核心控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php
  
namespace app\common\controller;
  
/**
 * @note Excel操作
 */
class Excel
{
  
    //  定义表格对象
    protected object $sheet;
  
    public function __construct(object $sheet, $sheetIndex = 0)
    {
        $this->sheet = $sheet;
        if (!is_object($this->sheet)) $this->sheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $this->sheet->getActiveSheet($sheetIndex);
    }
  
    /**
     * @notes 设置表头
     * @param array $header 表头数据
     * @param string|int $startRow 默认第一行
     */
    public function setHeader(array $header, string|int $startRow = 1): object
    {
        $header = array_values($header);
        //  计算总列数
        $column = $this->getColumn(count($header));
        foreach ($header as $key => $value) {
            $columnName = $column[$key] . $startRow;
            //  设置单元格值
            $this->sheet->getActiveSheet()->setCellValue($columnName, $value['title']);
            //  设置单元格自适应宽度
            $this->sheet->getActiveSheet()->getColumnDimension($column[$key])->setAutoSize(true);
            //  设置单元格自适应高度
            $this->sheet->getActiveSheet()->getRowDimension($startRow)->setRowHeight(24);
        }
        $startColumn = $column[0] . $startRow;
        $endColumn = $column[count($header) - 1] . $startRow;
        //  设置字体大小及加粗
        $this->sheet->getActiveSheet()->getStyle($startColumn . ':' . $endColumn)->getFont()->setBold(true)->setSize(12);
        //  设置单元格水平居中
        $this->sheet->getActiveSheet()->getStyle($startColumn . ':' . $endColumn)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        //  设置单元格垂直居中
        $this->sheet->getActiveSheet()->getStyle($startColumn . ':' . $endColumn)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
        //  设置单元格边框
        $this->sheet->getActiveSheet()->getStyle($startColumn . ':' . $endColumn)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
        return $this->sheet;
    }
  
    /**
     * @notes 设置单元格值
     * @param array $data 数据
     * @param array $header 表头数据
     * @param string|int $startRow 默认第二行开始
     */
    public function setContent(array $data, array $header, string|int $startRow = 2): object
    {
        //  获取总列数
        $column = $this->getColumn(count($header));
        //  遍历数据
        foreach ($data as $key => $value) {
            //  遍历表头
            for ($i = 0; $i < count($header); $i++) {
                //  获取单元格名称
                $columnName = $column[$i] . ($key + $startRow);
                //  设置单元格值
                $this->sheet->getActiveSheet()->setCellValue($columnName, $value[$header[$i]['key']] ?? '');
                //  设置单元格自适应宽度
                $this->sheet->getActiveSheet()->getColumnDimension($column[$i])->setAutoSize(true);
                //  设置单元格自适应高度
                $this->sheet->getActiveSheet()->getRowDimension($key + $startRow)->setRowHeight(24);
            }
        }
        $startColumn = $column[0] . $startRow;
        $endColumn = $column[count($column) - 1] . count($data) + $startRow - 1;
        //  设置字体大小及加粗
        $this->sheet->getActiveSheet()->getStyle($startColumn . ':' . $endColumn)->getFont()->setBold(false)->setSize(11);
        //  设置单元格水平居中
        $this->sheet->getActiveSheet()->getStyle($startColumn . ':' . $endColumn)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        //  设置单元格垂直居中
        $this->sheet->getActiveSheet()->getStyle($startColumn . ':' . $endColumn)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
        //  设置单元格边框
        $this->sheet->getActiveSheet()->getStyle($startColumn . ':' . $endColumn)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
        return $this->sheet;
    }
  
    /**
     * @notes 导出数据
     * @param string $fileName 文件名
     * @param string $sheetName 表名
     * @return string
     */
    public function export(string $fileName, string $sheetName = 'Sheet1'): string
    {
        //  设置表格标题
        $this->sheet->getActiveSheet()->setTitle($sheetName);
        //  设置表格格式
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($this->sheet);
        //  设置存储路径
        $basePath = public_path();
        $path = 'activity_sequence_template/';
        $fullPath = $basePath . $path . $fileName . '.xlsx';
        if (!is_dir($basePath . $path)) mkdir($basePath . $path, 0777, true);
        $writer->save($fullPath);
        return $path . $fileName . '.xlsx';
//        //  设置响应头
//        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
//        header('Cache-Control: max-age=0');
//        //  导出数据
//        $writer->save('php://output');
    }
  
    /**
     * @notes 自动计算列数
     * @param int|string $colNumber
     * @return array
     */
    protected function getColumn(int|string $colNumber = 1): array
    {
        //  生成A-Z的数组
        $arr = range('A', 'Z');
        //  计算循环次数
        $no = ceil($colNumber / count($arr));
        //  定义数组
        $data = [];
        if ($no <= 1) {
            for ($i = 0; $i < $colNumber; $i++) {
                $data[] = $arr[$i];
            }
        } else {
            for ($i = 0; $i < count($arr); $i++) {
                $data[] = $arr[$i];
            }
            for ($i = 0; $i < $colNumber - count($arr); $i++) {
                $list = (($i + count($arr)) % count($arr));
                $data[] = $arr[ceil(($i + 1) / count($arr)) - 1] . $arr[$list];
            }
        }
        return $data;
    }
}

到此这篇关于使用ThinkPHP8实现导出Excel数据表格功能的文章就介绍到这了!