使用phpexcel導出excel和phpword導出word--簡單使用


<?php
namespace app\index\controller;

//離線環境不能使用composer安裝,只能下載包文件,然后放在vendor下,代碼中require使用
require_once VENDOR_PATH.'/PHPExcel/PHPExcel.php';

use app\index\controller\Base;

class Phpexcel extends Base{

    public function __construct(){
        parent::__construct();
    }

    public function getExcel(){
        $pexcel = new \PHPExcel();
        $pexcel -> setActiveSheetIndex(0);//設置sheet序號
        $pexcel -> getActiveSheet() -> setTitle('電信網絡詐騙信息表');//設置sheet的名稱
        $pexcel -> getActiveSheet() -> setCellValue('A1','案件編號');//設置A1內容
     $pexcel -> getActiveSheet() -> mergeCells('A1:A3');//合並A1到A3列,合並行一樣的寫法
     $pexcel -> getDefaultStyle() -> getAlignment() -> setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
     $pexcel -> getActiveSheet() -> getStyle('A1') -> getAlignment() -> setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//A1水平居中
     $pexcel -> getActiveSheet() -> getStyle('A1') -> getFill() 
        -> applyFromArray(array('type'=> \PHPExcel_Style_Fill::FILL_SOLID,'color' => array('rgb' => 'ADD8E6')));//設置A1的填充顏色

        $filename = date('YmdHis').'.xls';//文檔名稱
        //設置輸出格式,寫入到輸出流
        $xlsWrite = new \PHPExcel_Writer_Excel5($pexcel);
        header("Content-Type:application/force-download");
        header("Content-Type:application/octet-stream");
        header("Content-Disposition:attachment;filename='".$filename."'");
        header("pragma:no-cache");
        $xlsWrite->save("php://output");
    }
  
   public function getWord(){
      $phpword = new \PhpWord();
      $phpword -> setDefaultFontName('仿宋');//設置字體
       $phpword -> setDefaultFontSize(16);//設置字號
      $fontcolor = array(
        "color" => '#FF0000'
      );//顏色
      $section = $phpword -> createSection();
      //section的addText方法生成的是段落,下面兩句自帶換行
       $section -> addText("問:",$fontcolor);//設置內容及內容的顏色
      $section-> addText("答:");
      //section的TextRun的addText方法生成的是一個字符串,沒有換行,下面兩句連成一個字符串
      $textrun = $section -> createTextRun();
      $textrun -> addText("第1個是電話");
      $textrun -> addText("第2個是微信");
 
      $filename = date('YmdHis').'.doc';
      header("Content-Description:File Transfer");
       header('Content-Disposition:attachment;filename='.$filename);
       header("Expires:0");
       $xmlWriter = \PHPWord_IOFactory::createWriter($phpword,'Word2007');
       $xmlWriter -> save('php://output');
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM