laravel-5 - Laravel Excel - 选择要导出的列

标签 laravel-5 maatwebsite-excel

我正在使用来自 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');}

我该如何解决?

谢谢

最佳答案

在 Laravel excel 3.1 上测试 docs

在 Controller 上

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

在 MyExport 上,查看 map 功能

 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;
    }
}

另请查看 this

关于laravel-5 - Laravel Excel - 选择要导出的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935559/

相关文章:

composer-php - Laravel 8 中损坏的 composer.json 文件

php - Laravel excel 导出 - 字符串格式的列显示为数字

php - 如何在代码Laravel中使用Artisan命令?

laravel - 使用 add 方法将值附加到 $request

javascript - Laravel Ajax 请求,Auth :login returns false! 但用户在刷新后登录

php - 使用 ORM 进行查询并在内部一起使用 (AND) 和 (OR)

laravel-5.5 - 如何用 phpoffice/phpspreadsheet 替换 phpoffice/phpexcel

php - laravel 5 迁移向我的数据库表添加了一些主键。如何预防呢?

laravel - 如何创建一个 excel 文件并在邮件中附加而不存储在本地磁盘中

excel - laravel excel 获取标题和 maatwebsite