导出Excel文件时调整列宽

我想通过使用下面的代码将数据从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文件中使用正确的meta构build几乎真正的 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。 请注意,这是一个刀片视图。

 <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>