douwei1174 2016-07-04 07:00
浏览 59

使用PHP将数据导出到Excel文件中

My problem looks like this at the front side:

enter image description here

After choosing which of my users I want to export: enter image description here

I'm sending AJAX request containing their database ids to external file named exportUsers.php.

So this is how back end of my problem looks like:

When data arrive to exportUsers.php, I query the database and make array($data) like this, which I want to export into Excel file.

enter image description here

This is how i tried to trigger download:

function cleanData(&$str)
    {
        $str = preg_replace("/\t/", "\\t", $str);
        $str = preg_replace("/?
/", "\
", $str);
        if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
    }
$flag = false;
foreach($data as $row1) {
    if(!$flag) {
        // display field/column names as first row
        echo implode("\t", array_keys($row1)) . "
";
        $flag = true;
        }
    array_walk($row, __NAMESPACE__ . '\cleanData');
    echo implode("\t", array_values($row1)) . "
";
   }
$filename = "users_data" . date('Ymd') . ".xls";

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=\"$filename\"");

But this is all I see in Network tool of my browser: enter image description here But no download was triggered. Please help

  • 写回答

1条回答 默认 最新

  • douguxun6866 2016-07-04 07:08
    关注

    Try this

     session_start();
     include "connection.php";
    
    
    $sql= mysql_query("select * from table") or die(print "Failed Download :".mysql_error());
    $columns_total = mysql_num_fields($sql);
    // Get The Field Name
    
    for ($i = 0; $i < $columns_total; $i++) {
    $heading = mysql_field_name($sql, $i);
    $output .= '"'.$heading.'",';
    }
    $output .="
    ";
    
    // Get Records from the table
    
    while ($row = mysql_fetch_array($sql)) {
    for ($i = 0; $i < $columns_total; $i++) {
    $output .='"'.$row["$i"].'",';
    }
    $output .="
    ";
    }
    
    // Download the file
    
    $filename = "FileName.xls";
    header('Content-type: application/xls');
    header('Content-Disposition: attachment; filename='.$filename);
    
    echo $output;
    
    //jzend... 
    exit;
    
    
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器