美文网首页
php导入导出csv文件

php导入导出csv文件

作者: 耍帅oldboy | 来源:发表于2023-03-26 23:31 被阅读0次

1、php导出csv文件

         /**
     * 导出csv
     * @param $data
     * @return void
     */
    public static function exportCsv($data,$filename=''){
        header("Content-type: text/csv;charset=UTF-8");
        header("Content-Disposition: attachment;filename=" .urlencode($filename. time()).'.csv');
        header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
        header('Expires: 0');
        header('Pragma: public');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Expose-Headers: Content-Disposition');

        ob_end_clean();
        ob_start();
       //内存中打开,不占用硬盘
        $fp = fopen('php'.'://output','w');  //'php'.'://output';直接写简书不让保存,只能换这种切开链接的方式写
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));

        //每1000条刷新一次缓存
        foreach ($data as $key=>$value) {
            if ($key % 1000 ==0) {
                ob_flush();
                flush();
            }
            //添加空格数字变文本
            foreach($value as $k=>$v){
                $value[$k] = "\t".$v;
            }
            fputcsv($fp, $value);
        }
        fclose($fp);
        ob_flush();
        flush();
        ob_end_clean();
        exit;
    }
}

2、导入csv文件

        $fp = fopen($filePath, 'rb');
        $data = [];
        while (!feof($fp)) {
            $data[] = fgetcsv($fp);
        }
        fclose($fp);
        unlink($filePath);

3、vue弹出下载

export function exportDownloadFile(res){
    // 文件名,获取原始的文件名
    const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
    const data = res.data // Blob数据对象
    const uA = window.navigator.userAgent
    const isIE =
      /msie\s|trident\/|edge\//i.test(uA) &&
      !!('uniqueID' in document || 'documentMode' in document || 'ActiveXObject' in window || 'MSInputMethodContext' in window)
    let url = window.URL.createObjectURL(new Blob([data]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    // 兼容IE
    if (isIE) {
      navigator.msSaveBlob(new Blob([data]), fileName)
    } else {
      link.click()
    }
}

相关文章

网友评论

      本文标题:php导入导出csv文件

      本文链接:https://www.haomeiwen.com/subject/hpmardtx.html