当前位置: 代码网 > it编程>编程语言>Php > php使用phpoffice/phpspreadsheet拓展操作excel实例

php使用phpoffice/phpspreadsheet拓展操作excel实例

2024年05月15日 Php 我要评论
一:安装phpoffice/phpspreadsheetcomposer require phpoffice/phpspreadsheet二:phpoffice/phpspreadsheet api接

一:安装phpoffice/phpspreadsheet

composer require phpoffice/phpspreadsheet

二:phpoffice/phpspreadsheet api接口详解

phpspreadsheet提供了丰富的api接口,可以设置诸多单元格以及文档属性,包括样式、图片、日期、函数等等诸多应用,总之你想要什么样的excel表格,phpspreadsheet都能做到

在使用phpoffice/phpspreadsheet的api接口前,确保引入了正确的文件并实例化

use phpoffice\phpspreadsheet\spreadsheet;//引入文件
$spreadsheet = new phpoffice\phpspreadsheet\spreadsheet();//创建一个新的excel文档
$sheet = $spreadsheet->getactivesheet();//获取当前操作sheet的对象

1:设置字体:

$sheet->getstyle('a7:b7')->getfont()->setbold(true)->setname('arial')
            ->setsize(10);//将a7至b7两单元格设置为粗体字,arial字体,10号字
$sheet->getstyle('b1')->getfont()->setbold(true);//将b1单元格设置为粗体字

2:设置颜色

$sheet->getstyle('a1')->getfont()->getcolor()->setargb(\phpoffice\phpspreadsheet\style\color::color_red);//将a1单元格文字颜色设为红色

3:设置列宽

$sheet->getcolumndimension('a')->setwidth(20);//将a列的宽度设为20(字符)
$sheet->getcolumndimension('b')->setautosize(true);//将b列的宽度设为自动宽度
$sheet->getdefaultcolumndimension()->setwidth(12);//设置默认列宽为12

4:设置行高

$sheet->getrowdimension('10')->setrowheight(100);//将第十行的高度设为100pt
$sheet->getdefaultrowdimension()->setrowheight(15);//设置默认行高为15

5 : 对齐

$sheet->getstyle('a:d')->getalignment()
            ->setvertical(\phpoffice\phpspreadsheet\style\alignment::vertical_center) //设置垂直居中
            ->sethorizontal(\phpoffice\phpspreadsheet\style\alignment::horizontal_center) //设置水平居中
            ->setwraptext(true); //设置自动换行

6:合并单元格

$sheet->mergecells('a1:d2');//a1到d2合并为一个单元格

7:将合并后的单元格拆分

$sheet->unmergecells('a1:d2');//将合并后的单元格拆分。

8:使用applyfromarray实现单元格样式设置

//样式变量
$style = [
//设置字体样式
'font' => [
        'name' => 'arial',
        'bold' => true,
        'italic' => false,
        'underline' => font::underline_double,
        'strikethrough' => false,
        'color' => [
            'rgb' => '808080'
        ]
    ],
//设置边框线样式
'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:设置工作表标题

$sheet->settitle('hello');;//设置当前工作表标题。

10:设置单元格的格式

$sheet->getstyle('d2')->getnumberformat()
            ->setformatcode(\phpoffice\phpspreadsheet\style\numberformat::format_text);//将d2单元格的格式设为文本格式
$sheet->getstyle('a1:d2')->getnumberformat()
            ->setformatcode(\phpoffice\phpspreadsheet\style\numberformat::format_text);//将a1到d2的单元格设置为文本格式

11 : 换行

$sheet->getcell('a4')->setvalue("hello\nworld");//将a4单元格的hello和world换行

12:超链接

//将a2单元格内容设置blog并点击跳转https://www.wj0511.com
$sheet->setcellvalue('a2', 'blog');
$sheet->getcell('a2')->gethyperlink()->seturl('https://www.wj0511.com');

13:使用函数

常用函数有:总和(sum),最大数(max),最小数(min),平均值(average)

$sheet->setcellvalue('b5', '=sum(b1:b4)');//将b5单元格的内容设为b1到b4的之和

14:设置文档属性

$spreadsheet->getproperties()
    ->setcreator("author")    //作者
    ->setlastmodifiedby("last-author") //最后修改者
    ->settitle("title")  //标题
    ->setsubject("subject") //副标题
    ->setdescription("description")  //描述
    ->setkeywords("keywords") //关键字
    ->setcategory("category"); //分类

三:简单实现生成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
{
    /**
     * 数字转字母 (类似于excel列标)
     * @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 = [
            '姓名',
            '性别',
            '学历',
            '年龄',
            '身高',
        ];
        //内容
        $data = [
            [
                '小明',
                '男',
                '专科',
                '18',
                '175'
            ],
            [
                '小红',
                '女',
                '本科',
                '18',
                '155'
            ],
            [
                '小蓝',
                '男',
                '专科',
                '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();//创建一个新的excel文档
        $sheet = $spreadsheet->getactivesheet();//获取当前操作sheet的对象
        $sheet->settitle('标题'); //设置标题
        $sheet->getstyle("{$firstcolum}:{$lastcolum}")->getalignment()
            ->setvertical(alignment::vertical_center) //设置垂直居中
            ->sethorizontal(alignment::horizontal_center) //设置水平居中
            ->setwraptext(true); //设置自动换行
        //设置宽度
        $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的单元格格式设为文本格式
        $sheet->getstyle("{$firstcolum}{$firstrow}:{$lastcolum}{$lastrow}")->getnumberformat()
            ->setformatcode(\phpoffice\phpspreadsheet\style\numberformat::format_text);
        //设置头信息样式
        $sheet->getrowdimension($row)->setrowheight(30);//设置行高
        $sheet->getstyle("{$firstcolum}{$row}:{$lastcolum}{$row}")->applyfromarray($headerstyle);
        //设置头信息
        foreach ($header as $key => $item) {
            $sheet->setcellvalue("{$column[$key]}{$row}", $item);
        }
        $row++;
        foreach ($data as $key => $model) {
            $sheet->getrowdimension($row)->setrowheight(30);//设置行高
            $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工作表标题
$info = [];//excel内容
$filename = "表格.xlsx";
$spreadsheet = iofactory::load($filename);
//$worksheet = $spreadsheet->getactivesheet();   //获取当前文件内容
$sheetallcount = $spreadsheet->getsheetcount(); // 工作表总数
for ($index = 0; $index < $sheetallcount; $index++) {   //工作表标题
    $title[] = $spreadsheet->getsheet($index)->gettitle();
}
//读取第一個工作表
$whattable = 0;
$sheet = $spreadsheet->getsheet($whattable);
$highest_row = $sheet->gethighestrow(); // 取得总行数
$highest_column = $sheet->gethighestcolumn(); ///取得列数  字母abc...
$highestcolumnindex = coordinate::columnindexfromstring($highest_column);  //转化为数字;
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实例的详细内容,更多关于phpoffice/phpspreadsheet操作excel的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com