导出Excel文件时调整列宽

时间:2015-10-07 10:01:56

标签: php excel laravel

我正在尝试使用以下代码将数据从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");

问题是如何为列提供自动宽度?

1 个答案:

答案 0 :(得分:1)

您不需要庞大的库来导出excel。您只需在html文件中使用正确的meta即可构建几乎正版 excel文件。

您必须在标题中包含以下内容:

<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
    <meta charset="UTF-8">
<!--[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]-->
...

我实际使用的完整代码是在下面。根据它在那里写的内容,很可能这段代码不适用于早期版本的MS Office。请注意,这是一个Blade视图。

&#13;
&#13;
<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
    <meta charset="UTF-8">
    <!--[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>
    @if(!empty($thead))
        <thead>
        {!! $thead !!}
        </thead>
    @endif
    @if(!empty($tbody))
        <tbody>
        {!! $tbody !!}
        </tbody>
    @endif
    @if(!empty($tfoot))
        <tfoot>
        {!! $tfoot !!}
        </tfoot>
    @endif
</table>
</body>
</html>
&#13;
&#13;
&#13;

这里的技巧是你可以利用各种功能,如列和行合并(使用colspanrowspan)等等(它使用对齐类,如{{1 }和text-center)。

您可以使用控制器中的代码强制下载文件,如下所示:

text-right

希望有所帮助。

相关问题