安裝
簡單示例
通過模板來生成文件
釋放內存
單元格
根據索引獲取英文列
設置值
合並單元格
居中顯示
寬度設置
批量設置單元格格式
直接輸出下載
自動計算列寬
函數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://output
或php://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();`
批量設置單元格格式
這樣效率更高
https://phpspreadsheet.readthedocs.io/en/develop/topics/recipes/#formatting-cells
https://phpspreadsheet.readthedocs.io/en/develop/topics/recipes/#valid-array-keys-for-style-applyfromarray
$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-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");