在laravel中编辑excel模板并下载

576 阅读1分钟

需求:按照给定的excel模板,将从数据库查询出来的内容追加到模板中并导出。

1. excel操作

读取excel文件:

Excel::load(文件路径,closure)

读取指定工作表

$reader->sheet(表格号(从0开始数),closure)

编辑单元格内容

$sheet->cell(单元格编号(比如:E6),要填入的数据)

指定行前插入行

$sheet->insertNewRowBefore(开始行,插入行数)

把数组中的一个元素填入到excel一整行里

$sheet->appendRow(行数, 填入的数据, true);

导出文件

$excel->export('xlsx')

2. 实现

$path = storage_path('exports/file.xls');
 Excel::load($path, function ($reader) use ($data) {
  $reader->sheet(0, function ($sheet) use ($data, $total_invoice_amount, $total_num, $total_untax_amount, $total_amount, $invoice_verify, $supplier_address) {
  $sheet->cell('B2', $data['supplier_info']);
  $sheet->cell('D2', $data['supplier_info']);  
  $invoice_start = 5;
  foreach ($data['invoice'] as $item) {
   $sheet->insertNewRowBefore($invoice_start,1);
   $sheet->appendRow($invoice_start++, $item, true);
   }
  });    
 })->export('xlsx');

遇到的问题&解决方法

如果想要的excel操作上文没提及,可以找下这个文件: excel源码:vendor-naatwebsite-excel-src-Maatwebsite-Excel-Classes-LaravelExcelWorksheet.php

  • export('xls'),导出格式为xls的时候脚本报错,改为export('xlsx')即可