phpspreadsheet開發手記


PhpSpreadsheet是一個純PHP類庫,使你可以讀寫Excel、LibreOffic Calc等這樣的表格格式。
https://phpspreadsheet.readthedocs.io/en/develop/

列從1開始算,行從1開始算
$sheet->setCellValueByColumnAndRow(1,1,'特別說明');php

安裝

composer require phpoffice/phpspreadsheet 版本號
默認狀況會提示找不到庫,上composer找是有的,是由於尚未穩定版,因此要指定版本 1.0.0betahtml

依賴
The following software is required to develop using PhpSpreadsheet:thinkphp

  • PHP version 5.6 or newer
  • PHP extension php_zip enabled
  • PHP extension php_xml enabled
  • PHP extension php_gd2 enabled (if not compiled in)

默認使用ZipArchive來壓縮保存
注意讀寫權限瀏覽器

簡單示例

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');

默認保存到執行php的根目錄,以thinkphp爲例index.php在D:\wwwroot\thinkphp\public,那麼文件就保存在這
注:若是不想保存到文件,能夠傳入php://outputphp://stdout直接輸出(例如html,輸出網頁)緩存

經過模板來生成文件

全用代碼寫太累,能夠用模板來修改,可是對於動態數據,仍是要由代碼生成app

//經過工廠模式建立內容
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx');

$worksheet = $spreadsheet->getActiveSheet();

$worksheet->getCell('A1')->setValue('John');
$worksheet->getCell('A2')->setValue('Smith');
//經過工廠模式來寫內容
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('write.xls');

釋放內存

爲了防止內存泄露,建議用完手動清理composer

$spreadsheet->disconnectWorksheets();
unset($spreadsheet);

單元格

根據索引獲取英文列

其中A=0
Cell::stringFromColumnIndex($pColumn)函數

設置值

$worksheet->getCell('A1')->setValue('John');
$sheet->setCellValue('A1', 'Hello World !');
$sheet->setCellValueByColumnAndRow($columnIndex, $rowIndex, $value);

合併單元格

/**
    * Set merge on a cell range by using numeric cell coordinates.
    *
    * @param int $pColumn1 Numeric column coordinate of the first cell (A = 0)
    * @param int $pRow1 Numeric row coordinate of the first cell
    * @param int $pColumn2 Numeric column coordinate of the last cell (A = 0)
    * @param int $pRow2 Numeric row coordinate of the last cell
    *
    * @throws Exception
    *
    * @return Worksheet
    */
    $sheet->mergeCellsByColumnAndRow($pColumn1, $pRow1, $pColumn2, $pRow2)

居中顯示

$sheet->getStyleByColumnAndRow(0, 1, $columnIndex, $rowIndex)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);

寬度設置

`$this->getColumnDimension($columnIndex)->setWidth($width);`
還能夠讓其自適應(不靠譜,建議自行設置)
`$sheet->calculateColumnWidths();`

批量設置單元格格式

這樣效率更高
https://phpspreadsheet.readthedocs.io/en/develop/topics/recipes/#formatting-cells
https://phpspreadsheet.readthedocs.io/en/develop/topics/recipes/#valid-array-keys-for-style-applyfromarrayui

$spreadsheet->getActiveSheet()->getStyleByColumnAndRow(1, 1, 18, count($todayRank) + 2)->applyFromArray([
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            ]
        ]);

直接輸出下載

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告訴瀏覽器輸出07Excel文件
//header('Content-Type:application/vnd.ms-excel');//告訴瀏覽器將要輸出Excel03版本文件
        header('Content-Disposition: attachment;filename="01simple.xlsx"');//告訴瀏覽器輸出瀏覽器名稱
        header('Cache-Control: max-age=0');//禁止緩存
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');

自動計算列寬

//注意$fromCol,$toCol是string類型,例如A、B、C、D
  function autoFitColumnWidthToContent($sheet, $fromCol, $toCol) {
        if (empty($toCol) ) {//not defined the last column, set it the max one
            $toCol = $sheet->getColumnDimension($sheet->getHighestColumn())->getColumnIndex();
        }
        for($i = $fromCol; $i <= $toCol; $i++) {
            $sheet->getColumnDimension($i)->setAutoSize(true);
        }
        $sheet->calculateColumnWidths();
    }

函數formula

https://phpspreadsheet.readthedocs.io/en/develop/references/function-list-by-name/
https://phpspreadsheet.readthedocs.io/en/develop/topics/calculation-engine/#function-referencethis

$worksheet->setCellValue('A12', '=DMIN(A4:E10,"Profit",A1:A2)');

$retVal = $worksheet->getCell('A12')->getCalculatedValue();
// $retVal = 225

單元格變可點擊的超鏈

$spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
$spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('https://www.example.com');

若是須要在表格內跳轉,則

$spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
$spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl("sheet://'Sheetname'!A1");
相關文章
相關標籤/搜索