如何用 php 读取一个很大的 excel 文件。

时间:2022-11-27 11:52:08

这个程序是用php 读取一个很大的excel文件,

先将 excel 文件保存成csv 文件,

然后利用 迭代器 逐行读取 excel 单元格的值,

拿到值以后 做相应处理,并打印结果。

<?php

// 加载 GuzzleHttp 为发送 http 请求提供方便
include_once('./vendor/autoload.php');
$client = new \GuzzleHttp\Client();

// 定义读取文件
    $file = './file/a.csv';

function getRows($file)
    {
        $handle = fopen($file, 'rb');

if (!$handle) {
            throw new Exception();
        }
        while (!feof($handle)) {
             yield fgetcsv($handle);
        }
        fclose($handle);
    }

// 获取迭代器
    $xrange = getRows($file);
    $ii = 0;

// 迭代处理 cvs 文件中的每一行内容
    foreach ($xrange as $key => $value) {
        $value = eval('return '.iconv('gbk','utf-8',var_export($value,true)).';');

$str = $value[4];
        $url = 'http://xxxx.xxxx.com/?api='.$str;

$response = $client->get($url);
        $body = $response->getBody();
        $remainingBytes = $body->getContents();

$remainingBytes = json_decode($remainingBytes,true);
        if( !empty($remainingBytes['data']) ){
            $res_ids = '';
            foreach ($remainingBytes['data'] as $kt => $vt) {
                $res_ids .= $vt['outid'].',';
            }
            $res_ids = trim($res_ids,',');
        }else{
            $res_ids = 'error';
        }

print_r($str);
            echo "\n";
            echo "\n";
            echo "\n";
            print_r($value[4]);
            echo "\n";
            echo "\n";
            echo "\n";
            print_r($res_ids);

$file = fopen('./new_end/new_a.xls', 'a');
        fwrite($file, $res_ids."\t".$str."\t".$value[4]."\t\n");
        // fclose($file);
        echo "\n";
        echo "\n";
        echo "\n";
        // die;
        $ii++;
        echo "time_________".$ii;
        echo "\n";
        echo "\n";
        echo "\n";
    }

?>