php导出excel数据

现在很多php到导入导出,今天就讲讲最基本常见的php导出excel,下载保存到本地

 

首先创建excel的类,代码如下

<?php
/**
 * 生成Excel文件类
 *
 * @package    library* www.33hao.com 专业团队 提供售后服务
 */
//defined('InShopNC') or exit('Access Invalid!');
class Excel{
    /**
    * excel文档头(返回的行)
    *
    * 依照excel xml规范。
    * @access private
    * @var string
    */
    private $header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?\>
    <Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"
    xmlns:x=\"urn:schemas-microsoft-com:office:excel\"
    xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"
    xmlns:html=\"http://www.w3.org/TR/REC-html40\">";

    /**
    * excel页脚
    * 依照excel xml规范。
    *
    * @access private
    * @var string
    */
    private $footer = "</Workbook>";
    
    /**
    * 文档行(行数组中)
    *
    * @access private
    * @var array
    */
    private $lines = array ();
    /**
    * 工作表(数组)
    *
    * @access private
    * @var array
    */
    private $worksheets = array ();
    /**
    * 单元格样式
    * @access private
    * @var string
    */
    private $cellstyle = array();
    
    /**
    * 默认单元格数据格式
    * @access private
    * @var string
    */
    private $default_cellformat = "String";
    
    public function __construct(){
        //设置默认样式
        $this->cellstyle['Default'] = '<Style ss:ID="Default" ss:Name="Normal">
               <Alignment ss:Vertical="Center"/>
               <Borders/>
               <Font ss:FontName="宋体" x:CharSet="134" ss:Size="11" ss:Color="#000000"/>
               <Interior/>
               <NumberFormat/>
               <Protection/>
              </Style>';
    }
    /**
    * 添加单行数据
    *
    * @access private
    * @param array 1维数组
    * @todo 行创建
    */
    private function addRow ($array)
    {
        //初始化单元格
        $cells = "";
        //构建单元格
        foreach ($array as $k => $v){
            $style_str = '';
            if(!empty($v['styleid'])){
                $style_str = 'ss:StyleID="'.$v['styleid'].'"';
            }
            $format_str = $this->default_cellformat;
            if(!empty($v['format'])){
                $format_str = $v['format'];
            }
            $cells .= "<Cell {$style_str} ><Data ss:Type=\"{$format_str}\">{$v['data']}</Data></Cell>\n";
        }
        //构建行数据
        $this->lines[] = "<Row>\n" . $cells . "</Row>\n";            
    }
    /**
    * 添加多行数据
    * @access public
    * @param array 2维数组
    * @todo 构造多行
    */
    public function addArray ($array)
    {
        $this->lines = array();
        //构建行数据
        foreach ((array)$array as $k => $v){
            $this->addRow ($v);
        }
    }
    /**
    * 添加工作表
    * @access public
    * @param string $sheettitle 工作表名
    * @todo 构造工作表XML
    */
    public function addWorksheet($sheettitle)
    {
        //剔除特殊字符
        $sheettitle = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $sheettitle);
        //现在,将其减少到允许的长度
        //$sheettitle = substr ($sheettitle, 0, 50);
        $this->worksheets[] = "\n<Worksheet ss:Name=\"$sheettitle\">\n<Table ss:DefaultRowHeight=\"20\">\n".
                              "<Column ss:Index=\"1\" ss:AutoFitWidth=\"0\"/>\n".
                              implode ("\n", $this->lines).
                              "</Table>\n</Worksheet>\n";
    }
    /**
    * 设置单元格样式
    * 
    * @access public
    * @param array 样式数组例如: array('id'=>'s_title','Font'=>array('FontName'=>'宋体','Size'=>'12','Bold'=>'1'));
    * 当id为Default时,为表格的默认样式
    */
    public function setStyle ($style_arr){
        if(empty($style_arr)){
            return false;
        }
        $id = $style_arr['id'];
        unset($style_arr['id']);
        $style_str = "<Style ss:ID=\"$id\">";
        foreach($style_arr as $k=>$v){
            $tmp = '';
            foreach((array)$v as $k_item=>$v_item){
                $tmp .= (" ss:$k_item=\"$v_item\"");
            }
            $style_str .= "<$k ".$tmp.'/>';
        }
        
        $this->cellstyle[$id] = $style_str.'</Style>';
    }
    /**
    * 设置默认单元格格式
    * 
    * @access public
    * @param string
    */
    public function setDefaultFormat ($format_str){
        if(empty($style_arr)){
            return false;
        }
        $this->default_cellformat = $format_str;
    }
    /**
    * 生成excel文件
    * 最后生成excel文件,并使用header()函数来将它交付给浏览器。
    * @access public
    * @param string $filename 文件名称
    */
    public function generateXML ($filename)
    {
        $encoded_filename = urlencode($filename);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);
        //头
        $ua = $_SERVER["HTTP_USER_AGENT"];
        header("Content-Type: application/vnd.ms-excel");
        if(preg_match("/MSIE/", $ua)){
            header('Content-Disposition: attachment; filename="'.$encoded_filename.'.xls"');
        }else if(preg_match("/Firefox/", $ua)){
            header('Content-Disposition: attachment; filename*="utf8\'\''.$filename.'.xls"');
        }else{
            header('Content-Disposition: attachment; filename="'.$filename.'.xls"');
        }
        header('Cache-Control: max-age=0');
        echo stripslashes ($this->header);
        //样式
        echo "\n<Styles>";
        foreach((array)$this->cellstyle as $k=>$v){
            echo "\n".$v;
        }
        echo "\n</Styles>";
        //工作表
        echo implode ("\n", $this->worksheets);
        echo $this->footer;
    }

    /**
     * 转码函数
     *
     * @param mixed $content
     * @param string $from
     * @param string $to
     * @return mixed
     */
    public function charset($content, $from='gbk', $to='utf-8') {
        $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
        $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
        if (strtoupper($from) === strtoupper($to) || empty($content)) {
            //如果编码相同则不转换
            return $content;
        }
        if (function_exists('mb_convert_encoding')) {
             if (is_array($content)){
                $content = var_export($content, true);
                $content = mb_convert_encoding($content, $to, $from);
                eval("\$content = $content;");return $content;
            }else {
                return mb_convert_encoding($content, $to, $from);
            }
        } elseif (function_exists('iconv')) {
             if (is_array($content)){
                $content = var_export($content, true);
                $content = iconv($from, $to, $content);
                eval("\$content = $content;");return $content;
            }else {
                return iconv($from,$to,$content);
            }
        } else {
            return $content;
        }
    }
}
?>

 

继续创建php文件,import.php

 

<?php 
//Language::read('export');
date_default_timezone_set('PRC');
include_once 'excel.php';//import('libraries.excel');


//print_r(date('Y-m-d H',time()));
//exit;
$excel_obj = new Excel();
$excel_data = array();
//设置样式
$excel_obj->setStyle(array('id'=>'s_title','Font'=>array('FontName'=>'宋体','Size'=>'12','Bold'=>'1')));
//header
$excel_data[0][] = array('styleid'=>'s_title','data'=>'品牌ID');
$excel_data[0][] = array('styleid'=>'s_title','data'=>'品牌');
$excel_data[0][] = array('styleid'=>'s_title','data'=>'品牌分类');
$excel_data[0][] = array('styleid'=>'s_title','data'=>'标识图');


//制造数组
$data = Array
(
    '0' => Array
        (
            'brand_id' => 364,
            'brand_name' => 'BH (必艾奇)',
            'brand_initial' => 'B',
            'brand_class' => '运动器械',
            'brand_pic' => '04420633630909218_small.jpg',
            'brand_sort' => 0,
            'brand_recommend' => 1,
            'store_id' => 4,
            'brand_apply' => 1,
            'class_id' => 665,
            'show_type' => 0
        ),

    '1' => Array
        (
            'brand_id' => 360,
            'brand_name' => '周生生',
            'brand_initial' => 'Z',
            'brand_class' => '纯金K金饰品',
            'brand_pic' => '04420650201635924_sm.jpg',
            'brand_sort' => 0,
            'brand_recommend' => 0,
            'store_id' => 0,
            'brand_apply' => 1,
            'class_id' => 532,
            'show_type' => 0
        ),

    '2' => Array
        (
            'brand_id' => 359,
            'brand_name' => '周大福',
            'brand_initial' => 'Z',
            'brand_class' => '纯金K金饰品',
            'brand_pic' => '04420650490304114_sm.jpg',
            'brand_sort' => 0,
            'brand_recommend' => 0,
            'store_id' => 0,
            'brand_apply' => 1,
            'class_id' => 532,
            'show_type' => 0
        ),

    '3' => Array
        (
            'brand_id' => 358,
            'brand_name' => '金史密斯(KINGSMITH)',
            'brand_initial' => 'J',
            'brand_class' => '健身器械',
            'brand_pic' => '04420592440315393_small.gif',
            'brand_sort' => 0,
            'brand_recommend' => 1,
            'store_id' => 4,
            'brand_apply' => 1,
            'class_id' => 691,
            'show_type' => 0,
        ),

    '4' => Array
        (
            'brand_id' => 353,
            'brand_name' => '古今',
            'brand_initial' => 'G',
            'brand_class' => '内衣',
            'brand_pic' => '04431807497959652_sm.jpg',
            'brand_sort' => 0,
            'brand_recommend' => 0,
            'store_id' => 0,
            'brand_apply' => 1,
            'class_id' => 6,
            'show_type' => 0
        ),

    '5' => Array
        (
            'brand_id' => 352,
            'brand_name' => '婷美(TINGMEI)',
            'brand_initial' => 'T',
            'brand_class' => '内衣',
            'brand_pic' => '04431809546541815_sm.png',
            'brand_sort' => 0,
            'brand_recommend' => 0,
            'store_id' => 0,
            'brand_apply' => 1,
            'class_id' => 6,
            'show_type' => 0
        )
);

foreach ((array)$data as $k=>$v){
    $tmp = array();
    $tmp[] = array('data'=>$v['brand_id']);
    $tmp[] = array('data'=>$v['brand_name']);
    $tmp[] = array('data'=>$v['brand_class']);
    $tmp[] = array('data'=>$v['brand_pic']);
    $excel_data[] = $tmp;
}
$excel_data = $excel_obj->charset($excel_data,'UTF-8');
$excel_obj->addArray($excel_data);
$excel_obj->addWorksheet($excel_obj->charset('表格','UTF-8'));
$excel_obj->generateXML($excel_obj->charset('表格','UTF-8').'-'.date('Y-m-d H',time()));

?>

 

调试一下输入

 

 

多多学习一下,看看对你有帮助,如果还有更好的关注一下我,相互学习,共同前进。

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明雨星云

感谢,我会继续创作更优质作品

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值