欢迎来到元素模板ys720.com,本站提供专业的织梦模板PBOOTCMS模板网站模板网站修改/网站仿站
当前位置:主页 > 程序教程 > thinkphp教程 >
thinkphp教程

ThinkPHP 5 PhpOffice/phpspreadsheet 导入和导出代码

(元素模板) / 2022-07-12 10:43

首先使用composer 安装扩展

composer require phpoffice/phpspreadsheet

创建文件 app/common/services/Phpoffice.php

Phpoffice.php 文件内容

<?php
namespace app\common\services;
use think\Controller;
use PhpOffice\PhpSpreadsheet\IOFactory;
// 给类文件的命名空间起个别名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
//Xlsx类  保存文件功能类
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// excel表
class Phpoffice
{
    /**
     * 导出excel表
     * $data:要导出excel表的数据,接受一个二维数组
     * $name:excel表的表名
     * $head:excel表的表头,接受一个一维数组
     * $key:$data中对应表头的键的数组,接受一个一维数组
     * 备注:此函数缺点是,表头(对应列数)不能超过26;
     *循环不够灵活,一个单元格中不方便存放两个数据库字段的值
     */
    public function outdata($name='测试表', $data=[], $head=[])
    {
        //计算表头数量
        $count = count($head); 
        // 实例化 Spreadsheet 对象
        $spreadsheet = new Spreadsheet();
        // 1获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();
        $styleArray = [
            // 对齐
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
            // 边框
            'borders' => [
                'outline' => [
                    //粗边框
                    // 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK, 
                    //细边框
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    //边框颜色
                    'color' => ['argb' => 'FF000000'],
                ],
            ],
        ];
        $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
        for ($i = 65; $i < $count + 65; $i++) {     //数字转字母从65开始,循环设置表头:

            $sheet->setCellValue(strtoupper(chr($i)) . '1', $head[$i - 65][0]);
            $sheet->getStyle(strtoupper(chr($i)) . '1')->applyFromArray($styleArray);
            $sheet->getStyle(strtoupper(chr($i)) . '1')->getFont()->setBold(false)->setName('宋体')->setSize(16);
        }

        /*--------------开始从数据库提取信息插入Excel表中------------------*/
        foreach ($data as $key => $item) {             //循环设置单元格:
            //$key+2,因为第一行是表头,所以写到表格时   从第二行开始写

            for ($i = 65; $i < $count + 65; $i++) {     //数字转字母从65开始:
                $sheet->setCellValue(strtoupper(chr($i)) . ($key + 2), $item[$head[$i - 65][1]]);
                $sheet->getStyle(strtoupper(chr($i)) . ($key + 2))->applyFromArray($styleArray);
                //取消科学计数
                if( $head[$i - 65][2]['science'] == 1){
                    $spreadsheet->getActiveSheet()->getStyle(strtoupper(chr($i)) . ($key + 2))->getNumberFormat() ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER);
                }
            }
        }
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');

        //删除清空:
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        return;
    }

    //导入
    public function import_data($filePath,$Extension,$keys)
    {
        //$keys 例子   
        // $atr = array(
        //     array("订单号","order_num"),
        //     array("年级","grade"),
        //     array("姓名","user_name"),
        // ); 

        // 有Xls和Xlsx和Cvs格式三种
        if ($Extension=="xls")
        {
            $reader = IOFactory::createReader('Xls');
        }elseif ($Extension=="xlsx")
        {
            $reader = IOFactory::createReader('Xlsx');
        }elseif ($Extension=="csv")
        {
            $reader = IOFactory::createReader('Csv');
        }
        //载入excel文件
        $excel = $reader->load($filePath);
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = $sheet->getHighestColumn();

        $count = ord($col_num);
        $count = $count - 64;

        for($i=2;$i<=$row_num;$i++){                                    //循环行数
            for( $x = 0; $x < $count; $x++ ){                           //循环列数
                $letter = strtoupper(chr($x + 65));         //字母
                $name = $excel->getActiveSheet()->getCell($letter.'1')->getValue();         //获取 表头名称
                foreach ($keys as $key => $value) {
                    if( $value[0] == $name){
                        $data[$i-2][$value[1]] = $excel->getActiveSheet()->getCell($letter.$i)->getValue();   
                        break;                    
                    }
                }
            }
        }
        return $data;
    }
}

说明

/ 单元格强化
/**
* 参数说明
* 设置单元格
* setCellValue(参数1,参数2)
* 参数1:单元格位置
* 参数2:单元格的值
* setCellValueByColumnAndRow(参数1,参数2,参数3)
* 参数1:列位置
* 参数2:行位置
* 参数3:单元格的值
*/

// 单元格文字样式设置
// getStyle 获取单元格样式
//    getFont 获取单元格文字样式
//    setBold 设置文字粗细
//    setName 设置文字字体
//    setSize 设置文字大小
// $sheet->getStyle('B2')->getFont()->setBold(true)->setName('宋体')->setSize(20);

// 单元格文字颜色
// getColor 获取坐标颜色
// setRGB设置字体颜色
// getRGB 获取字体颜色
// setARGB 设置字体颜色
// getARGB 获取字体颜色
// $sheet->getStyle('B2')->getFont()->getColor()->setRGB('#AEEEEE');
// $sheet->getStyle('B3')->getFont()->getColor()->setARGB('FFFF0000');

// 单元格格式
// $sheet->setCellValue('A1','2019-10-10 10:10:10');
// $sheet->setCellValue('A2','2019-10-10 10:10:10');
// $sheet->getStyle('A2')->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDD2);

使用方法:调用 导出

use app\common\services\Phpoffice;
$user = Db::name('user')->select();
$qr_code = new Phpoffice();
$head = ['ID号', '微信名称', '性别', '年龄', '手机号码'];// 表头信息
$keys = ['id', 'wx_name', 'sex', 'age', 'phone'];
$qr_code->outdata('测试',$user,$head,$keys);

调用 导入

use app\common\services\Phpoffice;
$atr = array(
array("序号","xh"),
        array("姓名","user_name"),
        array("身份证号","user_id_name"),
        array("手机号码","user_phone"),
        array("QQ","user_qq"),
        array("微信","user_wx"),
        array("来源ID","source"),
);
                $Phpoffice = new Phpoffice();
                $res = $Phpoffice->import_data('public/1.xls','1.xls',$atr);

Copyright @ 2013-2021 元素模板 www.ys720.com All Rights Reserved. 版权所有 元素模板 www.ys720.com