文件下載

文件下載是實(shí)際項(xiàng)目中經(jīng)常用的一個(gè)接口,不同于圖片下載客戶端自己保存就可以了,需要開放對(duì)應(yīng)的接口。同時(shí),一般會(huì)結(jié)合PHPExcel導(dǎo)出EXCEL表格。隨著 PhpSpreadsheet的更新,三種方式一并在此總結(jié)下。

1.普通文件下載
        //文件下載, readfile實(shí)現(xiàn)  
        $fileinfo = pathinfo($filename['path']);
        header('Content-type: application/x-'.$fileinfo['extension']);  
        header('Content-Disposition: attachment; filename='.$fileinfo['basename']);  
        header('Content-Length: '.$filename['size']);
        readfile(ROOT_PATH ."public" . DS  . $filename['path']); 
        exit(); 
2.1文件下載+PHPExcel(頭鐵版)

缺點(diǎn):表格設(shè)置需要代碼層實(shí)現(xiàn),較為復(fù)雜
優(yōu)點(diǎn):僅需要在代碼層更改

    //河長(zhǎng)信息導(dǎo)出
    public function getRiverOwnerDown(){

        $condition = [];
        RequestFunc::conditionAdd($condition, $this->get, ["pageNo", "pageSize", "river_type", "river_style", 'town_id', 'village_id','role_ids','searchWord','level_id']);

        $orderBy['groupBy'] =['ro.user_id'];
        RequestFunc::buildOrderBy($orderBy,$this->get);

        $expTitle = "河長(zhǎng)信息";

        $expCellName = ['河長(zhǎng)姓名','河長(zhǎng)級(jí)別','河道名稱','工作單位','所屬村鎮(zhèn)','辦公電話','聯(lián)系方式','任職詳情'];

        //只查看河長(zhǎng)數(shù)據(jù)
        $condition['check_brother'] = 1;
        //非市級(jí)河長(zhǎng)辦只能看到本鎮(zhèn)的數(shù)據(jù)
        //$this->admin['town_id'] =0;
        if($this->admin['town_id'] !== 0){
            $condition['town_id'] = $this->admin['town_id'];
        }

        $fields = ["au.user_name", 'rl.level_name', "r.river_name", "au.department", "CONCAT(au.town,au.village) as address", 'au.department_tel', 'au.mobile','au.position'];
        $expTableData = $this->dataDao->river_riverOwner_town_village($condition, $fields)->select();

        foreach ($expTableData as $key => $value) {
            $expTableData[$key] = array_values($value);
        }

        ExcelFunc::phpExcelOutput($expTitle,$expCellName,$expTableData);
         
    }
2.2文件下載+PHPExcel(結(jié)合模板下載方式)

優(yōu)點(diǎn):表格設(shè)置可直接修改對(duì)應(yīng)模板xls
缺點(diǎn):需要單獨(dú)上傳空模板xls

    /*
     * 河長(zhǎng)數(shù)據(jù)導(dǎo)出
     */
    public function userExport()
    {
        $excel = $_SERVER['DOCUMENT_ROOT'] . "/../application/common/json/user.xlsx";
        $link = [
            "B" => "user_name",//河長(zhǎng)姓名
            "C" => "level_name",//河長(zhǎng)級(jí)別
            "D" => "river_name",//河道名稱
            "E" => "river_style",//河道類型
            "F" => "river_type",//河道等級(jí)
            "G" => "department",//工作單位
            "H" => "town",//所屬鎮(zhèn)村
            "I" => "mobile",//聯(lián)系電話
            "J" => "department_tel",//辦公電話
        ];
        $userService = new UserService();
        CommonFunc::arrEmptyReplace($this->get,['level_id'],'1,2,4,5,8,9,10,11,12,13,14,15,16,17,18,19,20');
        if(!empty($this->get['river_type']))
        {
            switch($this->get['river_type']){
                //市級(jí)河道
                case 1:
                    $this->get['level_id'] = array_intersect([4,14,5,15,8,16,10,18],explode(",",$this->get['level_id']));
                    break;
                //鎮(zhèn)級(jí)河道
                case 2:
                    $this->get['level_id'] = array_intersect([9,17,11,19],explode(",",$this->get['level_id']));
                    break;
                //村級(jí)河道
                case 3:
                    $this->get['level_id'] = array_intersect([13,20],explode(",",$this->get['level_id']));
                    break;
                //市級(jí)河道XX段
                case 4:
                    $this->get['level_id'] = array_intersect([4,14,5,15,8,16,10,18],explode(",",$this->get['level_id']));
                    break;
                default:
                    break;
            }          
        }
        $list = $userService->userList($this->get)["list"];

        foreach ($list as $k => &$v) {
            //導(dǎo)出河道——river_type字段特別顯示
            if ($v['river_style'] == 0) {
                $river_type_exchange = ["1" => "市級(jí)河道", "2" => "鎮(zhèn)級(jí)河道", "3" => "村級(jí)河道"];
            }else if ($v['river_style'] ==1) {
                $river_type_exchange = ["1" => "市級(jí)湖泊", "2" => "鎮(zhèn)級(jí)湖泊", "3" => "村級(jí)湖泊"];
            }else{
                $river_type_exchange = ["1" => "水庫(kù)", "2" => "水庫(kù)", "3" => "水庫(kù)"];
            }
            CommonFunc::arrReplace($v, [
                "river_type" => $river_type_exchange,
                "river_style" => ["0" => "河道", "1" => "湖泊", "2" => "水庫(kù)"],
            ]);
        }
        $title = "河長(zhǎng)信息表";
        ExcelFunc::outPutByLoad($excel, $link, $list, $title);
    }

下面附上以上兩種方法用到的PHPExcel公共函數(shù)

需要用composer安裝——composer require phpoffice/phpexcel
疑問(wèn):這里沒(méi)用引入也能直接實(shí)例化,說(shuō)是什么工廠類之類的,反正就是可以吧,有點(diǎn)醉

<?php
namespace app\common\func;

/**
 * Class Common
 * @package App\Func
 */
class ExcelFunc
{

    public static function phpExcelOutput($expTitle, $expCellName, $expTableData, $style = [])
    {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名稱 將字符串從utf-8編碼轉(zhuǎn)為gb2312編碼
        $cellNum = count($expCellName);//獲取文件的列數(shù)
        $dataNum = count($expTableData);//獲取數(shù)據(jù)的條數(shù)
        $objPHPExcel = new \PHPExcel();//生成PHPExcel類實(shí)例
        //A-AZ列
        $cellName = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
            'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'AO', 'AP', 'AQ'];
        // 設(shè)置excel文檔的屬性
        $objPHPExcel->getProperties()->setCreator("php")//設(shè)置文檔屬性作者
        ->setLastModifiedBy("php")//設(shè)置最后修改人
        ->setTitle("Microsoft Office Excel Document")//設(shè)置文檔屬性標(biāo)題
        ->setSubject("php")//設(shè)置文檔屬性文檔主題
        ->setDescription("php")//設(shè)置文檔屬性備注
        ->setKeywords("php")//設(shè)置文檔屬性關(guān)鍵字
        ->setCategory("php");//設(shè)置文檔屬性類別

        //設(shè)置表的名稱
        $objPHPExcel->getActiveSheet()->setTitle($expTitle);

        if (!empty($style)) {
            if (!empty($style['width'])) {
                foreach ($style['width'] as $k => $v) {
                    $objPHPExcel->getActiveSheet()->getColumnDimension($k)->setWidth($v);
                }
            }
            if (!empty($style['height'])) {
                foreach ($style['height'] as $k => $v) {
                    $objPHPExcel->getActiveSheet()->getRowDimension($k)->setRowHeight($v);
                }
            }
            //固定表頭
            if (!empty($style['freezePane'])) {
                $objPHPExcel->getActiveSheet()->freezePane($style['freezePane']);
            }
        }

        //自動(dòng)換行、左右垂直居中
        $objPHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        for ($i = 0; $i < $cellNum; $i++) {
            //遍歷設(shè)置單元格的值 設(shè)置列名
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i]);
            if (!empty($expCellName[$i]['color'])) {
                $objPHPExcel->getActiveSheet()->getStyle($cellName[$i] . '1')->getFont()->getColor()->setARGB($expCellName[$i]['color']);
            }
        }
        //讓總循環(huán)次數(shù)小于數(shù)據(jù)條數(shù)
        for ($i = 0; $i < $dataNum; $i++) {
            //讓每列的數(shù)據(jù)數(shù)小于列數(shù)
            for ($j = 0; $j < $cellNum; $j++) {
                //設(shè)置單元格的值
                $objPHPExcel->getActiveSheet()->setCellValue($cellName[$j] . ($i + 2), ' '.$expTableData[$i][$j]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$expTitle.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    /*
     * 加載表格,填充數(shù)據(jù)
     */
    public static function outPutByLoad($excel, $link, $list, $title)
    {

        $Reader = new \PHPExcel_Reader_Excel2007();
        $PHPExcel = $Reader->load($excel);

        foreach($list as $k => $v){
            $PHPExcel->getActiveSheet()->setCellValue("A".($k+2), $k+1);
            foreach($link as $k1 => $v1){
                $key = $k1.($k+2);
                $PHPExcel->getActiveSheet()->setCellValue($key, $v[$v1]);
            }
        }
        header('pragma:public');
        $xlsTitle = 100;
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename={$title}.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

}

3.文件導(dǎo)入+PhpSpreadsheet

優(yōu)點(diǎn):官方推薦的新方法,導(dǎo)出速度更快,量更大
缺點(diǎn):英文文檔讀的一臉懵逼,相關(guān)demo不多,引入就難了半天
官方手冊(cè):phpspreadsheet手冊(cè)
大神指南:使用PhpSpreadsheet讀取和寫入Excel

<?php
/**
 * @authors ZL 
 * @email 987968469@qq.com
 * @date    2018-06-04 13:59:05  
 */
namespace app\admin\controller;

use app\common\controller\Admin;
use app\common\myFunc\ExcelFunc;
use think\Db;
//引入后就能使用了PHPSpreadsheet了——我也不知道為什么
require_once "./vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\IOFactory;

class Department extends Admin {
    /**
     * 數(shù)據(jù)導(dǎo)入
     */
    private function importData($inputFileName,$name){
        if (!file_exists($inputFileName)) {
            die('no file!');
        }
        vendor('PhpOffice.PhpSpreadsheet.IOFactory');
        /**  Identify the type of $inputFileName  **/
        $inputFileType = IOFactory::identify($inputFileName);
        /**  Create a new Reader of the type that has been identified  **/
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
        /**  Load $inputFileName to a Spreadsheet Object  **/
        $spreadsheet = $reader->load($inputFileName);
        $list = $spreadsheet->getActiveSheet()->toArray();
        //獲取json
        $json = file_get_contents(dirname(__FILE__) .'../../../common/Json/'.$name.'.json');
        $json = json_decode($json, true);
        //將表中的數(shù)據(jù)重組成數(shù)據(jù)庫(kù)錄入的數(shù)組
        $data = $this->buildArray($list,$json);//halt($data);
        
        $report = db('company_month_report')->where('date_time',$data[0]['date_time'])->column('id');//halt($report);
        foreach ($data as $key => $value) {
            if(in_array($value['id'], $report)){
                $result = db('company_month_report')
                    ->where('date_time',$value['date_time'])
                    ->where('id',$value['id'])
                    ->update($value);
            }else{
                $result = db('company_month_report')->insert($value);
            }
        }
        // halt(session('user_auth.is_government'));
        //該部門數(shù)據(jù)導(dǎo)入成功后,向cxly_department_work表中寫入數(shù)據(jù),方便定時(shí)任務(wù)提醒
        $result  =db('department_work')->insert([
            'date_time'=>$data[0]['date_time'],
            'department_id'=>session('user_auth.is_government')
        ]);
        if($result){
            return $this->success("導(dǎo)入成功!", url('enterprise/index'));
        }
        
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容