我正在使用来自 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/