php 导出excel 设置列宽,php – 导出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文件中使用适当的元数据即可构建几乎正版的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

]);

希望有所帮助.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值