3

我正在使用来自 maatwebsite 的 Laravel Excel,但在将数据导出到 xls 文件时遇到问题。我有这个查询,但我不需要显示 xls 文件中的所有列,但我需要在下载文件之前选择所有这些列来执行操作。在我的选择中,我有 8 列,但在我的标题中,我只有 7 列要显示,但这不起作用,因为 8ª 列也出现了。

我的功能:

 public function toExcel($id) { $b = Budget::find($id);

$budget = Budget_Item::join('budgets', 'budget__items.id_budget', '=', 'budgets.id')
    ->join('items_sizes', 'budget__items.id_itemSize', '=', 'items_sizes.id')
    ->join('items', 'items_sizes.id_item', '=', 'items.id')
    ->join('material_types', 'items_sizes.id_materialType', '=', 'material_types.id')
    ->select('items.reference AS Referência', 'items.name AS Descrição', 'items_sizes.size AS Tamanho', 'material_types.material_type AS Material', 'budget__items.amount AS Quantidade', 'items_sizes.unit_price AS Val.Unitário', 'budget__items.price AS Val.Total', 'budget__items.purchasePrice')
    ->where('id_budget', '=', $id)
    ->get();

$budgetUpdate = [];
$budgetUpdate[] = ['Referência', 'Descrição', 'Tamanho', 'Material', 'Quantidade', 'Val.Unitário', 'Val.Total'];
foreach ($budget as $key)
{
  if ($key->purchasePrice > 0)
  {
    $key->unit_price = $key->purchasePrice;
  }

  $budgetUpdated[] = $key->toArray();
}
Excel::create('Proposta_'.$b->reference, function($excel) use($budgetUpdated)
{
  // Set the title
  $excel->setTitle('Proposta');

  $excel->sheet('Sheetname', function($sheet) use($budgetUpdated)
  {
    $sheet->fromArray($budgetUpdated, null, 'A1', false, true);
  });

})->download('xls');}

我该如何解决?

谢谢

4

3 回答 3

5

在 Laravel excel 3.1 文档上测试

在控制器上

public function exportAsCsv() 
{
    return Excel::download(new MyExport, 'invoices.xlsx');
}

在 MyExport 上,查看地图功能

 class MyExport implements FromCollection, WithHeadings, WithMapping{

    public function collection(){
           return MyTable:all();
    }

    // here you select the row that you want in the file
    public function map($row): array{
           $fields = [
              $row->myfield2,
              $row->myfield1,
         ];
        return fields;
    }
}

还要检查这个

于 2019-09-09T14:15:13.613 回答
2

对于它的价值,我遇到了类似的问题并且在修复方面没有找到太多,所以这是我的解决方案。
1.我在回调中查询数据库并获取我需要的所有数据。
2. 然后我检查集合并在每次迭代时创建一个新数组并分配一个值和标题。非常适合从模型中挑选列

Excel::create('User List Export', function($excel) {
        $excel->sheet('Users', function($sheet) {
            $email = yourModelGoesHere::all();
            foreach ($email as $key => $value) {
                $payload[] = array('email' => $value['email'], 'name' => $value['name']);
            }
            $sheet->fromArray($payload);
        });
    })->download('xls');
于 2017-06-14T20:07:16.697 回答
0

你可以试试这个方法。
$user_id = Auth::user()->id

Excel::create('User', function($excel) use ($user_id){ 
  $excel->sheet('Sheet', function($sheet) use($user_id){

     $user = User::where('user_id', $user_id)->select('name', 'email', 'role', 'address')->get();   
  });
})->export('xls');

return redirect('your route');
于 2017-09-21T18:05:23.923 回答