使用PHP将数组发送到Excel文件

时间:2012-10-19 12:47:35

标签: php mysql arrays excel

我想将一个数组发送到Excel文件,这是一个包含不同类别的数组。

每个类别应分为一列。我写的代码是将所有值发送到Excel上的一个字段。我在哪里弄错了?

$shop['id']=$id_array;
    $shop['name']=$name_array;
    $shop['cat1'] = $cat1;
    $shop['cat2'] = $cat2;
    $shop['cat3'] = $cat3;


    $id_excel=implode(",",$shop['id']);
    $name_excel=implode(",",$shop['name']);
    $cat1_excel=implode(",",$shop['cat1']);
    $cat2_excel=implode(",",$shop['cat2']);
    $cat3_excel=implode(",",$shop['cat3']);

}
    $filename ="cat.xls";
    $contents = "$id_excel \t $name_excel \t $cat1_excel \t $cat2_excel \t $cat3_excel \t \n";
    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename='.$filename);
    echo $contents;

2 个答案:

答案 0 :(得分:1)

尝试使用这个漂亮的插件:PHPExel 使用这个插件很简单

答案 1 :(得分:0)

请尝试返回CSV文件而不是Excel。这是代码:

<? $shop['id']=$id_array;
    $shop['name']=$name_array;
    $shop['cat1'] = $cat1;
    $shop['cat2'] = $cat2;
    $shop['cat3'] = $cat3;



    $id_excel[]=implode(",",$shop);

    $filename ="cat.csv";
    $contents = implode("\n",$id_excel);
    header('Content-type: text/csv');
    header('Content-Disposition: attachment; filename='.$filename);
    echo $contents;
?>