使用PHPExcel导出和导入Excel

<?php
/**
 * 导出Excel
 *
 * @param array $head 表头
 * @param array $data 数据
 * @param string $filename 文件名(不含文件扩展名)
 * @return void
 */
function export_excel($head, $data, $filename)
{
    // 由于导出Excel比较耗时且比较消耗内存,故要设置一下脚本最大运行时间和最大可用内存
    set_time_limit(0);
    ini_set('memory_limit', '512M');

    require_once __DIR__ . '/phpexcel/autoload.php';

    $phpexcel = new PHPExcel();

    // 设置文件属性,导出的Excel文件右键属性-详细信息可以看到文件属性(非必须)
    $phpexcel->getProperties()
        ->setCreator('--setCreator--')// 作者
        ->setLastModifiedBy('--setLastModifiedBy--')// 最后一次保存者
        ->setTitle('--setTitle--')// 标题
        ->setSubject('--setSubject--')// 主题
        ->setDescription('--setDescription--');// 备注

    $nextLetter = static function ($letter) {
        $letter = ord($letter);
        return chr(++$letter);
    };

    try {
        $activeSheet = $phpexcel->setActiveSheetIndex(0);
    } catch (PHPExcel_Exception $exception) {
        exit($exception->getMessage());
    }

    //========== 填充表头 ==========//
    $letter = 'A';
    foreach ($head as $key => $value) {
        $activeSheet->setCellValue("{$letter}1", $value);
        $letter = $nextLetter($letter);
    }

    //========== 填充数据 ==========//
    $i = 2; // 第一行是表头,所以从第二行开始填充数据
    foreach ($data as $key1 => $value1) {
        $letter = 'A';

        foreach ($head as $key2 => $value2) {
            $cellValue = isset($value1[$key2]) ? $value1[$key2] : '';
            $activeSheet->setCellValueExplicit("{$letter}{$i}", $cellValue, PHPExcel_Cell_DataType::TYPE_STRING);
            $letter = $nextLetter($letter);
        }

        $i++;
    }

    $phpexcel->getActiveSheet()->setTitle('这是工作表名'); // 设置工作表名字(非必须)

    try {
        $phpexcel->setActiveSheetIndex(0);
    } catch (PHPExcel_Exception $exception) {
        exit($exception->getMessage());
    }

    ob_end_clean(); // 清除缓冲区,避免乱码

    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header("Content-Disposition: attachment;filename={$filename}.xls");
    header('Cache-Control: max-age=0');

    try {
        $writer = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');

        try {
            $writer->save('php://output');
        } catch (PHPExcel_Writer_Exception $exception) {
            exit($exception->getMessage());
        }
    } catch (PHPExcel_Reader_Exception $exception) {
        exit($exception->getMessage());
    }

    exit();
}

$head = [
    'name' => '姓名',
    'gender' => '性别',
    'age' => '年龄',
    'mobile' => '手机号码',
    'id' => '身份证号码',
];

$data = [
    [
        'name' => '张三',
        'gender' => '男',
        'age' => 18,
        'mobile' => '18833333333',
        'id' => '430802198211276545',
    ],

    [
        'name' => '李四',
        'gender' => '女',
        'age' => 17,
        'mobile' => '18844444444',
        'id' => '44022419830411629X',
    ],

    [
        'name' => '王五',
        'gender' => '男',
        'age' => 19,
        'mobile' => '18855555555',
        'id' => '610626198501166495',
    ],
];

$filename = '导出Excel演示 - ' . date('YmdHis');

export_excel($head, $data, $filename);

<?php
/**
 * 导入Excel
 *
 * @param string $file Excel文件硬盘路径
 * @return array Excel数据
 */
function import_excel($file)
{
    // 由于导入Excel比较耗时且比较消耗内存,故要设置一下脚本最大运行时间和最大可用内存
    set_time_limit(0);
    ini_set('memory_limit', '512M');

    require_once __DIR__ . '/phpexcel/autoload.php';

    try {
        $readerType = PHPExcel_IOFactory::identify($file); // 返回值:Excel5
    } catch (PHPExcel_Reader_Exception $exception) {
        exit($exception->getMessage());
    }

    try {
        $dataObject = PHPExcel_IOFactory::createReader($readerType)->load($file);
    } catch (PHPExcel_Reader_Exception $exception) {
        exit($exception->getMessage());
    }

    $data = $dataObject->getsheet(0)->toArray(); // 读取数据

    unset($data[0]); // 删除表头

    return $data;
}

$file = __DIR__ . '/demo.xls';
$data = import_excel($file);
foreach ($data as list($name, $gender, $age, $mobile, $id)) {
    echo "{$name}  {$gender}  {$age}  {$mobile}  {$id}" . PHP_EOL;
}
//================= 输出结果 =================//
// 张三  男  18  18833333333  430802198211276545
// 李四  女  17  18844444444  44022419830411629X
// 王五  男  19  18855555555  610626198501166495

Copyright © 2024 码农人生. All Rights Reserved