首页 > 其他分享 >导入导出Csv

导入导出Csv

时间:2022-10-13 13:56:18浏览次数:47  
标签:fp arr 导出 fileName header 导入 array Csv row

导入Csv

    /**
     * 导入Csv
     * ThinkPHP5.1框架
     */
    public function csvDr()
    {
        $excelData = array();
        //第一种:将文件一次性全部读出来
//        $content = trim(firle_get_contents('../public/upload/test.csv'));
//        $excelData = explode("\n", $content);
//        array_shift($excelData);

        //第二种:直接使用file
        $excelData = file('../public/upload/test.csv');
        array_shift($excelData);//删除第一行数组(一般都是标题)
        if (empty($excelData)) {
            return false;
            exit();
        }
        $chunkData = array_chunk($excelData, 500);//分割数组 size的数量保持在500-1000,过大会导致数组卡顿
        $count = count($chunkData);//for循环分批插入中使用

        //第一种方法foreach循环分批导入
        $row = array();
        foreach ($chunkData as $item) {
            $data = array();
            foreach ($item as $value) {
                //转码并去除html标签和空字符
                $value = iconv("GBK", "UTF-8//IGNORE", trim(strip_tags($value)));
                $arr = explode(',', $value);//将转好的字符串分割成数组
                $row['id'] = $arr[0];
                $row['name'] = $arr[1];
                $row['city'] = $arr[2];
                $row['phone'] = $arr[3];
                $row['platform'] = $arr[4];
                $row['status'] = $arr[5];
                $row['time'] = $arr[6];
                $row['effect'] = $arr[7];
                $data[] = $row;
            }
            $db = Db::name('seach')->fetchSql()->insertAll($data);
            dump($db);
        }
        //第二种for循环分批插入
//        for ($i = 0; $i < $count; $i++) {
//            $data = array();
//            foreach ($chunkData[$i] as $value) {
//                $value = iconv("GBK", "UTF-8//IGNORE", trim(strip_tags($value)));
//                $arr = explode(',', trim($value));
//                $row['id'] = $arr[0];
//                $row['name'] = $arr[1];
//                $row['city'] = $arr[2];
//                $row['phone'] = $arr[3];
//                $row['platform'] = $arr[4];
//                $row['status'] = $arr[5];
//                $row['time'] = $arr[6];
//                $row['effect'] = $arr[7];
//                $data[] = $row;
//            }
//            $db = Db::name('seach')->fetchSql()->insertAll($data);
//            dump($db);
//        }

    }

导出Csv

/**
 * 数据导出到excel(csv文件)
 * @param $fileName  文件名
 * @param array $tileArray  一维数组
 * @param array $dataArray  二维数组
 */
function export_excel($fileName, $tileArray = [], $dataArray = [])
{
    ini_set('memory_limit', '1024M');
    ini_set('max_execution_time', 0);
    ob_end_clean();
    ob_start();
    header('Content-Type: text/csv;charset=utf-8');
    //header("Content-Disposition:filename=" . $fileName);
    header("Content-Disposition:attachment;filename=" . $fileName . '.csv');
    header('Cache-Control: max-age=0');
    header('Pragma:public');
    $fp = fopen('php://output', 'a');
    //$fp = fopen('php://output', 'w');
    fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
    fputcsv($fp, $tileArray);
    $index = 0;
    foreach ($dataArray as $item) {
        if ($index == 10000) {
            $index = 0;
            ob_flush();
            flush();
        }
        $index++;
        fputcsv($fp, $item);
        unset($item); 
    }
    unset($dataArray);
    fclose($fp);

    ob_flush();
    flush();
    ob_end_clean();
}
/**
 * @param $filename 文件名
 * @param array $$titleArray  标题  一维数组
 * @param array $dataArray 内容  二维数组
 */
function export_csv($fileName, array $titleArray, array $dataArray)
{
    //$fileName = iconv('utf-8', 'gb2312', $fileName);//文件名称
    //$fileName = iconv('utf-8', 'gb2312', $fileName) . date('_YmdHis');// 文件名称可根据自己情况设定
    // header函数需要放fopen之前,不然会直接在浏览器页面打印输出。而不是文件下载
    header('Content-Type: application/vnd.ms-excel;charset=utf-8');
    header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
    header('Cache-Control: max-age=0');
    header('Pragma:public');
    ob_clean();
    ob_start();
    $fp = fopen('php://output', 'a');
    //$fp = fopen('php://output', 'w');
    fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//解决乱码
    fputcsv($fp, $titleArray);

    $num = 0;
    $countData = count($dataArray);
    if ($countData <= 10000) {
        $limit = 1000;
    } elseif ($countData > 10000 && $countData <= 30000) {
        $limit = 3000;
    } else {
        $limit = 5000;
    }

    foreach ($dataArray as $value) {
        $num++;
        if ($num == $limit) {
            ob_flush();
            flush();
            $num = 0;
        }
        fputcsv($fp, $value);
        unset($value);
    }
    unset($dataArray);
    fclose($fp);

    ob_flush();
    flush();
    ob_end_clean();

    exit();
}

调用

    /**
     * 调用导出Csv
     * ThinkPHP5.1框架
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function csvDc()
    {
        $filename = 'test';//Csv文件名
        $header = ['序号', '项目', '城市', '手机', '平台', '状态', '日期', '生效时间'];//标题(一位数组)
        $data = Db::table('seach')->select();//数据内容(二维数组)
        export_csv($filename, $header, $data);
    }


作者:DongQin小迷弟
链接:https://www.jianshu.com/p/e43cd4b934ea
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

标签:fp,arr,导出,fileName,header,导入,array,Csv,row
From: https://www.cnblogs.com/gwhm/p/16787922.html

相关文章