我试图通过使用此代码将数据从Mysql导出到excel文件:
$stories = Story::all();
$header = 'Name' . "\t" . 'Email' . "\t" . 'Title' . "\t" . 'Created At' . "\t" . 'Story';
$xsl = $header . "\n";
foreach ($stories as $story)
{
$row = '';
$row .= '"' . str_replace('"', '""', stripslashes($story->name )) . '"' . "\t";
$row .= '"' . str_replace('"', '""', stripslashes($story->email)) . '"' . "\t";
$row .= '"' . str_replace('"', '""', stripslashes($story->title)) . '"' . "\t";
$row .= '"' . str_replace('"', '""', stripslashes($story->created_at)) . '"' . "\t";
$row .= '"' . str_replace('"', '""', stripslashes($story->story)) . '"' . "\t";
$xsl .= trim($row) . "\n";
}
$xsl = str_replace("\\t", "", $xsl);
return Response::make($xsl)->header('Content-type', 'application/vnd.ms-excel')->header('Content-disposition', "attachment;filename=Stories [as of].xls");
问题是如何给列自动宽度?
最佳答案 您不需要一个巨大的库来导出excel.只需在html文件中使用适当的元数据即可构建几乎正版的excel文件.
您必须在标题中包含以下内容:
...
我实际使用的完整代码是在下面.根据它在那里写的内容,很可能这段代码不适用于早期版本的MS Office.请注意,这是一个Blade视图.
@if(!empty($thead))
{!! $thead !!}
@endif
@if(!empty($tbody))
{!! $tbody !!}
@endif
@if(!empty($tfoot))
{!! $tfoot !!}
@endif
这里的技巧是你可以利用各种功能,如列和行合并(使用colspan和rowspan)等等(它使用对齐类,如文本中心和文本右).
您可以使用控制器中的代码强制下载文件,如下所示:
$fileName = "export.xls";
$data = View::make('export.excel.table', [
'thead' => $thead,
'tbody' => $tbody,
'tfoot' => $tfoot,
]);
return Response::make($data, 200, [
'Content-type' => 'application/excel',
'Content-Type' => 'application/excel',
'Content-Disposition' => 'attachment; filename=' . $fileName
]);
希望有所帮助.