phpspreadsheet開發手記

 


安裝
簡單示例
通過模板來生成文件
釋放內存
單元格
根據索引獲取英文列
設置值
合併單元格
居中顯示
寬度設置
直接輸出下載
自動計算列寬
函數formula
單元格變可點擊的超鏈


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

 

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

安裝

composer require phpoffice/phpspreadsheet 版本號 
默認情況會提示找不到庫,上composer找是有的,是因爲還沒有穩定版,所以要指定版本 1.0.0beta

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

  • 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,輸出網頁)

通過模板來生成文件

全用代碼寫太累,可以用模板來修改,但是對於動態數據,還是要由代碼生成

//通過工廠模式創建內容
$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');

釋放內存

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

$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();`

直接輸出下載

        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-reference

$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");

轉自:http://www.cnblogs.com/leestar54/p/7786806.html 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章