ThinkPHP5調用PHPExcel類實現導入導出

注意:extend是放置第三方類的地方,不要亂配置命名空間那些,引發沒必要要的類錯誤php

 

代碼以下html

<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
//use lib\PExcel;

class Four extends Controller
{
    //上傳頁面展現
    public function index(){
        return view();
    }

    //實現excel的導入操做
    public function uploadExcel(){
//        //接收文件
//        $file = request()->file('excel');
//        $info = $file->validate(['size'=>3145728,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'excels');
//        if($info){
//            $excel_path = ROOT_PATH.'public'.DS.'static'.DS."excels".DS.$info->getSaveName();
//        }else{
//            $excel_path = null;
//        }
        //防止亂碼
        ini_set('memory_limit', '1024M');//設置php容許的文件大小最大值
        Loader::import('PHPExcel.Classes.PHPExcel');//必須手動導入,不然會報PHPExcel類找不到
        header("Content-type:text/html;charset=utf-8");
        //接收文件
        $file = $_FILES['excel'];
        $extension = strtolower( pathinfo($file['name'], PATHINFO_EXTENSION) );
        //實例化主文件
        $phpExcel = new \PHPExcel();
        //建立讀入器
        if($extension=='xlsx'){
            $objRender = \PHPExcel_IOFactory::createReader('excel2007');
        }else{
            $objRender = \PHPExcel_IOFactory::createReader('Excel5');
        }
        //讀取excel文件
        $ExcelObj = $objRender->load($file['tmp_name']);
        //查看有幾個sheet
        $sheetContent = $ExcelObj->getSheet(0)->toArray();
        unset($sheetContent[0]);
        //取出文件的內容描述信息
        //$sheetColumn = $objRender->listWorksheetInfo($file['tmp_name']);
        foreach ($sheetContent as $k => $v){
            $arr['uname'] = $v[0];
            $arr['sex'] = $v[1];
            $arr['age'] = $v[2];
            $arr['class_name'] = $v[3];
            $res[] = $arr;
        }

        if(Db::name('excel_upload')->insertAll($res)){
            $this->success("導入成功");
        }else{
            $this->error("導入失敗");
        }
        //echo $sheetColumn[0]['totalColumns'];die;
    }

    //實現excel的導出操做
    public function excel_download(){
        ini_set('memory_limit', '1024M');//設置php容許的文件大小最大值
        Loader::import('PHPExcel.Classes.PHPExcel');//必須手動導入,不然會報PHPExcel類找不到
        $data = Db::table("excel_upload")->select();
        //實例化excel(至關於建立了一個excel)
        $objPHPExcel = new \PHPExcel();
        //得到當前活動的sheet
        $objSheet = $objPHPExcel->getActiveSheet();
        //給當前的sheet修更名稱
        $objSheet->setTitle("測試數據導出");
        //設置單元格垂直居中、水平居中
        $objSheet->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //設置單元格格式範圍的字體、字體大小、加粗
        $objSheet->getStyle("A1:Z1")->getFont()->setName("微軟雅黑")->setSize(10)->setBold(true);
        //給單元格填充背景色
        $objSheet->getStyle("A1:Z1")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('#00FF00');
        //填充邊框
        $styleArray = [
            'borders'=>[
                'outline'=>[
                    'style'=>\PHPExcel_Style_Border::BORDER_THICK,
                    'color' => ['argb' => '#F0F8FF'],
                ],
            ],
        ];

        //填充樣式
        $objSheet->getStyle("A1")->applyFromArray($styleArray);
        $objSheet->getStyle("B1")->applyFromArray($styleArray);
        $objSheet->getStyle("C1")->applyFromArray($styleArray);
        $objSheet->getStyle("D1")->applyFromArray($styleArray);
        $objSheet->getStyle("E1")->applyFromArray($styleArray);

        //填充數據
        $objSheet->setCellValue("A1","ID")
            ->setCellValue("B1","姓名")
            ->setCellValue("C1","性別")
            ->setCellValue("D1","年齡")
            ->setCellValue("E1","班級");


        //到這裏第一行就被佔用了,因此要從第二行開始循環
        $j = 2;
        foreach ($data as $k => $v){
            $objSheet->setCellValue("A".$j,$v['id'])
                ->setCellValue("B".$j,$v['uname'])
                ->setCellValue("C".$j,$v['sex'])
                ->setCellValue("D".$j,$v['age'])
                ->setCellValue("E".$j,$v['class_name']);
            $j++;
        }

//        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        header('Content-Disposition: attachment;filename="' . date('Ymd') . '.xlsx"');
//        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, 'Excel2007');
//        $objWriter->save('php://output');


//        exit;

        //設置文件保存的命名、編碼、同時開放保存路徑的權限
        //命名
        $file_name = "上海軟工專業高級成材率彙總 ".date("Y-m-d",time()).".xlsx";
        //編碼
        header('Content-Type:application/vnd.ms-excel;charset=utf-8');
        //告訴瀏覽器要輸出的名稱
        header("Content-Disposition:attachment;filename=$file_name");
        //禁止瀏覽器緩存
        header('Cache-Control:max-age=0');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
        //完全開放保存路徑
        $objWriter->save('php://output');
        exit();
    }

    public function te(){
        $a = "
<table>
<thead>
<tr>
<th style='color: #ffb454'>adsf</th>
<th>中文</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>123</td>
</tr>
</tbody>
</table>
";

        $a = "\xEF\xBB\xBF" . $a;
        $filename = date('Ymd').'.xls'; //設置文件名
        header( "Content-Type: application/vnd.ms-excel; name='excel'" );

        header( "Content-type: application/octet-stream" );

        header( "Content-Disposition: attachment; filename=".$filename );

//header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
//
//header( "Pragma: no-cache" );
//
//header( "Expires: 0" );

        exit( $a );
    }


    public function ttt(){
        ini_set('memory_limit', '1024M');//設置php容許的文件大小最大值
        Loader::import('PHPExcel.Classes.PHPExcel');//必須手動導入,不然會報PHPExcel類找不到
        $objPHPExcel = new \PHPExcel();
        $worksheet = $objPHPExcel->getActiveSheet();
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
// Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '暱稱')
            ->setCellValue('B1', '連接')
            ->setCellValue('C1', '房間號')
            ->setCellValue('D1', '分組');
// Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . date('Ymd') . '.xlsx"');
        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, 'Excel2007');
        $objWriter->save('php://output');


        exit;
    }
}

 

 

重點看前兩個方法   web

uploadExcel  
excel_download~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
相關文章
相關標籤/搜索