首页 > 解决方案 > 在laravel中将数据库表导出到EXCEL

问题描述

我正在使用 laravel5.6。我想将数据库表数据导出到 excel 文件中。这是我的控制器代码

    use Exporter;

    $business = Approvedemand::all();
    $values ='';
    foreach($business as $item)
    {
        $values.='<tr>
            <td>'.$item['id'].'</td>
            <td>'.$item['name'].'</td>
            </tr>';   
    }
    header('Content-type: application/excel');
    $filename = date('Y-m-d').'-approveList'.'.xls';
    header('Content-Disposition: attachment; filename='.$filename);

    $data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
    <head>
       <!--[if gte mso 9]>
       <xml>
         <x:ExcelWorkbook>
             <x:ExcelWorksheets>
               <x:ExcelWorksheet>
                  <x:Name>Sheet 1</x:Name>
                      <x:WorksheetOptions>
                          <x:Print>
                             <x:ValidPrinterInfo/>
                          </x:Print>
                      </x:WorksheetOptions>
               </x:ExcelWorksheet>
            </x:ExcelWorksheets>
        </x:ExcelWorkbook>
    </xml>
    <![endif]-->
</head>
<body>
   <table>
      <tr>
        <td>ID</td>
        <td>Name</td>
     </tr>'
    .$values.
  '</table>
 </body>
 </html>';

 echo $data;

当我运行它时,会下载 excel 文件,但它会在 excel 中显示 html 标签。我不确定这种方法是否正确。

标签: phpexcellaravelexport-to-excel

解决方案


当我运行这个时,excel文件..

我假设您的意思是使用网络路由调用控制器功能。就像是..

Route::get('/your/path', 'BusinessController@export')->name('export');

我想将数据库表数据导出到 excel 文件中。

您可以为此使用Maatwebsite/Excel 2.1.0

业务控制器

use App\Approvedemand;

public function export()
{
    $data = App\Approvedemand::all();

    return Excel::create('Approve Demand'), function($excel) use ($data) {
        $excel->sheet('Sheetname', function($sheet) use ($data)
        {
            $sheet->fromArray($data);
        });
    })->export('xls');
}

这只是一个基本的例子。您显然希望在此处包含一些验证。


推荐阅读