首页 > 解决方案 > Laravel:如何将自定义刀片表下载为 excel

问题描述

我在 laravel 应用程序的刀片文件中有这张表:

<form method="POST" action="{{url('/download')}}" id="download_form">
  @csrf <!-- {{ csrf_field() }} -->
  <table class="table font-weight-bold w-100" id="excel_table">
    <thead class="table-primary">
      <tr>
        <th class="text-center">#</th>
        <th class="text-center">ناڤ</th>
        <th class="text-center">كوم</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="text-center">{{$counter}}</td>
        <td class="text-right table-primary">{{$student->name}}</td>
        <td class="text-center table-primary">{{$sub_total}}</td>
      </tr>
    </tbody>
  </table>
<div>
<input type="hidden" name="file_contente" id="file_contente">
<input type="hidden" value="{{$stage}}" name="stage" id="">
<input type="hidden" value="{{$group}}" name="group" id="">
<button type="submit" id="download" class="btn btn-success">Download to excel</button>
</div>
</form>
</div>
<script>
$(document).ready(function() {
  $('#download').click(function() {
    var table_content = '<table>';
    table_content += $('#excel_table').html();
    table_content+= '</table>';
    $('#file_content').val(table_content);
    $('#download_form').html();
  })
})
</script>

控制器是:

public function download(Request $req)
{
    $temporary_html_file = './tmp_html/' . time() . '.html';
    file_put_contents($temporary_html_file, $req->file_contente);
    $reader = IOFactory::createReader('Html');
    $spreadsheet = $reader->load($temporary_html_file);
    $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    $filename = $req->stage." ".$req->group . '.xlsx';
    $writer->save($filename);
    header('Content-Type: application/x-www-form-urlencoded');
    header('Content-Transfer-Encoding: Binary');
    header("Content-disposition: attachment; filename=\"".$filename."\"");
    readfile($filename);
    unlink($temporary_html_file);
    unlink($filename);
}

我得到错误:

file_put_contents(./tmp_html/1634558222.html):无法打开流:没有这样的文件或目录

我该如何解决?我做错了什么?

在公用文件夹中创建 temp_html 文件夹后进行编辑 ,我收到此错误:

./tmp_html/1634560521.html 是无效的 HTML 文件。

标签: excellaravellaravel-blade

解决方案


推荐阅读