我在网上找到了以下函数,该函数应该获取一些mysql数据并将其下载为CSV / Excel。它有点工作,但它不是在用户的浏览器中触发文件下载,而是简单地将数据转储到响应流的末尾,并在所有其他页面内容之后显示在浏览器窗口的底部。我做错了什么?
重要提示:如果我从Excel内容类型更改为CSV,它没有任何区别,我得到相同的结果,虽然从技术上来说它创建了CSV内容而不是真正的Excel内容。
function DownloadQueryToCSV($sql, $filename){
$result = mysql_query($sql) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t"; //tabbed character
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
die(); // WARNING: Must die at end of function, else other page contents will end up in spreadsheet!!
}
版主:这与Excel无关,也不与mysql to excel formatting issues
重复答案 0 :(得分:0)
尝试使用此处列出的Excel内容类型:What is a correct mime type for docx, pptx etc?
<script>
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: true,
success: function(response){
$("#displayMessage").html(response);
$("#chatForm").trigger("reset");
}
});
return false;
});
});
$(document).ready(function(e){ $.ajaxSetup({cache:false});
setInterval(function(){$('#displayMessage').load('log.php');}, 3000);
});
</script>
如果还不够,请尝试添加(虽然我知道CSV是文本):
.xls application/vnd.ms-excel