PHP基础-如何生成Excel文件

需要操作Excel,必须下载PHPExcel这个类,可以从官网PHPExcelhttps://github.com/PHPOffice/PHPExcel);

其中Documentation文件夹为类文档,Example为测试用例,Classes文件夹是真正用到的类,将Classes文件夹整个复制到程序目录下;

<?php
/**
 * Created by PhpStorm.
 */

echo "<span>虾米大王使用PHPExcel生成Excel文档</span>";
echo "<br>";
error_reporting(E_ALL);
require_once ('Classes/PHPExcel.php');  //引用PHPExcel

$obj_phpexcel = new PHPExcel();  //创建类实例
$obj_phpexcel->setActiveSheetIndex(0);  //设置当前页
$obj_phpexcel->getActiveSheet()->mergeCells('A1:D2'); //合并单元格
$obj_phpexcel->getActiveSheet()->getStyle('A1:D2')->applyFromArray(
    array(
        'font'=>array('bold'=>true),
        'alignment'=>array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER),
        'borders'=>array('top'=>array('style'=>PHPExcel_Style_Border::BORDER_THIN)),
        'fill'=>array('type'=>PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,'rotation'=>90,
            'startcolor'=>array('rgb'=>'DCDCDC'),'endcolor'=>array('rgb'=>'FFFFFF'))
        )
);  //对合并的单元格,设置格式,应用array方式,font为字体加粗,alignment为对齐方式(居中),borders为边框,fill为填充方式

$obj_phpexcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(12);  //设置合并单元格的字体大小
$obj_phpexcel->getActiveSheet()->setCellValue('A1','虾米大王创建的PHPEXCELL测试'); //对合并的单元格填充文字
$obj_phpexcel->getActiveSheet()->getStyle('A1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_BLUE); //设置字体颜色
$obj_phpexcel->getActiveSheet()->getStyle('A3:D3')->applyFromArray(
    array('fill'=>array('type'=>PHPExcel_Style_Fill::FILL_SOLID,'color'=>array('rgb'=>'D1EEEE')),)
); //对第三行设置fill格式,和单元格颜色

$obj_phpexcel->getActiveSheet()->setCellValue('A3','test1'); //对第三行1列,填充文字
$obj_phpexcel->getActiveSheet()->setCellValue('B3','test2');
$obj_phpexcel->getActiveSheet()->setCellValue('C3','test3');
$obj_phpexcel->getActiveSheet()->setCellValue('D3','test4');
$obj_phpexcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); //列宽度改为自动宽度
$obj_phpexcel->setActiveSheetIndex(0); //设置当前活动页

$obj_writer = PHPExcel_IOFactory::createWriter($obj_phpexcel,'Excel2007'); //生成文件
$obj_writer->save('shrimpking2007.xlsx'); //保存文件
$obj_writer = PHPExcel_IOFactory::createWriter($obj_phpexcel,'Excel5');
$obj_writer->save('shrimpking5.xls');

系统中至少要安装office 2007以上的版本。

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:C马雯娟 返回首页