:::

2-1 PhpSpreadsheet的安裝及使用

一、安裝PhpSpreadsheet

  1. 官網:https://github.com/PHPOffice/PhpSpreadsheet
  2. 手冊:https://phpspreadsheet.readthedocs.io/en/develop/
  3. 先在網頁錄下建立專案資料夾。如:excel
  4. 進入專案資料夾執行以下指令:
    composer require phpoffice/phpspreadsheet
  5. 如此即可安裝好PhpSpreadsheet 元件

二、基本Excel

  1. 建立excel.php
    <?php
    
    require 'vendor/autoload.php';
    
    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
    
    $spreadsheet = new Spreadsheet();
    $sheet       = $spreadsheet->getActiveSheet();
    $sheet->setCellValue('A1', '這是第一格');
    
    $writer = new Xlsx($spreadsheet);
    $writer->save('存放於主機檔名.xlsx');

三、利用PHP內建伺服器運作

  1. 在終端機執行:
    php -S localhost:8000
  2. 如此,無須網頁伺服器即可運作:
    http://localhost:8000/excel.php

     

四、若想直接下載成xlsx

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="檔名.xlsx"');
header('Cache-Control: max-age=0');

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');

四、若想直接下載成xls

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="檔名.xls"');
header('Cache-Control: max-age=0');

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');

 


:::

書籍目錄

展開 | 闔起

快速登入


https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1336%26tbsn%3D36

計數器

今天: 4462446244624462
昨天: 2489248924892489
總計: 8026444802644480264448026444802644480264448026444