基于PhpExcel封装的PHPOffice工具类,导出Excel文件

7 篇文章 0 订阅
1 篇文章 0 订阅

笔者使用的环境目前为Thinkphp5+PHP7.1

首先composer安装PHPExcel,

composer require phpoffice/phpexcel

注:phpexcel不再维护,推荐使用phpspreadsheet,

composer require phpoffice/phpspreadsheet

PhpOffice.php

class PhpOffice
{
    private $excel;
    private $writer;
    private $writer5;
    private $filename;
    static $rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',];

    public function __construct() {
        import('PHPExcel', CORE_PATH, '.php');
        $this->excel = new \PHPExcel();
        $this->setConfig();
        //Save Excel 2007 file 保存
        $this->writer = new \PHPExcel_Writer_Excel2007($this->excel);
        //Save Excel 5 file 保存
        $this->writer5 = new \PHPExcel_Writer_Excel5($this->excel); //设置保存版本格式

    }

    /**
     * @title 设置文件名称
     * @param string $filename
     * @return $this
     */
    public function setFileName($filename = '') {
        if ($filename) {
            $this->filename = $filename;
        } else {
            $this->filename = date('Y-m-d H:m:s');
        }
        return $this;
    }

    /**
     * @title 设置表单名称
     * @param $name
     * @return $this
     */
    public function setSheetName($name) {
        $this->excel->getActiveSheet()->setTitle($name);
        return $this;
    }

    /**
     * @title 设置列标题
     * @param $title
     * @param int $height
     * @param int $width
     * @return $this
     */
    public function setSheetTitle($title, $height = 20, $width = 15) {
        if (!is_array($title)) {
            $title = explode(',', $title);
        }
        //循环标题数组
        foreach ($title as $k => $value) {
            $this->excel->setActiveSheetIndex(0)->setCellValue(self::$rows[$k] . '1', $value);
            //设置列宽
            $this->excel->getActiveSheet()->getColumnDimension(self::$rows[$k])->setWidth($width);
            //设置字体
            $this->excel->getActiveSheet()->getStyle(self::$rows[$k] . '1')->getFont()->setSize(15);
        }
        //设置行高
        $this->excel->getActiveSheet()->getRowDimension(1)->setRowHeight($height);
        return $this;
    }

    /**
     * @title 设置宽度
     * @param array $column
     * @return $this
     */
    public function setWidth($column = []) {
        //设置列宽
        foreach ($column as $key => $val) {
            $this->excel->getActiveSheet()->getColumnDimension(strtoupper($key))->setWidth($val);
        }
        return $this;
    }

    /**
     * @title 填充数据
     * @param $data
     * @param int $start
     * @return $this
     */
    public function setData($data, $start = 2) {
        if (!is_array($data)) {
            $data = explode(',', $data);
        }
        foreach ($data as $k => $datum) {
            foreach ($datum as $i => $item) {
                $this->excel->setActiveSheetIndex(0)->setCellValue(self::$rows[$i] . $start, $item);
            }
            $start++;
        }
        return $this;
    }


    /**
     * @title 设置表格基本信息(选填)
     * @return \PHPExcel
     */
    public function setConfig() {
        $this->excel->getProperties()->setCreator('Pt')
            ->setLastModifiedBy('Pt')
            ->setTitle('xls')
            ->setSubject('')
            ->setDescription('')
            ->setKeywords('')
            ->setCategory('');
        $this->excel->getDefaultStyle()->getFont()->setSize(15);
        $this->setFileName();
        return $this->excel;
    }

    /**
     * @title 测试运行
     */
    public function test_run() {

        $spreadsheet = $this->excel;

        // Add some data
        $spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B1', 'world!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D1', 'world!');

        // Miscellaneous glyphs, UTF-8
        $spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A4', 'Miscellaneous glyphs')
            ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');

        // Rename worksheet

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $spreadsheet->setActiveSheetIndex(0);

        $this->downloadExcel();

    }

    /**
     * @title 导入数据
     * @param string $filepath
     * @return array
     */
    public function loadExcel($filepath = '') {
        $spreadsheet = \PHPExcel_IOFactory::load($filepath);
        $result = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        return $result;
    }


    /**
     * @title 输出下载文件
     */
    public function downloadExcel($type='xls') {

        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="'.$this->filename.'.xls"');
        header("Content-Transfer-Encoding:binary");
        if($type == 'xlsx'){
            $this->writer->save('php://output');
        }else{
            $this->writer5->save('php://output');
        }
        exit;
    }

}

使用用法

$objPhpExcel = new \PhpOffice();
//待导出数据
$data = [];
//表头
$data[] = ['序号','项目类型','项目名称','项目级别','主办单位','承办单位','协办单位','项目简介'];
foreach ($pro_arr as $k=>$v){
    //处理数据
    $data[] = [
        $k+1,
        getDicName($v['project_type']),
        $v['title'],
        getDicName($v['project_level']),
        $v['org_unit'],
        $v['co_unit'],
        $v['contract_unit'],
        $v['description']
    ];
}
$file_name = '信息表'.date('Ymd');
$set_width = ['A'=>5,'B'=>15,'C'=>50,'D'=>15,'E'=>20,'F'=>20,'G'=>20];
$objPhpExcel->setFileName($file_name);
$objPhpExcel->setWidth($set_width);
$objPhpExcel->setData($data,1);
$objPhpExcel->downloadExcel();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值