PhpSpreadsheet 官方網站:https://github.com/PHPOffice/PhpSpreadsheet

英文使用手冊:https://phpspreadsheet.readthedocs.io/

安裝 – 使用 composer

最快速穩定的方法就是使用 composer 來管理我們的套件。

composer require phpoffice/phpspreadsheet

如果對 compoer 不了解,可以參考聖佑的 PHP 也有 Day #28 – Composer 從入門到實戰

基本用法 1 – 將 xlsx 檔存在伺服器上

產生一個簡單的 excel 檔,並在伺服器目前的目錄下儲存這個檔案

<?php

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');

基本用法 2 – 讓使用者下載成 xlsx 檔案

產生一個簡單的 excel 檔,並傳送給使用者,讓使用者能開啟或儲存這個 excel 檔案

<?php

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');

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

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');

基本用法 3 – 讓使用者下載成 xls 檔案

有時候需要比較舊的 excel 97-2003 格式,也就是附檔名為 xls 的excel 檔

<?php

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');

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

// 也可以使用以下的方式,但要先導入 IOFactory
// 好處是可以在執行時期動態決定檔案格式
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
Last modified: 2019-11-07

Author

Comments

Write a Reply or Comment

Your email address will not be published.