将数据保存到Excel

时间:2018-05-24 19:33:05

标签: php laravel laravel-5

我想将数据保存到Excel而不是PDF。请协助。

这是我的控制器:

{{1}}

1 个答案:

答案 0 :(得分:0)

您可以使用This Library。我给你举个例子。希望得到你的帮助。

public function getUsageData(Request $request){
    Excel::create('Export data', function($excel) {

    $excel->sheet('Sheet 1', function($sheet) {
        $start_date = $request->get('start_date');
        $end_date = $request->get('end_date');

        $particulars = DB::table('particulars')
            ->join('reqs', 'particulars.particular_id', "=", 'reqs.particular_id')
            ->whereBetween('date_applied', [$start_date, $end_date])
            ->select('particulars.item_name', 'particulars.unit', 'particulars.price', 'reqs.quantity_issued',
                DB::raw('particulars.price*reqs.quantity_issued AS total_cost'))
            ->get();

         foreach($particulars as $particular) {
             $data[] = array(
                $particular->some_field,
                $particular->some_another_field,
                // and so on ...                    
            );
        } // if you don't need id, ommite it. but make sure $particulars is an array

        $sheet->fromArray($data, null, 'A1', false, false);
        $headings = array('some_field', 'some_another_field');
        $sheet->prependRow(1, $headings); // it will create the first row of your Excel sheet as headings
    });
  })->export('xls');
}