刚接触 Laravel 的时候,当初自己负责订单部分,经常核对数据,数据不可能每次都从数据库给财务的小姑娘导出,就做了导出到 Excel 表这么一个小功能,今天分享给大家。

Excel

总之就是把数据库表里面的数据导出到 excel 表。

安装 Excel 插件

本文结合 laravel 项目介绍 Excel 插件的基本使用,所以使用 Composer 来安装,而且 Excel 插件官网也推荐使用 Composer 来安装。

composer require "maatwebsite/Excel:~2.1.0"

在 app/config/app.php 的 providers 里面添加

 Maatwebsite\Excel\ExcelServiceProvider::class,

在 app/config/app.php 的 aliases 里面添加

'Excel' => Maatwebsite\Excel\Facades\Excel::class,

如果是 Laravel 5 以上,执行下面的命令,会有一个 Excel.php 添加到config 里面

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

使用 Excel 插件

Excel::create($filename, function($Excel) use($order) {
    $Excel->sheet('Sheetname', function($sheet) use($order) {
        $sheet->loadView('Excel.courseTJsumToExcel',array('order'=>$order));
    });
})->export('xls');

courseTJsumToExcel.blade.php

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<table>
    <thead>
        <tr>
            <th>课程名程</th>
            <th>课程ID</th>
            <th>支付订单</th>
            <th>支付金额</th>
            <th>PV</th>
            <th>UV</th>
        </tr>
    </thead>
    <tbody>
        @if($order)
            @foreach ($order as $detail)
                <tr>
            <td>{{$detail->course_title}}</td>
                    <td>{{$detail->courses_id}}</td>
                    <td>{{$detail->qnum? $detail->qnum : 0}}</td>
                    <td>{{$detail->qmoney ? $detail->qmoney : 0}}</td>
                    <td>{{$detail->pv ? $detail->pv : 0}}</td>
                    <td>{{$detail->uv ? $detail->uv : 0}}</td>
                </tr>
            @endforeach
      @endif
    </tbody>
</table>
</html>

1.$order 是我拿到的订单信息。

2.courseTJsumToExcel.blade.php 里面定义你要输出的内容。

参考文档

1.https://github.com/Maatwebsite/Laravel-Excel

Copyright © coding01 2017 all right reserved,powered by Gitbook该文件修订时间: 2018-06-17 22:20:20

results matching ""

    No results matching ""