PHP 文件导出(Excel, CSV,txt)

淺唱寂寞╮ 提交于 2020-04-06 11:12:23

1,Excel 导出:

 

/**
     * Excel导出例子
     */
    public function excel($res){
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("XXX");
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();

        $objActSheet->setCellValue('A1', '门店名称');
        $objActSheet->setCellValue('B1', '门店UID');
        $objActSheet->setCellValue('C1', '交易时间');
        $objActSheet->setCellValue('D1', '应收金额');
        $objActSheet->setCellValue('E1', '实收金额');
        $objActSheet->setCellValue('F1', '支付笔数');
        $objActSheet->setCellValue('G1', '取消笔数');
        $objActSheet->setCellValue('H1', '应扣手续费');
        $objActSheet->setCellValue('I1', '实扣手续费');
        $objActSheet->setCellValue('J1', '红包');
        $objActSheet->setCellValue('K1', '结算金额');

        $i = 2 ;
        $data = $res[0]; //数据
        // $shop_list = $res[1];
        $ymd = $res[2]; //时间
        foreach($data as $k=>$rs){

            $objActSheet->setCellValue('A'.$i, !empty($rs['shop_name'])?$rs['shop_name']:'');
            
            $objActSheet->setCellValue('B'.$i, $rs['shop_sub_id']);
            //交易时间
            $objActSheet->setCellValue('C'.$i, $ymd);
            
            $objActSheet->setCellValue('D'.$i, !empty($rs['pay_price']) ? $rs['pay_price'] : 0);
            $objActSheet->setCellValue('E'.$i, !empty($rs['jiao']) ? $rs['jiao'] : 0);
            $objActSheet->setCellValue('F'.$i, !empty($rs['count_success']) ? $rs['count_success'] : 0);
            $objActSheet->setCellValue('G'.$i, !empty($rs['count_fail']) ? $rs['count_fail'] : 0);
            $objActSheet->setCellValue('H'.$i, !empty($rs['ought']) ? $rs['ought'] : 0);
            $objActSheet->setCellValue('I'.$i, !empty($rs['reality_poundage']) ? $rs['reality_poundage'] : 0);
            $objActSheet->setCellValue('J'.$i, !empty($rs['rebate']) ? $rs['rebate'] : 0);
            $objActSheet->setCellValue('K'.$i, !empty($rs['jie']) ? $rs['jie'] : 0);

            $i++;
        }
  
        $fname = 'order_'.time();

        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$fname.'.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

 

2, CSV导出:

$filename = 'csv_'. time();
   $title="标题1,标题2,标题N";
   $this->export($filename,  $title);
   $this->csv($csv_res);
  
================ 下面是调用方法例子 =============================================================

    /**
     * 导出csv文件
     * @param 文件名 $filename
     * @param 数据 $data
     * @param 从数据中取指定字段 $fileds
     * @param 字段名 多个用逗号分割 $title
     * @param 数据量过大标记 $tooMuch
     */
    public function export($filename,  $title,$tooMuch=0){
        $filename   =   @iconv('UTF-8','GBK',$filename.'.csv');
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo @iconv('UTF-8', 'GBK//IGNORE', $title)."\r\n";
    }

    /**
     * [csv 导出数据]
     * @param  [type] $data [数据]
     * @return [type]       [description]
     */
    private function csv($data)
    {
        $regex = "/[ '.,:;*?~`!@#$%^&+_=<>{}]|\]|\[|\/|\\|\"|\|/";
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $value['shop_name']=isset($value['shop_name'])?FuncHelper::escapeEmoji($value['shop_name']):'-';
                $address=isset($value['address'])?$value['address']:'-';//门店地址
                $shop_name=preg_replace($regex,"",$value['shop_name']);
                $board_total = isset($value['board_total']) ? $value['board_total']:"0";
                $first_login_time = isset($value['first_login_time']) ? date('Y-m-d H:i:s',$value['first_login_time']):"-";
                $goods_count = isset($value['goods_count']) ? $value['goods_count']:"0";
                $pay_sum = isset($value['pay_sum']) ? $value['pay_sum']:"0";

                echo '"'.@mb_convert_encoding($value['id'], 'GBK', 'UTF-8').'",'; 
                echo '"'.@mb_convert_encoding($value['uid'], 'GBK', 'UTF-8').'",';
                echo '"'.@mb_convert_encoding($shop_name, 'GBK', 'UTF-8').'",';
                echo '"'.@mb_convert_encoding($address, 'GBK', 'UTF-8').'",';
                echo '"'.@mb_convert_encoding($board_total, 'GBK', 'UTF-8').'",';
                echo '"'.@mb_convert_encoding($first_login_time, 'GBK', 'UTF-8').'",';
                echo '"'.@mb_convert_encoding($goods_count, 'GBK', 'UTF-8').'",';
                echo '"'.@mb_convert_encoding($pay_sum, 'GBK', 'UTF-8').'",';

                echo " \r\n";
            }
        }
    }

 

另外,如果碰到导出的数字太大的话,表格会默认对数字进行科学计数,像“1.21E + ”这种的,解决方法:只需要在输出的加上 “\t” 即可,例子如下:

echo '"'.@mb_convert_encoding($pay_sum, 'GBK', 'UTF-8'). "\t" . '",';   ## 输出后面加上 \t

 

 

3, txt导出

只需要把上面CSV导出的 export方法改一句参数就可以

        $filename = @mb_convert_encoding($filename . '.txt', 'GBK', 'UTF-8'); //.csv的文件名改为.txt
        // header("Content-type:application/vnd.ms-excel");
        header('Content-Type: application/octet-stream'); //上面的改为这句

自己补充:excel导出如果数据量大的话,超级慢,服务器很容易崩,但是可以自主设置行宽,字体、背景等样式,csv导出速度超级快,大数据量也不是问题,但是不能设置样式(个人不会设置),txt导出跟csv一样,就是格式变了

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!