PhpSpreadsheet导入导出

PhpSpreadsheet

使用前,使用composer引入PhpSpreadsheet

composer require phpoffice/phpspreadsheet

方法:

  1. 导入转数组
  2. 导出为文件
  3. 导入文件存入数据库
<?php
/**
 * Created by PhpStorm.
 * User: WuNai
 * Date: 2019/4/2/002
 * Time: 16:57
 */

namespace common\helpers;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class FileProcess
{
    /**
     * 文件 转 Array
     * @param string $filePath 文件路径
     * @return array
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public static function toArray($filePath)
    {

        $spreadsheet = IOFactory::load($filePath);// 载入excel表格

        $worksheet = $spreadsheet->getActiveSheet();

        $highestRow = $worksheet->getHighestRow(); // 总行数
        $highestColumn = $worksheet->getHighestColumn(); // 总列数

        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);

        $data = [];
        for ($row = 2; $row <= $highestRow; ++$row) { // 从第二行开始
            $row_data = [];
            for ($column = 1; $column <= $highestColumnIndex; $column++) {
                $row_data[] = $worksheet->getCellByColumnAndRow($column, $row)->getValue();
            }
            $data[] = $row_data;
        }

        return $data;
    }

    /**
     * Array 转 文件
     * @param array $title 标题 格式['title1', 'title2']
     * @param array $data 导出数据 ['A1' => '***', 'B2' => '***']
     * @param string $fileName 导出文件名称
     * @param array $options 配置 [ 'fileType' => 'xls',    导出文件后缀 默认 xls
     *                             'savePath' => '/web'    自定义保存地址
     *                           ]
     * @return bool
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public static function toFile($title, $data, $fileName, $options = [])
    {

        /** 设置转义格式 */
        if (isset($options['fileType']) && !in_array($options['fileType'], ['xls', 'xlsx', 'ods', 'csv', 'html', 'tcpdf', 'dompdf', 'mpdf'])) {
            return false;
        }

        $spreadsheet = new Spreadsheet();

        $worksheet = $spreadsheet->getActiveSheet();
        //设置标题名称
        $worksheet->setTitle($fileName);

        foreach ($title as $key => $value) {
            $worksheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }

        $row = 2; //第二行开始
        foreach ($data as $item) {
            $column = 1;
            foreach ($item as $value) {
                $worksheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
            }
            $row++;
        }

        /** 设置文件后缀名 */
        if (!isset($options['fileType'])) {
            $fileName = $fileName . '.xls';
        } else {
            $fileName = $fileName . '.' . $options['fileType'];
        }

        /** 设置文件路径 */
        if (!isset($options['savePath'])) {
            $savePath = \Yii::$app->basePath . '/web/' . $fileName;
        } else {
            $savePath = $options['savePath'] . $fileName;
        }

        /** @var string $writerType 转义成PhpSpreadsheet能识别的后缀 */
        $writerType = ucfirst($options['fileType']);

        $writer = IOFactory::createWriter($spreadsheet, $writerType);

        $writer->save($savePath);

        /* 释放内存 */
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        ob_end_flush();

        return true;
    }

    /**
     * 导入文件插入数据库
     * @param string $tableName 表名
     * @param array $filed 字段名 [ 'create_id', 'create_time' ]
     * @param string $filePath 文件路径
     * @return bool|int
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \yii\db\Exception
     */
    public static function toSql($tableName, $filed, $filePath)
    {
        $params = self::toArray($filePath);

        $result = \Yii::$app->db->createCommand()->batchInsert($tableName, $filed, $params)->execute();

        return $result;
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值