PHP导出Excel实例讲解

yipeiwu_com5年前PHP代码库

本次实现PHP导出Excel文件使用的是PHP开源程序PHPExcel,部分关键代码分享给大家,具体内容如下

<?php
error_reporting(E_ALL);
date_default_timezone_set('Asia/Shanghai');
require_once './Classes/PHPExcel.php';
$data=array(
  0=>array(
    'id'=>1001,

    'username'=>'张飞',
    'password'=>'123456',
    'address'=>'三国时高老庄250巷101室'
  ),
  1=>array(
    'id'=>1002,
    'username'=>'关羽',
    'password'=>'123456',
    'address'=>'三国时花果山'
  ),
  2=>array(
    'id'=>1003,
    'username'=>'曹操',
    'password'=>'123456',
    'address'=>'延安西路2055弄3号'
  ),
  3=>array(
    'id'=>1004,
    'username'=>'刘备',
    'password'=>'654321',
    'address'=>'愚园路188号3309室'
  )
);
$objPHPExcel=new PHPExcel();
$objPHPExcel->getProperties()->setCreator('//www.jb51.net')
               ->setLastModifiedBy('//www.jb51.net')
               ->setTitle('Office 2007 XLSX Document')
               ->setSubject('Office 2007 XLSX Document')
               ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
               ->setKeywords('office 2007 openxml php')

               ->setCategory('Result file');

$objPHPExcel->setActiveSheetIndex(0)

      ->setCellValue('A1','ID')

      ->setCellValue('B1','用户名')

      ->setCellValue('C1','密码')

      ->setCellValue('D1','地址');

$i=2;     

foreach($data as $k=>$v){

  $objPHPExcel->setActiveSheetIndex(0)
      ->setCellValue('A'.$i,$v['id'])
      ->setCellValue('B'.$i,$v['username'])
      ->setCellValue('C'.$i,$v['password'])
      ->setCellValue('D'.$i,$v['address']);

  $i++;

}
$objPHPExcel->getActiveSheet()->setTitle('三年级2班');

$objPHPExcel->setActiveSheetIndex(0);
$filename=urlencode('学生信息统计表').'_'.date('Y-m-dHis');
 
//生成xlsx文件
/*
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
*/

//生成xls文件
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;

注意:如果导出中文时出现乱码,可以尝试将字符串转换成gb2312,代码类似如下:

查看代码打印

$str=mb_convert_encoding("gb2312","UTF-8",$str);

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

相关文章

PHP GD库相关图像生成和处理函数小结

本文总结了PHP GD库相关图像生成和处理函数。分享给大家供大家参考,具体如下: 这几天在学习图像验证码部分,参考了许多例子,都是用GD库来生成和绘制图像的,所以打算把GD库封装成类来使...

php树型类实例

本文实例讲述了php树型类。分享给大家供大家参考。具体分析如下: 该实例原理简单,学过数据结构的一看就明白是什么道理了,不过今天在使用时数据中出现了子节点id(71)小于父节点id(10...

php生成百度sitemap站点地图类函数实例

本文实例讲述了php生成百度sitemap站点地图类函数的方法,分享给大家供大家参考。具体实现方法如下: 问题概述: 公司网站是问答百科的网站、seo工程师提出需求说根据网站的问题来生成...

redis 队列操作的例子(php)

入队操作 复制代码 代码如下: <?php $redis = new Redis(); $redis->connect('127.0.0.1',6379); while(Tr...

php5.6.x到php7.0.x特性小结

本文总结分析了php5.6.x到php7.0.x特性。分享给大家供大家参考,具体如下: php5.6.x到php7.0.x特性 1.标量类型声明 字符串(string), 整数 (int...