【问题标题】:Send an array to an Excel file using PHP使用 PHP 将数组发送到 Excel 文件
【发布时间】:2012-10-19 12:47:34
【问题描述】:

我想向 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;

【问题讨论】:

  • 这远非 .xls 文件。它只是一个带有逗号和制表符分隔字符串的文本文件。它甚至不是真正的 CSV 文件。我建议您要么使用真正的 Excel 编写器库,要么至少尝试理解 CSV 格式并将其表示为这样。
  • 根据我的经验,这并不像这样简单。您是否尝试过打开由 excel 创建的 xls?里面有很多很多的废话。尝试使用 Excel-Tool 或其他工具,或者..也许只是创建一个 .csv。 Excel 会很好地打开它,而且很容易用像你这样的代码来创建它。

标签: php mysql arrays excel


【解决方案1】:

尝试使用这个不错的插件:PHPExel 有了这个插件就很简单了

【讨论】:

    【解决方案2】:

    请尝试返回 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;
    ?>
    

    【讨论】:

      猜你喜欢
      • 2015-01-03
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 2016-09-04
      • 2020-05-09
      • 2016-10-14
      • 1970-01-01
      相关资源
      最近更新 更多