最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

php使用phpoffice/phpspreadsheet拓展操作excel實(shí)例

 更新時間:2023年11月07日 11:02:32   作者:huaweichenai  
這篇文章主要為大家介紹了php使用phpoffice/phpspreadsheet拓展操作excel實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

一:安裝phpoffice/phpspreadsheet

composer require phpoffice/phpspreadsheet

二:phpoffice/phpspreadsheet API接口詳解

PhpSpreadsheet提供了豐富的API接口,可以設(shè)置諸多單元格以及文檔屬性,包括樣式、圖片、日期、函數(shù)等等諸多應(yīng)用,總之你想要什么樣的Excel表格,PhpSpreadsheet都能做到

在使用phpoffice/phpspreadsheet的API接口前,確保引入了正確的文件并實(shí)例化

use PhpOffice\PhpSpreadsheet\Spreadsheet;//引入文件
$spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();//創(chuàng)建一個新的excel文檔
$sheet = $spreadsheet->getActiveSheet();//獲取當(dāng)前操作sheet的對象

1:設(shè)置字體:

$sheet->getStyle('A7:B7')->getFont()->setBold(true)->setName('Arial')
            ->setSize(10);//將A7至B7兩單元格設(shè)置為粗體字,Arial字體,10號字
$sheet->getStyle('B1')->getFont()->setBold(true);//將B1單元格設(shè)置為粗體字

2:設(shè)置顏色

$sheet->getStyle('A1')->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);//將A1單元格文字顏色設(shè)為紅色

3:設(shè)置列寬

$sheet->getColumnDimension('A')->setWidth(20);//將A列的寬度設(shè)為20(字符)
$sheet->getColumnDimension('B')->setAutoSize(true);//將B列的寬度設(shè)為自動寬度
$sheet->getDefaultColumnDimension()->setWidth(12);//設(shè)置默認(rèn)列寬為12

4:設(shè)置行高

$sheet->getRowDimension('10')->setRowHeight(100);//將第十行的高度設(shè)為100pt
$sheet->getDefaultRowDimension()->setRowHeight(15);//設(shè)置默認(rèn)行高為15

5 : 對齊

$sheet->getStyle('A:D')->getAlignment()
            ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER) //設(shè)置垂直居中
            ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER) //設(shè)置水平居中
            ->setWrapText(true); //設(shè)置自動換行

6:合并單元格

$sheet->mergeCells('A1:D2');//A1到D2合并為一個單元格

7:將合并后的單元格拆分

$sheet->unmergeCells('A1:D2');//將合并后的單元格拆分。

8:使用applyFromArray實(shí)現(xiàn)單元格樣式設(shè)置

//樣式變量
$style = [
//設(shè)置字體樣式
'font' => [
        'name' => 'Arial',
        'bold' => true,
        'italic' => false,
        'underline' => Font::UNDERLINE_DOUBLE,
        'strikethrough' => false,
        'color' => [
            'rgb' => '808080'
        ]
    ],
//設(shè)置邊框線樣式
'borders' => [
         //allBorders所有的邊框線樣式
         //左邊框線
       'bottom' => [
           'borderStyle' => Border::BORDER_DASHDOT,
           'color' => [
              'rgb' => '808080'
            ]
       ],
         //上邊框線
       'top' => [
           'borderStyle' => Border::BORDER_DASHDOT,
           'color' => [
               'rgb' => '808080'
           ]
       ]
],
//對齊樣式
'alignment' => [
   'horizontal' => Alignment::HORIZONTAL_CENTER,
   'vertical' => Alignment::VERTICAL_CENTER,
   'wrapText' => true,
],
//是否使用前綴
'quotePrefix'    => true
];
$sheet->getStyle('A1:D1')->applyFromArray($style);

9:設(shè)置工作表標(biāo)題

$sheet->setTitle('Hello');;//設(shè)置當(dāng)前工作表標(biāo)題。

10:設(shè)置單元格的格式

$sheet->getStyle('D2')->getNumberFormat()
            ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);//將D2單元格的格式設(shè)為文本格式
$sheet->getStyle('A1:D2')->getNumberFormat()
            ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);//將A1到D2的單元格設(shè)置為文本格式

11 : 換行

$sheet->getCell('A4')->setValue("hello\nworld");//將A4單元格的hello和world換行

12:超鏈接

//將A2單元格內(nèi)容設(shè)置blog并點(diǎn)擊跳轉(zhuǎn)https://www.wj0511.com
$sheet->setCellValue('A2', 'blog');
$sheet->getCell('A2')->getHyperlink()->setUrl('https://www.wj0511.com');

13:使用函數(shù)

常用函數(shù)有:總和(SUM),最大數(shù)(MAX),最小數(shù)(MIN),平均值(AVERAGE)

$sheet->setCellValue('B5', '=SUM(B1:B4)');//將B5單元格的內(nèi)容設(shè)為B1到B4的之和

14:設(shè)置文檔屬性

$spreadsheet->getProperties()
    ->setCreator("author")    //作者
    ->setLastModifiedBy("last-author") //最后修改者
    ->setTitle("title")  //標(biāo)題
    ->setSubject("subject") //副標(biāo)題
    ->setDescription("description")  //描述
    ->setKeywords("keywords") //關(guān)鍵字
    ->setCategory("category"); //分類

三:簡單實(shí)現(xiàn)生成excel(這里我下載使用的Yii框架自帶的下載方法)

<?php
/**
 * author: wangjian
 * date: 2019/7/15
 */
namespace app\controllers;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Yii;
use yii\web\Controller;
class ExcelController extends Controller
{
    /**
     * 數(shù)字轉(zhuǎn)字母 (類似于Excel列標(biāo))
     * @param Int $index 索引值
     * @param Int $start 字母起始值
     * @return String 返回字母
     */
    public function intToChr($index, $start = 65)
    {
        $str = '';
        if (floor($index / 26) > 0) {
            $str .= $this->intToChr(floor($index / 26)-1);
        }
        return $str . chr($index % 26 + $start);
    }
    public function actionIndex()
    {
        //頭信息
        $header = [
            '姓名',
            '性別',
            '學(xué)歷',
            '年齡',
            '身高',
        ];
        //內(nèi)容
        $data = [
            [
                '小明',
                '男',
                '專科',
                '18',
                '175'
            ],
            [
                '小紅',
                '女',
                '本科',
                '18',
                '155'
            ],
            [
                '小藍(lán)',
                '男',
                '???,
                '20',
                '170'
            ],
            [
                '張三',
                '男',
                '本科',
                '19',
                '165'
            ],
            [
                '李四',
                '男',
                '???,
                '22',
                '175'
            ],
            [
                '王二',
                '男',
                '???,
                '25',
                '175'
            ],
            [
                '麻子',
                '男',
                '本科',
                '22',
                '180'
            ],
        ];
        $header = array_values($header);
        $data = array_values($data);
        //獲取列信息
        $column = []; //['A','B','C','D','E']
        foreach ($header as $k => $item) {
            $column[$k] = $this->intToChr($k);
        }
        //獲取初始列和最終列
        $firstColum = $column[0];
        $lastColum = $column[count($column) - 1];
        //獲取初始行和最終行
        $firstRow = 1;
        $lastRow = count($data) + 1;
        $row = 1;
        $spreadsheet = new Spreadsheet();//創(chuàng)建一個新的excel文檔
        $sheet = $spreadsheet->getActiveSheet();//獲取當(dāng)前操作sheet的對象
        $sheet->setTitle('標(biāo)題'); //設(shè)置標(biāo)題
        $sheet->getStyle("{$firstColum}:{$lastColum}")->getAlignment()
            ->setVertical(Alignment::VERTICAL_CENTER) //設(shè)置垂直居中
            ->setHorizontal(Alignment::HORIZONTAL_CENTER) //設(shè)置水平居中
            ->setWrapText(true); //設(shè)置自動換行
        //設(shè)置寬度
        $sheet->getDefaultColumnDimension()->setWidth(20);
        $headerStyle = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
            ],
            'font' => [
                'bold' => true,
                'size' => 14,
            ],
        ];
        $cellStyle = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
            ],
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => 'FF000000'],
                ]
            ],
            'font' => [
                'size' => 10,
            ],
        ];
        //將excel的單元格格式設(shè)為文本格式
        $sheet->getStyle("{$firstColum}{$firstRow}:{$lastColum}{$lastRow}")->getNumberFormat()
            ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);
        //設(shè)置頭信息樣式
        $sheet->getRowDimension($row)->setRowHeight(30);//設(shè)置行高
        $sheet->getStyle("{$firstColum}{$row}:{$lastColum}{$row}")->applyFromArray($headerStyle);
        //設(shè)置頭信息
        foreach ($header as $key => $item) {
            $sheet->setCellValue("{$column[$key]}{$row}", $item);
        }
        $row++;
        foreach ($data as $key => $model) {
            $sheet->getRowDimension($row)->setRowHeight(30);//設(shè)置行高
            $sheet->getStyle("{$firstColum}{$row}:{$lastColum}{$row}")->applyFromArray($cellStyle);
            $i = 0;
            foreach ($model as $value) {
                $sheet->setCellValue("{$column[$i]}{$row}", $value);
                $i++;
            }
            $row++;
        }
        $file = '表格' . '.xlsx';//保存地址
        $writer = new Xlsx($spreadsheet);
        $writer->save($file);//生成excel文件
        Yii::$app->response->sendFile($file, '下載的excel名稱.xlsx')->send();
    }
}

四:讀取excel文件

$title = [];//excel工作表標(biāo)題
$info = [];//excel內(nèi)容
$fileName = "表格.xlsx";
$spreadsheet = IOFactory::load($fileName);
//$worksheet = $spreadsheet->getActiveSheet();   //獲取當(dāng)前文件內(nèi)容
$sheetAllCount = $spreadsheet->getSheetCount(); // 工作表總數(shù)
for ($index = 0; $index < $sheetAllCount; $index++) {   //工作表標(biāo)題
    $title[] = $spreadsheet->getSheet($index)->getTitle();
}
//讀取第一個工作表
$whatTable = 0;
$sheet = $spreadsheet->getSheet($whatTable);
$highest_row = $sheet->getHighestRow(); // 取得總行數(shù)
$highest_column = $sheet->getHighestColumn(); ///取得列數(shù)  字母abc...
$highestColumnIndex = Coordinate::columnIndexFromString($highest_column);  //轉(zhuǎn)化為數(shù)字;
for ($i = 1; $i <= $highestColumnIndex; $i++) {
    for ($j = 1; $j <= $highest_row; $j++) {
        $conent = $sheet->getCellByColumnAndRow($i, $j)->getCalculatedValue();
        $info[$j][$i] = $conent;
    }
}
var_dump($info);

參考:https://phpspreadsheet.readth...

以上就是php使用phpoffice/phpspreadsheet拓展操作excel實(shí)例的詳細(xì)內(nèi)容,更多關(guān)于phpoffice/phpspreadsheet操作excel的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

临江市| 施甸县| 高淳县| 西安市| 河曲县| 怀来县| 都匀市| 宜都市| 土默特右旗| 江华| 远安县| 南昌市| 岐山县| 当涂县| 安龙县| 阿瓦提县| 翁牛特旗| 胶南市| 江安县| 旅游| 唐河县| 将乐县| 博罗县| 许昌市| 关岭| 石泉县| 巧家县| 新河县| 东海县| 惠来县| 塘沽区| 保德县| 龙南县| 双峰县| 栾城县| 霍邱县| 息烽县| 武城县| 南木林县| 宁晋县| 余江县|