本文實(shí)例講述了PHP使用PhpSpreadsheet操作Excel。分享給大家供大家參考,具體如下:
一、PhpSpreadsheet 介紹
1、PhpSpreadsheet 是什么
PhpSpreadsheet是一個(gè)用純PHP編寫的庫,提供了一組類,使您可以讀取和寫入不同的電子表格文件格式
PhpSpreadsheet提供了豐富的API接口,可以設(shè)置諸多單元格以及文檔屬性,包括樣式、圖片、日期、函數(shù)等等諸多應(yīng)用,總之你想要什么樣的Excel表格,PhpSpreadsheet都能做到
- 使用 PhpSpreadsheet 開發(fā)的PHP要求 7.1或更高版本
- PhpSpreadsheet 支持鏈?zhǔn)讲僮?/li>
2、PhpSpreadsheet 支持的文件格式
3、PhpSpreadsheet 官方網(wǎng)址
- https://phpspreadsheet.readthedocs.io
4、PhpSpreadsheet 安裝
- composer require phpoffice/phpspreadsheet
二、基礎(chǔ)知識(shí)
1、載入
?php
# 載入composer自動(dòng)加載文件 require 瑞塊兒
require 'vendor/autoload.php'; autoload 奧特老特
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
2、獲取工作簿
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
3、獲取單元格
- 兩種獲取單元格方式
- getCell
- getCellByColumnAndRow
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
# 獲取單元格
$cell = $sheet->getCell('A1');
$cell = $sheet->getCellByColumnAndRow(1,1);
4、設(shè)置單元格
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
# 獲取單元格
$cellA = $sheet->getCell('A1');
# 設(shè)置單元格值
$cellA->setValue('歐陽克');
# 獲取單元格
$cellB = $sheet->getCellByColumnAndRow(1,2);
# 設(shè)置單元格值
$cellB->setValue('黃蓉');
# 獲取設(shè)置單元格,鏈?zhǔn)讲僮?
$sheet->getCell('A3')->setValue('郭靖');
$sheet->getCellByColumnAndRow(1,4)->setValue('楊康');
5、獲取單元格值
- getValue 獲取單元格值
- getCoordinate 獲取單元格坐標(biāo)
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
# 獲取單元格
$cellA = $sheet->getCell('A1');
# 設(shè)置單元格值
$cellA->setValue('歐陽克');
echo '值: ', $cellA->getValue(),PHP_EOL;
echo '坐標(biāo): ', $cellA->getCoordinate();
6、保存表格
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
# 獲取單元格
$cellA = $sheet->getCell('A1');
# 設(shè)置單元格值
$cellA->setValue('歐陽克');
# 獲取單元格
$cellB = $sheet->getCellByColumnAndRow(1,2);
# 設(shè)置單元格值
$cellB->setValue('黃蓉');
# 獲取設(shè)置單元格,鏈?zhǔn)讲僮?
$sheet->getCell('A3')->setValue('郭靖');
$sheet->getCellByColumnAndRow(1,4)->setValue('楊康');
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
三、強(qiáng)化單元格
1、設(shè)置單元格
- setCellValue
- 參數(shù)1:單元格位置
- 參數(shù)2:單元格的值
- setCellValueByColumnAndRow
- 參數(shù)1:列位置
- 參數(shù)2:行位置
- 參數(shù)3:單元格的值
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->setCellValueByColumnAndRow(1, 2, 1);
$sheet->setCellValueByColumnAndRow(2, 2, '歐陽克');
$sheet->setCellValueByColumnAndRow(3, 2, '18歲');
$sheet->setCellValueByColumnAndRow(4, 2, '188cm');
$sheet->setCellValueByColumnAndRow(1, 3, 2);
$sheet->setCellValueByColumnAndRow(2, 3, '黃蓉');
$sheet->setCellValueByColumnAndRow(3, 3, '17歲');
$sheet->setCellValueByColumnAndRow(4, 3, '165cm');
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
2、單元格文字樣式
- getStyle 獲取單元格樣式
- getFont 獲取單元格文字樣式
- setBold 設(shè)置文字粗細(xì)
- setName 設(shè)置文字字體
- setSize 設(shè)置文字大小
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->setCellValueByColumnAndRow(1, 2, 1);
$sheet->setCellValueByColumnAndRow(2, 2, '歐陽克');
$sheet->setCellValueByColumnAndRow(3, 2, '18歲');
$sheet->setCellValueByColumnAndRow(4, 2, '188cm');
$sheet->setCellValueByColumnAndRow(1, 3, 2);
$sheet->setCellValueByColumnAndRow(2, 3, '黃蓉');
$sheet->setCellValueByColumnAndRow(3, 3, '17歲');
$sheet->setCellValueByColumnAndRow(4, 3, '165cm');
$sheet->getStyle('B2')->getFont()->setBold(true)->setName('宋體')->setSize(20);
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
3、單元格文字顏色
- getColor() 獲取坐標(biāo)顏色
- setRGB() 設(shè)置字體顏色
- getRGB() 獲取字體顏色
- setARGB() 設(shè)置字體顏色
- getARGB() 獲取字體顏色
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->setCellValueByColumnAndRow(1, 2, 1);
$sheet->setCellValueByColumnAndRow(2, 2, '歐陽克');
$sheet->setCellValueByColumnAndRow(3, 2, '18歲');
$sheet->setCellValueByColumnAndRow(4, 2, '188cm');
$sheet->setCellValueByColumnAndRow(1, 3, 2);
$sheet->setCellValueByColumnAndRow(2, 3, '黃蓉');
$sheet->setCellValueByColumnAndRow(3, 3, '17歲');
$sheet->setCellValueByColumnAndRow(4, 3, '165cm');
$sheet->getStyle('B2')->getFont()->getColor()->setRGB('#AEEEEE');
echo $sheet->getStyle('B2')->getFont()->getColor()->getRGB(),PHP_EOL;
$sheet->getStyle('B3')->getFont()->getColor()->setARGB('FFFF0000');
echo $sheet->getStyle('B3')->getFont()->getColor()->getARGB();
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
4、單元格格式
- getNumberFormat 獲取格式
- setFormatCode 設(shè)置格式
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','2019-10-10 10:10:10');
$sheet->setCellValue('A2','2019-10-10 10:10:10');
$sheet->getStyle('A2')->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDD2);
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
- setWrapText 設(shè)置文本里的\n符合為:換行
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1',"歐陽克\n黃蓉");
$sheet->getStyle('A1')->getAlignment()->setWrapText(true);
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
- getHyperlink 獲取單元格鏈接
- setUrl 設(shè)置單元格鏈接
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','www.php.cn');
$sheet->getCell('A1')->getHyperlink()->setUrl('http://www.php.cn');
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
四、批量操作
1、使用公式
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','10');
$sheet->setCellValue('B1','15');
$sheet->setCellValue('C1','20');
$sheet->setCellValue('D1','25');
$sheet->setCellValue('E1','30');
$sheet->setCellValue('G1','35');
$sheet->setCellValue('A2', '總數(shù):');
$sheet->setCellValue('B2', '=SUM(A1:G1)');
$sheet->setCellValue('A3', '平均數(shù):');
$sheet->setCellValue('B3', '=AVERAGE(A1:G1)');
$sheet->setCellValue('A4', '最小數(shù):');
$sheet->setCellValue('B4', '=MIN(A1:G1)');
$sheet->setCellValue('A5', '最大數(shù):');
$sheet->setCellValue('B5', '=MAX(A1:G1)');
$sheet->setCellValue('A6', '最大數(shù):');
$sheet->setCellValue('B6', '\=MAX(A1:G1)'); // 使用轉(zhuǎn)義字符
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
2、批量賦值
- fromArray 從數(shù)組中的值填充工作表
- 參數(shù)1:數(shù)據(jù)(數(shù)組)
- 參數(shù)2:去除某個(gè)值
- 參數(shù)3:從哪個(gè)位置開始
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->fromArray(
[
[1,'歐陽克','18歲','188cm'],
[2,'黃蓉','17歲','165cm'],
[3,'郭靖','21歲','180cm']
],
3,
'A2'
);
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
3、合并單元格
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->mergeCells('A1:B5');
$sheet->getCell('A1')->setValue('歐陽克');
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
合并后,賦值只能給A1,開始的坐標(biāo)。
4、拆分單元格
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->mergeCells('A1:B5');
$sheet->unmergeCells('A1:B5');
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
5、列和行操作
- getColumnDimension 獲取一列
- getWidth 獲取一列的寬度
- setWidth 設(shè)置一列的寬度
- setAutoSize 設(shè)置一列的寬度自動(dòng)調(diào)整
- getDefaultColumnDimension 獲取一列的默認(rèn)值
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
echo $sheet->getColumnDimension('A')->getWidth();
$sheet->getColumnDimension('A')->setWidth(100);
$sheet->getColumnDimension('B')->setAutoSize(true);
$sheet->getDefaultColumnDimension()->setWidth(1);
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
- getRowDimension 獲取一行
- getRowHeight 獲取一行的高度
- setRowHeight 設(shè)置一行的高度
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
echo $sheet->getRowDimension(1)->getRowHeight();
$sheet->getRowDimension(1)->setRowHeight(100);
$sheet->getDefaultRowDimension()->setRowHeight(1);
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
- getHighestColumn 獲取總列數(shù)
- getHighestRow 獲取總行數(shù)
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->setCellValueByColumnAndRow(1, 2, 1);
$sheet->setCellValueByColumnAndRow(2, 2, '歐陽克');
$sheet->setCellValueByColumnAndRow(3, 2, '18歲');
$sheet->setCellValueByColumnAndRow(4, 2, '188cm');
$sheet->setCellValueByColumnAndRow(1, 3, 2);
$sheet->setCellValueByColumnAndRow(2, 3, '黃蓉');
$sheet->setCellValueByColumnAndRow(3, 3, '17歲');
$sheet->setCellValueByColumnAndRow(4, 3, '165cm');
echo $sheet->getHighestColumn();
echo $sheet->getHighestRow();
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
6、單元格樣式
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->setCellValueByColumnAndRow(1, 2, 1);
$sheet->setCellValueByColumnAndRow(2, 2, '歐陽克');
$sheet->setCellValueByColumnAndRow(3, 2, '18歲');
$sheet->setCellValueByColumnAndRow(4, 2, '188cm');
$styleArray = [
// use PhpOffice\PhpSpreadsheet\Style\Alignment; 文件里常量,就是參數(shù)
// Alignment::HORIZONTAL_CENTER 水平居中
// Alignment::VERTICAL_CENTER 垂直居中
'alignment' => [
// 'horizontal' => Alignment::HORIZONTAL_CENTER, //水平居中
// 'vertical' => Alignment::VERTICAL_CENTER, //垂直居中
'horizontal' => 'center', //水平居中
'vertical' => 'center', //垂直居中
],
// use PhpOffice\PhpSpreadsheet\Style\Border; 文件里常量,就是參數(shù)
// Border::BORDER_THICK 邊框樣式
'borders' => [
'outline' => [
// 'borderStyle' => '\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK',
'borderStyle' => 'thick',
'color' => ['argb' => 'FFFF0000'],
],
],
'font' => [
'name' => '黑體',
'bold' => true,
'size' => 22
]
];
$sheet->getStyle('A1')->applyFromArray($styleArray);
# Xlsx類 將電子表格保存到文件
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$writer = new Xlsx($spreadsheet);
$writer->save('1.xlsx');
五、工作薄操作
1、xlsx 文件下載
- IOFactory::createWriter 寫入到文件
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->setCellValueByColumnAndRow(1, 2, 1);
$sheet->setCellValueByColumnAndRow(2, 2, '歐陽克');
$sheet->setCellValueByColumnAndRow(3, 2, '18歲');
$sheet->setCellValueByColumnAndRow(4, 2, '188cm');
// MIME 協(xié)議,文件的類型,不設(shè)置,會(huì)默認(rèn)html
header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// MIME 協(xié)議的擴(kuò)展
header('Content-Disposition:attachment;filename=1.xlsx');
// 緩存控制
header('Cache-Control:max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
// php://output 它是一個(gè)只寫數(shù)據(jù)流, 允許你以 print 和 echo一樣的方式寫入到輸出緩沖區(qū)。
$writer->save('php://output');
2、xls 文件下載
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->setCellValueByColumnAndRow(1, 2, 1);
$sheet->setCellValueByColumnAndRow(2, 2, '歐陽克');
$sheet->setCellValueByColumnAndRow(3, 2, '18歲');
$sheet->setCellValueByColumnAndRow(4, 2, '188cm');
$filename = '1.xls';
header('Content-Type:application/vnd.ms-excel');
header('Content-Disposition:attachment;filename=1.xls');
header('Cache-Control:max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
3、設(shè)置工作簿標(biāo)題
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','姓名');
$sheet->setCellValue('C1','年齡');
$sheet->setCellValue('D1','身高');
$sheet->setCellValueByColumnAndRow(1, 2, 1);
$sheet->setCellValueByColumnAndRow(2, 2, '歐陽克');
$sheet->setCellValueByColumnAndRow(3, 2, '18歲');
$sheet->setCellValueByColumnAndRow(4, 2, '188cm');
$sheet->setTitle('歐陽克');
// MIME 協(xié)議,文件的類型,不設(shè)置,會(huì)默認(rèn)html
header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// MIME 協(xié)議的擴(kuò)展
header('Content-Disposition:attachment;filename=1.xlsx');
// 緩存控制
header('Cache-Control:max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
// php://output 它是一個(gè)只寫數(shù)據(jù)流, 允許你以 print 和 echo一樣的方式寫入到輸出緩沖區(qū)。
$writer->save('php://output');
4、讀取表格
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 創(chuàng)建讀操作
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
# 打開文件、載入excel表格
$spreadsheet = $reader->load('1.xlsx');
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
# 獲取 單元格值 和 坐標(biāo)
$cellC1 = $sheet->getCell('B2');
echo '值: ', $cellC1->getValue(),PHP_EOL;
echo '坐標(biāo): ', $cellC1->getCoordinate(),PHP_EOL;
$sheet->setCellValue('B2','歐陽鋒');
# 獲取 單元格值 和 坐標(biāo)
$cellC2 = $sheet->getCell('B2');
echo '值: ', $cellC2->getValue(),PHP_EOL;
echo '坐標(biāo): ', $cellC2->getCoordinate();
六、office 后綴對(duì)應(yīng)的 content-type
后綴 |
MIME Type |
.doc |
application/msword |
.dot |
application/msword |
.docx |
application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.dotx |
application/vnd.openxmlformats-officedocument.wordprocessingml.template |
.docm |
application/vnd.ms-word.document.macroEnabled.12 |
.dotm |
application/vnd.ms-word.template.macroEnabled.12 |
.xls |
application/vnd.ms-excel |
.xlt |
application/vnd.ms-excel |
.xla |
application/vnd.ms-excel |
.xlsx |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xltx |
application/vnd.openxmlformats-officedocument.spreadsheetml.template |
.xlsm |
application/vnd.ms-excel.sheet.macroEnabled.12 |
.xltm |
application/vnd.ms-excel.template.macroEnabled.12 |
.xlam |
application/vnd.ms-excel.addin.macroEnabled.12 |
.xlsb |
application/vnd.ms-excel.sheet.binary.macroEnabled.12 |
.ppt |
application/vnd.ms-powerpoint |
.pot |
application/vnd.ms-powerpoint |
.pps |
application/vnd.ms-powerpoint |
.ppa |
application/vnd.ms-powerpoint |
.pptx |
application/vnd.openxmlformats-officedocument.presentationml.presentation |
.potx |
application/vnd.openxmlformats-officedocument.presentationml.template |
.ppsx |
application/vnd.openxmlformats-officedocument.presentationml.slideshow |
.ppam |
application/vnd.ms-powerpoint.addin.macroEnabled.12 |
.pptm |
application/vnd.ms-powerpoint.presentation.macroEnabled.12 |
.potm |
application/vnd.ms-powerpoint.presentation.macroEnabled.12 |
.ppsm |
application/vnd.ms-powerpoint.slideshow.macroEnabled.12 |
七、實(shí)戰(zhàn)
1、導(dǎo)出數(shù)據(jù)
CREATE TABLE `login_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) DEFAULT NULL COMMENT '管理員ID',
`client` tinyint(4) unsigned DEFAULT '0' COMMENT '0-PC 1-ios 2-android',
`add_time` int(11) DEFAULT '0' COMMENT '創(chuàng)建時(shí)間',
`ip` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '登錄IP',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=1122 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='登錄日志';
- index.php 數(shù)據(jù)列表頁面
?php
# 載入方法庫
require 'function.php';
$select = select('login_log','*');
if(empty($select)){
exit;
}else{
foreach($select as $v){
switch ($v['client']) {
case 0:
$v['client'] = 'PC電腦';
break;
case 1:
$v['client'] = '蘋果手機(jī)';
break;
case 2:
$v['client'] = '安卓手機(jī)';
break;
}
$v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
}
}
?>
!DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>導(dǎo)出數(shù)據(jù)/title>
link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" rel="external nofollow" >
/head>
body>
div style="text-align:center;">
a href="download.php" rel="external nofollow" rel="external nofollow" class="layui-btn layui-btn-radius layui-btn-danger">導(dǎo)出數(shù)據(jù)/a>
/div>
table class="layui-table">
thead>
tr>
th>ID/th>
th>用戶ID/th>
th>登陸設(shè)備/th>
th>登陸時(shí)間/th>
th>登陸ip/th>
/tr>
/thead>
tbody>
?php
foreach($select as $v){
?>
tr>
td>?php echo $v['id'] ?>/td>
td>?php echo $v['uid'] ?>/td>
td>?php echo $v['client'] ?>/td>
td>?php echo $v['add_time'] ?>/td>
td>?php echo $v['ip'] ?>/td>
/tr>
?php
}
?>
/tbody>
/table>
/body>
/html>
?php
# 載入方法庫
require 'function.php';
$select = select('login_log','*');
if(empty($select)){
exit;
}else{
foreach($select as $v){
switch ($v['client']) {
case 0:
$v['client'] = 'PC電腦';
break;
case 1:
$v['client'] = '蘋果手機(jī)';
break;
case 2:
$v['client'] = '安卓手機(jī)';
break;
}
$v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
}
}
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','ID');
$sheet->setCellValue('B1','用戶ID');
$sheet->setCellValue('C1','登陸設(shè)備');
$sheet->setCellValue('D1','登陸時(shí)間');
$sheet->setCellValue('E1','登陸ip');
$sheet->fromArray(
$select,
null,
'A2'
);
// MIME 協(xié)議,文件的類型,不設(shè)置,會(huì)默認(rèn)html
header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// MIME 協(xié)議的擴(kuò)展
header('Content-Disposition:attachment;filename=1.xlsx');
// 緩存控制
header('Cache-Control:max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
// php://output 它是一個(gè)只寫數(shù)據(jù)流, 允許你以 print 和 echo一樣的方式寫入到輸出緩沖區(qū)。
$writer->save('php://output');
?>
2、導(dǎo)入數(shù)據(jù)
# 商品分類表
CREATE TABLE `shop_cat` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`pid` int(10) unsigned DEFAULT '0' COMMENT '父ID',
`name` varchar(50) DEFAULT NULL COMMENT '分類名',
`status` tinyint(1) unsigned DEFAULT '1' COMMENT '狀態(tài) 1開啟 0關(guān)閉',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COMMENT='分類表';
INSERT INTO `shop_cat` VALUES (1, 0, '女裝', 1);
INSERT INTO `shop_cat` VALUES (2, 0, '男裝', 1);
INSERT INTO `shop_cat` VALUES (3, 0, '孕產(chǎn)', 1);
INSERT INTO `shop_cat` VALUES (4, 1, '連衣裙', 1);
INSERT INTO `shop_cat` VALUES (5, 1, '牛仔褲', 1);
INSERT INTO `shop_cat` VALUES (6, 2, '襯衫', 1);
INSERT INTO `shop_cat` VALUES (7, 3, '睡衣', 1);
# 商品表
CREATE TABLE `shop_list` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cat_id` int(10) unsigned DEFAULT NULL COMMENT '分類ID',
`cat_fid` int(10) unsigned DEFAULT NULL COMMENT '分類父ID',
`title` varchar(200) NOT NULL COMMENT '商品標(biāo)題',
`price` double(10,2) unsigned NOT NULL COMMENT '價(jià)格',
`img` varchar(200) NOT NULL COMMENT '商品圖片',
`add_time` int(10) unsigned NOT NULL COMMENT '添加時(shí)間',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='商品表';
!DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>導(dǎo)出數(shù)據(jù)/title>
link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" rel="external nofollow" >
/head>
body>
div style="text-align:center;">
button type="button" class="layui-btn" id="up">i class="layui-icon">/i>上傳文件/button>
a href="download.php" rel="external nofollow" rel="external nofollow" class="layui-btn layui-btn-danger">i class="layui-icon">/i>示例下載/a>
/div>
div id="log" style="text-align:center;">
/div>
/body>
/html>
script src="layui/layui.js" charset="utf-8">/script>
script>
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
upload.render({
elem: '#up'
,url: 'data.php'
,accept: 'file' //普通文件
,done: function(res){
if(res.code == 0){
for(var i=0;ires.data.length;i++){
$("#log").append('div>'+res.data[i]+'/div>');
}
}
}
});
})
/script>
?php
$file = $_FILES['file']['tmp_name'];
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 載入方法庫
require 'function.php';
# 創(chuàng)建讀操作
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
# 打開文件、載入excel表格
$spreadsheet = $reader->load($file);
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
# 獲取總列數(shù)
$highestColumn = $sheet->getHighestColumn();
# 獲取總行數(shù)
$highestRow = $sheet->getHighestRow();
# 列數(shù) 改為數(shù)字顯示
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
$log = [];
for($a=2;$a$highestRow;$a++){
$title = $sheet->getCellByColumnAndRow(1,$a)->getValue();
$cat_fname = $sheet->getCellByColumnAndRow(2,$a)->getValue();
$cat_name = $sheet->getCellByColumnAndRow(3,$a)->getValue();
$price = $sheet->getCellByColumnAndRow(4,$a)->getValue();
$img = $sheet->getCellByColumnAndRow(5,$a)->getValue();
$cat_fid = find('shop_cat','id','name="'.$cat_fname.'"');
$cat_id = find('shop_cat','id','name="'.$cat_name.'"');
$data = [
'title' => $title,
'cat_fid' => $cat_fid['id'],
'cat_id' => $cat_id['id'],
'price' => $price,
'img' => $img,
'add_time' => time(),
];
$ins = insert('shop_list',$data);
if($ins){
$log[] = '第'.$a.'條,插入成功';
}else{
$log[] = '第'.$a.'條,插入失敗';
}
}
echo json_encode(['code'=>0,'msg'=>'成功','data'=>$log]);
?php
# 載入composer自動(dòng)加載文件
require 'vendor/autoload.php';
# 給類文件的命名空間起個(gè)別名
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
# 實(shí)例化 Spreadsheet 對(duì)象
$spreadsheet = new Spreadsheet();
# 獲取活動(dòng)工作薄
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1','商品標(biāo)題');
$sheet->setCellValue('B1','一級(jí)分類');
$sheet->setCellValue('C1','二級(jí)分類');
$sheet->setCellValue('D1','進(jìn)貨價(jià)');
$sheet->setCellValue('E1','圖片');
$data = [
'云朵般輕盈的仙女裙 高級(jí)釘珠收腰長裙 氣質(zhì)無袖連衣裙',
'女裝',
'連衣裙',
279.99,
'https://gd3.alicdn.com/imgextra/i3/266969832/O1CN01PWUBBB2MV6ekBKtb6_!!266969832.jpg_400x400.jpg',
];
$sheet->fromArray(
$data,
null,
'A2'
);
// MIME 協(xié)議,文件的類型,不設(shè)置,會(huì)默認(rèn)html
header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// MIME 協(xié)議的擴(kuò)展
header('Content-Disposition:attachment;filename=商品列表示例.xlsx');
// 緩存控制
header('Cache-Control:max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
// php://output 它是一個(gè)只寫數(shù)據(jù)流, 允許你以 print 和 echo一樣的方式寫入到輸出緩沖區(qū)。
$writer->save('php://output');
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php操作office文檔技巧總結(jié)(包括word,excel,access,ppt)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計(jì)算法總結(jié)》、《PHP數(shù)學(xué)運(yùn)算技巧總結(jié)》、《php正則表達(dá)式用法總結(jié)》、《php字符串(string)用法總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- PHP讀取Excel內(nèi)的圖片(phpspreadsheet和PHPExcel擴(kuò)展庫)
- ThinkPHP5與單元測(cè)試PHPUnit使用詳解
- PHP單元測(cè)試配置與使用方法詳解
- PHPUnit + Laravel單元測(cè)試常用技能
- PHP使用phpunit進(jìn)行單元測(cè)試示例
- 使用PHPUnit進(jìn)行單元測(cè)試并生成代碼覆蓋率報(bào)告的方法
- PHP單元測(cè)試框架PHPUnit用法詳解
- php使用unset()刪除數(shù)組中某個(gè)單元(鍵)的方法
- PhpSpreadsheet設(shè)置單元格常用操作匯總