| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267 |
- <?php
- namespace common\components\export;
- use common\enums\DownloadEnum;
- use common\helpers\UploadHelper;
- use common\models\common\Attachment;
- use common\models\common\Download;
- use common\traits\ErrorTrait;
- use Exception;
- use Yii;
- use yii\base\Component;
- class CsvTool extends Component
- {
- use ErrorTrait;
- const EXPORT_MODE_SYNC = 1;
- const EXPORT_MODE_ASYNC = 2;
- private $_base_dirname = 'download'; //下载中心目录
- private $_handler; // 文件指针
- public $file_dirname; //下载中心资源存放目录
- public $relative_filename; // 文件存储相对路径
- public $export_mode;
- public $filename;
- public $full_filename;
- public $header;
- public $data;
- public $file_size = 0;
- public $line_num = 0;
- public $download_url = '';
- public $absolute_dir = '';
- public $relative_dir = '';
- /**
- * 导出数据
- * @Author bing
- * @DateTime 2021-10-22 11:54:12
- * @param [type] $export_mode
- * @return void
- * @copyright: Copyright (c) 2020 广东七件事集团
- */
- public function export(bool $is_make_head = false)
- {
- try {
- $this->_checkParams($is_make_head);
- switch ($this->export_mode) {
- // 同步下载
- case self::EXPORT_MODE_SYNC:
- header('Content-Type: application/vnd.ms-excel');
- // header('Content-Disposition: attachment;filename*=utf-8' . "'zh_cn'" . iconv('utf-8', 'gbk', $this->filename . '.csv'));
- header("Content-Disposition: attachment;filename={$this->filename}.csv");
- header('Cache-Control: max-age=0');
- //打开PHP文件句柄,php://output 表示直接输出到浏览器
- $this->_handler = fopen('php://output', 'a');
- $this->header = $this->_handRowData($this->header);
- fputcsv($this->_handler, $this->header);
- // 数据总量
- if (!empty($this->data)) {
- $i = 0;
- $limit = 10000;
- while ($this->data[$i]) {
- if ($i % $limit == 0) {
- // 清一下缓冲区
- ob_flush();
- flush();
- }
- $row = $this->_handRowData($this->data[$i]);
- fputcsv($this->_handler, $row);
- unset($this->data[$i]);
- $i++;
- }
- }
- fclose($this->_handler);
- exit;
- break;
- // 异步导出至下载中心
- case self::EXPORT_MODE_ASYNC:
- $this->relative_dir = $this->_getBaseDonwLoadDir();
- $this->absolute_dir = Yii::getAlias('@attachment') . '/' .$this->relative_dir;
- $this->full_filename = $this->absolute_dir . '/' . $this->filename . '.csv';
- $this->relative_filename = $this->relative_dir . '/' . $this->filename . '.csv';
- if (!file_exists($this->full_filename)) {
- $this->_handler = fopen($this->full_filename, 'a+');
- fwrite($this->_handler, "\xEF\xBB\xBF");
- //将数据通过fputcsv写到文件句柄
- $this->header = $this->_handRowData($this->header);
- fputcsv($this->_handler, $this->header);
- }
- $this->_handler = fopen($this->full_filename, 'a+');
- $i = 0;
- $limit = 10000;
- while(!empty($this->data[$i])){
- if($i != 0 && $i % $limit == 0){
- // 清一下缓冲区
- ob_flush();
- flush();
- }
- $row = $this->_handRowData($this->data[$i]);
- $row = array_values($row);
- fputcsv($this->_handler, $row);
- unset($this->data[$i]);
- $i ++;
- $this->line_num ++;
- }
- fclose($this->_handler);
- $this->file_size = file_exists($this->full_filename) ? $this->transf_byte(filesize($this->full_filename)) : 0;
- break;
- }
- } catch (Exception $e) {
- echo $e->getMessage();
- $this->setError($e->getMessage());
- return false;
- }
- }
- /**
- * 检查参数
- * @Author bing
- * @DateTime 2021-10-22 16:04:42
- * @return void
- * @copyright: Copyright (c) 2020 广东七件事集团
- */
- private function _checkParams($is_make_head = false)
- {
- if ($is_make_head) {
- if (!$this->filename || !$this->header) {
- throw new Exception('导出参数错误');
- }
- } else {
- if (!$this->filename || !$this->header || !$this->data) {
- throw new Exception('导出参数错误');
- }
- }
- }
- /**
- *
- * @Author bing
- * @DateTime 2021-10-22 14:55:47
- * @return string //相对路径
- * @copyright: Copyright (c) 2020 广东七件事集团
- */
- private function _getBaseDonwLoadDir()
- {
- $relative_dir = $this->_base_dirname;
- $absolute_dir = Yii::getAlias('@attachment') . '/' . $this->_base_dirname;
- if ($this->file_dirname) {
- $absolute_dir .= '/' . $this->file_dirname;
- $relative_dir .= '/' . $this->file_dirname;
- }
- if (!is_dir($absolute_dir)) {
- mkdir($absolute_dir, 0777, true);
- }
- return $relative_dir;
- }
- /**
- * 每一列数据做处理
- * @Author bing
- * @DateTime 2021-10-22 15:59:39
- * @copyright: Copyright (c) 2020 广东七件事集团
- * @param array $row
- * @return array
- */
- private function _handRowData($row){
- return array_map(function($clo){
- // json不做处理
- try {
- if(is_null(json_decode($clo))){
- $clo = rtrim($clo, "\r\n");
- $clo = str_replace(",", ",", $clo);
- // $clo = is_string($clo) ? iconv('UTF-8', 'GBK', $clo) . "\t" : $clo;
- // $clo = is_string($clo) ? iconv("UTF-8", "GB2312//IGNORE", $clo) . "\t" : $clo;
- $clo = is_string($clo) ? $clo . "\t" : $clo;
- $clo = is_int($clo) ? intval($clo) : $clo;
- $clo = is_float($clo) ? floatval($clo) : $clo;
- }
- return $clo;
- } catch (\Exception $e) {
- return $clo;
- }
- },$row);
- }
- /**
- * 上传至云存储
- * @Author: hua
- * @DateTime: 2021/10/14 10:36
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $mall_id
- * @param $relative_filename //相对路径的文件资源
- * @return string
- * @throws \League\Flysystem\FileExistsException
- * @throws \League\Flysystem\FileNotFoundException
- * @throws \yii\web\NotFoundHttpException
- */
- public function upload($mall_id, $relative_filename)
- {
- $config = \Yii::$app->services->attachment->getStorageConfig($mall_id);
- $config['mall_id'] = $mall_id;
- $upload = new UploadHelper($config, 'files');
- switch ($config['drive']) {
- case Attachment::DRIVE_LOCAL:
- return \Yii::getAlias('@attachurl') . '/'.$relative_filename;
- case Attachment::DRIVE_OSS:
- $url = $upload->upload($relative_filename);
- if (!empty($config['storage_aliyun_user_url'])) {
- return $config['storage_aliyun_transport_protocols'].'://'.$config['storage_aliyun_user_url'] . '/' . $url;
- }
- break;
- case Attachment::DRIVE_COS:
- $url = $upload->upload($relative_filename);
- if (!empty($config['domain'])) {
- return $config['domain'] . '/' . $url;
- }
- break;
- case Attachment::DRIVE_QINIU:
- $url = $upload->upload($relative_filename);
- if (!empty($config['domain'])) return $config['domain'] . '/' . $url;
- break;
- }
- }
- public function transf_byte($byte) {
- $kb = 1024;
- $mb = $kb * 1024;
- $gb = $mb * 1024;
- if ($byte < $kb) {
- return $byte . 'b';
- } else if ($byte < $mb) {
- return round($byte / $kb, 2) . 'kb';
- } else if ($byte < $gb) {
- return round($byte / $mb, 2) . 'mb';
- }
- }
- public function utf8ToGbk($string) {
- return iconv("UTF-8", "gbk//TRANSLIT", $string);
- }
- /**
- * @desc:上传至云存储和更新down模型
- * @Author: hua
- * @Date: 2021/11/15
- * @Time: 15:39
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $download
- * @param $mall_id
- * @return mixed
- * @throws \League\Flysystem\FileExistsException
- * @throws \League\Flysystem\FileNotFoundException
- * @throws \yii\web\NotFoundHttpException
- */
- public function updateDown($download,$mall_id){
- $url = $this->upload($mall_id, $this->relative_filename);
- $download->status = DownloadEnum::STATUS_FINISH;
- $download->url = $url;
- $download->num = $this->line_num;
- $download->size = $this->file_size;
- return $download->save();
- }
- }
|