欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用PHPExcel导出Excel表

程序员文章站 2023-02-16 13:47:04
本文实例为大家分享了phpexcel导出excel表的具体代码,供大家参考,具体内容如下 /** * excel导出 * @param $file...

本文实例为大家分享了phpexcel导出excel表的具体代码,供大家参考,具体内容如下

/**
   * excel导出
   * @param $filename(文件名)
   * @param $headarr (表头)
   * @param $data  (每一行的数据)
   * @throws \phpexcel_exception
   * @throws \phpexcel_reader_exception
   */
  function getexcel($filename,$headarr,$data){
    include_once (think_path."library/vendor/phpexcel/phpexcel.php");
    include_once (think_path."library/vendor/phpexcel/phpexcel/writer/excel2007.php");
    include_once (think_path."library/vendor/phpexcel/phpexcel/writer/excel5.php");
    include_once (think_path."library/vendor/phpexcel/phpexcel/iofactory.php");
    if(empty($data) || !is_array($data)){
      die("data must be a array");
    }
    if(empty($filename)){
      exit;
    }
    $date = date("y_m_d",time());
    $filename .= "_{$date}.xlsx";
 
    //创建新的phpexcel对象
    $objphpexcel = new \phpexcel();
    $objprops = $objphpexcel->getproperties();
 
    //设置表头
    $key = ord("a");
    $key2 = ord("a");
    $colum2 = '';
    $objactsheet = $objphpexcel->getactivesheet();
    $objphpexcel->getactivesheet()->getcolumndimension('a')->setwidth(25);
    foreach($headarr as $v){
      $colum = chr($key);
      $objphpexcel->setactivesheetindex(0) ->setcellvalue($colum2.$colum.'1', $v);
      if($key < 90){
        $key += 1;
      }else{
        $key = ord("a");
        $colum2 = chr($key2);
        $key2++;
      }
    }
    //exit;
    $column = 2;
 
    foreach($data as $key => $rows){ //行写入
      $span = ord("a");
      $span2 = ord("a");
      $j2 = '';
      foreach($rows as $keyname=>$value){// 列写入
        $j = chr($span);
        //$objactsheet->setcellvalue($j.$column, $value);
        //把每个单元格设置成分文本类型
        //dump($j2.$j.$column);
        $objactsheet->setcellvalueexplicit($j2.$j.$column,$value,\phpexcel_cell_datatype::type_string);
 
        if($span < 90){
          $span += 1;
        }else{
          $span = ord("a");
          $j2 = chr($span2);
          $span2++;
        }
      }
      $column++;
    }
    // exit;
    $filename = iconv("utf-8", "gb2312", $filename);
    //重命名表
    $objphpexcel->getactivesheet()->settitle('simple');
    //设置活动单指数到第一个表,所以excel打开这是第一个表
    $objphpexcel->setactivesheetindex(0);
    //将输出重定向到一个客户端web浏览器(excel2007)
    header('content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header("content-disposition: attachment; filename=\"$filename\"");
    header('cache-control: max-age=0');
    $objwriter = \phpexcel_iofactory::createwriter($objphpexcel, 'excel2007');
//    if(!empty($_get['excel'])){
//      $objwriter->save('php://output'); //文件通过浏览器下载
//    }else{
//      $objwriter->save($filename); //脚本方式运行,保存在当前目录
//    }
    $objwriter->save('php://output');
    exit;
 
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。