>php教程 >PHP源码 >PHPEXCEL生成excel文件

PHPEXCEL生成excel文件

PHP中文网
PHP中文网원래의
2016-05-25 17:09:091150검색

支持任意行列数据生成excel文件

<?php
/**
 * PHPEXCEL生成excel文件
 * @author:firmy
 * @desc 支持任意行列数据生成excel文件,暂未添加单元格样式和对齐
 */
 
require_once &#39;library/PHPExcel.php&#39;;
require_once &#39;library/PHPExcel/Reader/Excel2007.php&#39;;
require_once &#39;library/PHPExcel/Reader/Excel5.php&#39;;
include_once &#39;library/PHPExcel/IOFactory.php&#39;;
 
$fileName = "test_excel";
$headArr = array("第一列","第二列","第三列");
$data = array(array(1,2),array(1,3),array(5,7));
getExcel($fileName,$headArr,$data);
 
 
function getExcel($fileName,$headArr,$data){
    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");
    foreach($headArr as $v){
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.&#39;1&#39;, $v);
        $key += 1;
    }
     
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach($data as $key => $rows){ //行写入
        $span = ord("A");
        foreach($rows as $keyName=>$value){// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j.$column, $value);
            $span++;
        }
        $column++;
    }
 
    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    $objPHPExcel->getActiveSheet()->setTitle(&#39;Simple&#39;);
    //设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    //将输出重定向到一个客户端web浏览器(Excel2007)
          header(&#39;Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&#39;);
          header("Content-Disposition: attachment; filename=\"$fileName\"");
          header(&#39;Cache-Control: max-age=0&#39;);
          $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, &#39;Excel2007&#39;);
          if(!empty($_GET[&#39;excel&#39;])){
            $objWriter->save(&#39;php://output&#39;); //文件通过浏览器下载
        }else{
          $objWriter->save($fileName); //脚本方式运行,保存在当前目录
        }
  exit;
 
}

                   


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.