php - 在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 标签。我不确定这种方法是否正确。
解决方案
当我运行这个时,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');
}
这只是一个基本的例子。您显然希望在此处包含一些验证。
推荐阅读
- amazon-web-services - 当数据目录之一没有记录时,aws 胶水工作室内部连接会出错
- javascript - JavaScript:用户单击一次后如何禁用 JavaScript 中的多个按钮
- django - 我已经配置了我的 uwsgi.ini 文件,并且它与 nohup 一起工作正常。如何在启动时自动启动 uwsgi?
- python - ValueError:在用户代码中,同时在 R 中使用 keras 模型
- python - 从熊猫数据框中删除列数(以相同字母结尾)
- node.js - Cookie 在 HttpHeaders 中可用,但在应用程序中不可用
- postgresql - 具有可变长度参数列表的 Prisma $queryRaw
- python - 如何在 pandas DataFrame 中搜索行条目?
- c# - ML.NET 模型生成器16.6.1
- javascript - 从字符串到 if 语句