dousonghs58612 2013-06-20 03:56
浏览 34

问题将数据库查询结果导出到Excel

I need to export the results of a MySQL query to an Excel file. I picked up some code to achieve this, but there is one issue. The code sends the header information to the browser with the .xls content type and the query results following the headers. The code for the called page is as follows:

<?php
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/?
/", "\
", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}

// filename for download
$filename = "customer_inventory_" . date('Ymd') . ".xls";

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");

$flag = false;
$query = "SELECT customer_id,sku,qtyoh,date FROM sims_customer_inventory WHERE   customer_id=$customer_id and date=(select max(date) from sims_customer_inventory)";
$result = mysql_query($query, $conn) or die(mysql_error());
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
  // display field/column names as first row
  echo implode("\t", array_keys($row)) . "
";
  $flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "
";
?>

The problem is that when the page is called in this form:

<form action="inventory_download.php" method="get" onsubmit="return validateInventoryform();">

The file does not automatically download. However, when I refresh the page the file downloads. My problem is that when the page is called this should automatically execute the code to download the file. It does not do that. I have looked all over the internet to solve the problem, but I can't find out why it does not work.

  • 写回答

1条回答 默认 最新

  • duanjue7508 2013-07-06 05:03
    关注

    This problem is caused by the passing of ajax data to the external page that creates the .xls data. The answer is to turn off the ajax data in the link:

    <a href="something.php" data-ajax="false">
    

    That will allow the php code to work properly. There is still the problem that this is not actually a valid Excel file. This code creates a header and follows it with data that is interpreted as an Excel file. It is not an Excel file, but it does open in Excel and then it can be saved as an Excel file. That is an important distinction. If you are in need of an actual Excel file then PHPExcel is what you should use. That is probably the best option.

    评论

报告相同问题?

悬赏问题

  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法