dse3168 2013-06-25 07:21
浏览 39

使用PHP中的Link \ Button将Mysql数据导出到MS Excel中

I am a newbie to PHP and need help in exporting a selected content from Mysql Table to MS Excel using PHP. I need this done by a click of a button or a link.

Below is a piece of code I have done so far but I am consistently getting a warning as "Cannot modify header information - headers already sent". Also suggest a good way to export table on a click of a button\link. Thanks

//Export Contents

$header = '';

$data = '';

$fields = mysql_num_fields($sql);

//fetch header

for($i=0; $i < $fields; $i++)
{

    $header .= mysql_field_name($sql, $i)."\t";
}

//fetch data each row, store on tabular row data

while($row = mysql_fetch_row($sql))
{

    $line = '';
    foreach($row as $value)
    {
        if(!isset($value) || $value == "")
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace('"', '""', $value);
            $value = '"'.$value.'"'."\t";
        }

        $line .= $value;
    }

    $data .= trim($line)."
";
    $data = str_replace("", "", $data);
}

//Naming the excel sheet

$name = $customerFilter."_".date('d-m-y').".xls";

header("Content-type:application/vnd.ms-excel;name='excel'");

header("Content-Disposition: attachment; filename=$name");

header("Pragma: no-cache");

header("Expires: 0");

//Output Data

echo $header."

".$data;
  • 写回答

2条回答 默认 最新

  • douti9253 2013-06-25 07:35
    关注

    if you got a "headers already sent" you have some output (whitespaces) before sending your excel headers. Please enshure that the <?php tag is the very first in your file.

    Please read this thread: How to fix "Headers already sent" error in PHP

    You should use a library like this http://phpexcel.codeplex.com/ to be able to output stable excel files.

    Here is a hello world example for phpexcel:

    http://phpexcel.codeplex.com/wikipage?title=Examples&referringTitle=Home

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度