首页 > 编程语言 >PHP用PhpOffice->PhpSpreadsheet导出excel

PHP用PhpOffice->PhpSpreadsheet导出excel

时间:2023-05-23 15:44:18浏览次数:30  
标签:sheet header column filename PhpSpreadsheet PhpOffice PHP row

phpexcel由于版本陈旧性能低下官方放弃维护
转而开发PhpSpreadsheet 用了最新得psr标准因而 对php版本不向下兼容需要注意!。

PhpSpreadsheet是一个用纯PHP编写的库,提供了一组类,使您可以读取和写入不同的电子表格文件格式
PhpSpreadsheet提供了丰富的API接口,可以设置诸多单元格以及文档属性,包括样式、图片、日期、函数等等诸多应用,总之你想要什么样的Excel表格,PhpSpreadsheet都能做到

使用 PhpSpreadsheet 开发的PHP要求 7.1或更高版本
PhpSpreadsheet 支持链式操作

安装:

composer require phpoffice/phpspreadsheet

工具类:

class ExcelUtil extends Model {
      private  $cellName = [
          'A',
          'B',
          'C',
          'D',
          'E',
          'F',
          'G',
          'H',
          'I',
          'J',
          'K',
          'L',
          'M',
          'N',
          'O',
          'P',
          'Q',
          'R',
          'S',
          'T',
          'U',
          'V',
          'W',
          'X',
          'Y',
          'Z',
          'AA',
          'AB',
          'AC',
          'AD',
          'AE',
          'AF',
          'AG',
          'AH',
          'AI',
          'AJ',
          'AK',
          'AL',
          'AM',
          'AN',
          'AO',
          'AP',
          'AQ',
          'AR',
          'AS',
          'AT',
          'AU',
          'AV',
          'AW',
          'AX',
          'AY',
          'AZ'
      ];

      public static function export($data, $title, $filename, $fields=[]) {

              // Create new Spreadsheet object
              $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
              $sheet = $spreadsheet->getActiveSheet();

              //设置表头单元格内容
              foreach ($title as $key => $value) {
                  $column = $this->cellName[$key].'1';
                  // 单元格内容写入
                  $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
                  //设置字体粗体
                  $spreadsheet->getActiveSheet()->getStyle($column)->getFont()->setBold(true);
              }

            //设置表格数据,从第二行开始
              $row = 2;
              foreach ($data as $item) {
                  $column = 1;
                  if($fields) {
                      foreach ($fields as $field) {
                          // 单元格内容写入
                          $sheet->setCellValueByColumnAndRow($column, $row, $item[$field]);
                          $column++;
                      }
                      $row++;
                      continue;
                  }else{
                foreach ($item as $value) {
                            // 单元格内容写入
                            $sheet->setCellValueByColumnAndRow($column, $row, $value);
                            $column++;
                      }
                      $row++;
            }
              }

              // Redirect output to a client’s web browser (Xlsx)
              header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
              header('Content-Disposition:attachment;filename="' . $filename . '.xls"');
              header('Cache-Control: max-age=0');
              // If you're serving to IE 9, then the following may be needed
              header('Cache-Control: max-age=1');

              // If you're serving to IE over SSL, then the following may be needed
              header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
              header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
              header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
              header('Pragma: public'); // HTTP/1.0

              $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
              $writer->save('php://output');
              exit;
      }
}

  

调用工具类导出excel:

$list = [
      [1, 11.00, '2023-05-23'],
      [2, 22.00, '2023-05-23']
];
$filename = '充值明细(' . date("Y-m-d", time()) . ')';
$header = array('ID', '金额', '支付时间');
ExcelUtil::export($list, $header, $filename);

  

 

标签:sheet,header,column,filename,PhpSpreadsheet,PhpOffice,PHP,row
From: https://www.cnblogs.com/yangyixin/p/17425433.html

相关文章

  • 一个简单的应用MVC思想的php程序
    <?php//controller.php控制器程序require_once("model.class.php");$type=isset($_GET['type'])?$_GET['type']:3;$modelObj=newDateTime2();switch($type){case1:$str=$modelObj->getD......
  • 【PHP兴趣部落-05】html table(表格)
    一、简介:表格由<table>标签来定义。每个表格均有若干行(由<tr>标签定义),每行被分割为若干单元格(由<td>标签定义)。字母td指表格数据(tabledata),即数据单元格的内容。数据单元格可以包含文本、图片、列表、段落、表单、水平线、表格等等。二、代码<!DOCTYPEhtml><html......
  • 【PHP兴趣部落-09】递归转义
    一、定义addslashes()函数返回在预定义字符之前添加反斜杠的字符串。预定义字符是:单引号(’)双引号(”)反斜杠(\)NULL注释:默认地,PHP对所有的GET、POST和COOKIE数据自动运行addslashes()。所以您不应对已转义过的字符串使用addslashes(),因为这样会导致双层转义。遇到这种情况时可......
  • 【PHP兴趣部落-08】PHP中时区设置的三种方法(timezone)
    一、三种方法php中时区默认是格林尼治时间,和中国时差八个小时。现在根据需要将时间设置为中国时间,下面整理了三种方法。方法1:最好的方法在php.ini里加上找到date.timezone项,设置date.timezone=“Asia/Shanghai”,重启环境就ok了。方法2:在需要用到这些时间函数的时候,在页面添......
  • 【PHP兴趣部落-04】html 表单中常用元素
    一、简介html表单中常用的一些元素:比如按钮,输入框、单选框、复选框等控件元素。表单标签:<form>元素标签:<inputtype=”类型”name=”控件名”value=”值”>三、代码<html><head><title>html基本元素学习</title></head><!--表单--><formaction="ok.html"met......
  • PhpStorm-中文汉化版设置教程
    原文地址:https://www.ngxcode.com/archives/607.html前言相信不少开发PHP的同学,对PhpStorm编辑器都不陌生,PhpStorm是JetBrains公司开发的一款商业的PHP集成开发工具,旨在提高用户效率,可深刻理解用户的编码,提供智能代码补全,快速导航以及即时错误检查。但PhpStorm默认是英文......
  • ctfshow php特性
    web111源代码highlight_file(__FILE__);error_reporting(0);include("flag.php");functiongetFlag(&$v1,&$v2){eval("$$v1=&$$v2;");//这里是一个赋值语句把v2的值复制下面通过get获得的$$v1值var_dump($$v1);//打印$$v1的值}if(isset($_......
  • php+phpstorm+xdebug配置
    简介原文链接:https://culturesun.site/index.php/archives/675.html因为博客是php的,所以无奈接触了php开发,虽然之前也学习过php语法。搞开发是离不开debug。最初从网上找到相关教程配置成功了,后来升级php,浏览器崩了搞的debug不行,再配置怎么也不成功,准确的来说,网上的辣鸡贴子太......
  • 宝塔面板中安装php8以上环境,提示: configure: error: iconv does not support errno
    问题:宝塔面板中安装php8编译时提示configure:error:iconvdoesnotsupporterrno#下面这些是配置yum源和epel源,阿里云ecs在centos8测试成功wgethttp://mirrors.cloud.aliyuncs.com/repo/Centos-vault-8.5.2111.repo-O/etc/yum.repos.d/Centos-vault-8.5.2111.repo&&......
  • php 操作数组 (合并,拆分,追加,查找,删除等)
    1.合并数组array_merge()函数将数组合并到一起,返回一个联合的数组。所得到的数组以第一个输入数组参数开始,按后面数组参数出现的顺序依次迫加。其形式为:Php代码1.arrayarray_merge(array这个函数将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组......