Laravel从对象导出多个项目

时间:2015-10-12 13:07:28

标签: php laravel laravel-5

我尝试使用maatwebsite的Laravel Excel package将一个对象中的多个项目导出到Laravel 5.1中的CSV。

我使用的代码有效但只导出最后一条记录,而不是所有记录。

我的代码是:

return Excel::create('Voucher-Export-'.time(), function($excel) use($rows)
{
    $excel->setTitle('Voucher Export');
    $excel->sheet('Voucher Export', function($sheet) use($rows) {
        foreach($rows->items() as $row) {
            $sheet->fromArray($row->toArray());
        }
    });
})->store('xls', false, true);

$rows拥有这样的对象:

array:20 [▼
  0 => Coupon {#369 ▼
    #table: "coupons"
    #fillable: array:8 [▶]
    #connection: null
    #primaryKey: "id"
    #perPage: 15
    +incrementing: true
    +timestamps: true
    #attributes: array:12 [▶]
    #original: array:12 [▶]
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #guarded: array:1 [▶]
    #dates: []
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    #morphClass: null
    +exists: true
    +wasRecentlyCreated: false
  }
  1 => Coupon {#370 ▶}
  2 => Coupon {#371 ▶}
  3 => Coupon {#372 ▶}
  4 => Coupon {#373 ▶}
  5 => Coupon {#374 ▶}
  6 => Coupon {#375 ▶}
  7 => Coupon {#376 ▶}
  8 => Coupon {#377 ▶}
  9 => Coupon {#378 ▶}
  10 => Coupon {#379 ▶}
  11 => Coupon {#380 ▶}
  12 => Coupon {#381 ▶}
  13 => Coupon {#382 ▶}
  14 => Coupon {#383 ▶}
  15 => Coupon {#384 ▶}
  16 => Coupon {#385 ▶}
  17 => Coupon {#386 ▶}
  18 => Coupon {#387 ▶}
  19 => Coupon {#388 ▶}
]

但是,这会导致仅导出最后一行。有谁知道如何做到这一点?

1 个答案:

答案 0 :(得分:2)

我还没有使用过这个插件,但是从docs看来你传递的是一个行数组,而不是一个行数组。

我想你的代码失败了,因为$sheet->fromArray()创建了一个工作表而不是一行,所以只有最后一个$row被加载为工作表。

docs示例

Excel::create('Filename', function($excel) {
  $excel->sheet('Sheetname', function($sheet) {
    $sheet->fromArray(array(
      array('data1', 'data2'),
      array('data3', 'data4')
    ));
  });
})->export('xls');

您的新代码

return Excel::create('Voucher-Export-'.time(), function($excel) use($rows)
{
  $excel->setTitle('Voucher Export');
  $excel->sheet('Voucher Export', function($sheet) use($rows) {
    $sheet->fromArray($rows->toArray());
  });
})->store('xls', false, true);
相关问题