Javascript 单击按钮后下载CSV文件
大家早上好, 我需要强制下载csv文件时,用户点击按钮导出csv,我看到很多页面在这里和谷歌,并尝试了很多事情,但任何东西都是为我工作。 我有一个带有这个按钮的主页,点击它会向另一个页面发送一个带有Javascript和ajax的POST请求,该页面创建了csv文件,并且理论上下载了该文件。 这是主页的代码:Javascript 单击按钮后下载CSV文件,javascript,php,jquery,csv,Javascript,Php,Jquery,Csv,大家早上好, 我需要强制下载csv文件时,用户点击按钮导出csv,我看到很多页面在这里和谷歌,并尝试了很多事情,但任何东西都是为我工作。 我有一个带有这个按钮的主页,点击它会向另一个页面发送一个带有Javascript和ajax的POST请求,该页面创建了csv文件,并且理论上下载了该文件。 这是主页的代码: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jque
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>
</head>
<?php
$filter="<button id='exportCSV' >Export CSV</button><br/></div>";
echo $filter
?>
<script>
$(function() {
$("#exportCSV").click(function(){
var query="select * from thcu_cabtemphpc order by timetag desc limit 300";
var table="thcu_cabtemphpc";
//alert(query+" "+table);
//alert(dataString);
$.ajax({
type: "POST",
url: "exportCSV.php",
data: {cvsExp: query, table:table},
success: function(result){
alert("Export in progress");
//$("#export").html(result);
}
});
});
});
</script>
</html>
当然,这只是一个测试,我有另一个主页,用户可以在其中选择查询和表。
这是ExportCSV.php的代码
<html>
<body>
<?php
include('connection.php');
function array2csv($bd, $query, $id){
$sql = mysql_query($query);
$day = gmdate("d-M-Y");
$offset = +2 * 3600; // timezone offset for UTC-13
$utcTime = gmdate( 'd.m.Y H:i:s' );
$milliseconds ="".round(microtime(true) * 1000);
$val= substr($milliseconds,8,10);
//echo $val;
$valor = gmdate( 'd-m-Y_H-i-s-'.$val, time() + $offset );
$name= $day."_".$id."data_export_".$valor.".csv";
$fp = fopen($name, 'w');
while ($res=mysql_fetch_row($sql)) {
$count = 0;
foreach ($res as $val) {
if ($count == 0){
$data = gmdate("Y-m-d H:i:s", substr(($val/10000000) - 12219292800, 0,10));
$arr[$count] = $data;
$count++;
} else {
$arr[$count] = $val;
}
}
$delimiter=",";
fputcsv($fp,$arr,$delimiter);
}
//fpassthru($fp);
fclose($fp);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $name . '.csv"');
header('Content-Length: ' . filesize($name));
echo readfile($name);
}
if(isset($_POST["cvsExp"])) {
$query=$_POST["cvsExp"];
$id=$_POST["table"];
//download_send_headers("data_export_".gmdate("Y-m-d").".csv");
array2csv($bd,$query,$id);
die();
}
?></body>
</html>
我尝试这样的代码,但不起作用,我尝试将application/octet替换为text/csv,我尝试插入echo readfile$name或只插入readfile$name,但任何操作都可以。这样做的结果是在webroot中创建一个文件,这不好,我希望浏览器下载该文件。
非常感谢
编辑:我尝试只使用下载脚本执行页面,并且它是工作的,问题是当我使用ajax调用它时!!!这怎么可能?错误在哪里?我没有检查您的内部代码,但CSV肯定不能以标记开头!您只需回复CSV内容,删除所有标记,但不包括 例如:
<?php
include('connection.php');
function array2csv($bd, $query, $id){
$sql = mysql_query($query);
$day = gmdate("d-M-Y");
$offset = +2 * 3600; // timezone offset for UTC-13
$utcTime = gmdate( 'd.m.Y H:i:s' );
$milliseconds ="".round(microtime(true) * 1000);
$val= substr($milliseconds,8,10);
//echo $val;
$valor = gmdate( 'd-m-Y_H-i-s-'.$val, time() + $offset );
$name= $day."_".$id."data_export_".$valor.".csv";
$fp = fopen($name, 'w');
while ($res=mysql_fetch_row($sql)) {
$count = 0;
foreach ($res as $val) {
if ($count == 0){
$data = gmdate("Y-m-d H:i:s", substr(($val/10000000) - 12219292800, 0,10));
$arr[$count] = $data;
$count++;
} else {
$arr[$count] = $val;
}
}
$delimiter=",";
fputcsv($fp,$arr,$delimiter);
}
//fpassthru($fp);
fclose($fp);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $name . '.csv"');
header('Content-Length: ' . filesize($name));
echo readfile($name);
}
if(isset($_POST["cvsExp"])) {
$query=$_POST["cvsExp"];
$id=$_POST["table"];
//download_send_headers("data_export_".gmdate("Y-m-d").".csv");
array2csv($bd,$query,$id);
die();
}
?>
我刚刚删除了标题和尾随标记HTML标记
您指定了需要强制下载的方法,并且没有提供任何错误消息,因此我假设您可以通过浏览器很好地访问它
您需要首先删除该页面上的所有HTML标记。当您回显readfile$name;,您想要下载的结果文件看起来有点像这样:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>
</head>
(YOUR CSV FILE HERE)
</body>
</html>
标题函数
使用的任何标题函数都应该在页面中的任何其他内容之前发送到客户端;甚至在include connection.php之前,它就应该位于代码的最顶端;行。Ajax
不能使用Ajax下载文件
相反,如果您希望使用附加参数请求exportCSV.php文件,请将其设置为GET或POST,即:
<a href="exportCSV.php?table=table&query=name_of_the_query">Export CSV</a>
然后在该函数中返回readfile$name,而不是回显它。退出而不是死亡
实例
下面是一个简单脚本的工作示例:
<?php
// example csv
$url = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv';
function download_file()
{
// getting content to use in the example
$content = file_get_contents($url);
$filename = '/tmp/sample.csv';
// creating temp file
$handle = fopen($filename, 'w+');
fwrite($handle, $content);
fclose($handle);
// setting headers
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
return readfile($filename);
}
if (isset($_GET['export']) && $_GET['export'] === '1') {
download_file();
exit();
}
?>
<html>
<body>
<a href="?export=1">Export</a>
</body>
</html>
我希望这会有所帮助。这是我动态下载csv的简单代码
if(isset($_POST['somebutton']))
{
$filename = "somefilename.csv";
$fp = fopen('php://output', 'w');
$query = "select * from thcu_cabtemphpc order by timetag desc limit 300";
$result = mysql_query($query);
for($i=0;$i<=7;$i++)
{
$header[] = mysql_field_name($result, $i);
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$query = "select * from thcu_cabtemphpc order by timetag desc limit 300";
$result12= mysql_query($query);
while($row12 = mysql_fetch_row($result12)) {
fputcsv($fp, $row12);
}
exit;
}
这是我下载简单Excel的代码。把这个php放到任何地方,你就可以下载csv了。首先我要说的是感谢大家的回答,今天我找到了一个解决方案,我在主页上添加了以下内容:
$(function() {
$('#CSV').click(function(){
$('#wait-animation').show();
var where="<?php Print($where) ?>";
var table="<?php Print($id) ?>";
//var table="thcu_cabtemphpc";
alert("Export in progress");
alert(query);
document.location.href = 'exportCSV.php?where='+where+'&table='+table;
$('#wait-animation').hide();
});
});
在导出页面中:
<?php
include('connection.php');
header("Last-Modified: " . @gmdate("D, d M Y H:i:s",$_GET['timestamp']) . " GMT");
header("Content-type: text/x-csv");
// If the file is NOT requested via AJAX, force-download
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
header("Content-Disposition: attachment; filename=search_results.csv");
}
$table=$_GET['table'];
$where=$_GET['where'];
$day = gmdate("d-M-Y");
$offset = +2 * 3600; // timezone offset for UTC-13
$utcTime = gmdate( 'd.m.Y H:i:s' );
$milliseconds ="".round(microtime(true) * 1000);
$val= substr($milliseconds,8,10);
$valor = gmdate( 'd-m-Y_H-i-s-'.$val, time() + $offset );
$filename= $day."_".$table."data_export_".$valor.".csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='monitoring' AND TABLE_NAME='".$table."'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$result = mysql_query("select * from ".$id." where ".$where);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
return $filename;
exit;
?>
非常感谢。
祝您度过愉快的一天。将查询字符串从客户端发送到服务器端是非常糟糕和不安全的设计尝试返回readfile$name,而不是回显它。也可以使用exit而不是die。看一看:我试过了,但没什么变化。这只是一个测试,真正的页面是不同的。好吧,我创建了一个带有标题的新函数,我先调用它,但仍然不起作用。我用exit和delete ech更改模具,但仍然相同。请在标题函数上方添加此代码:ini_set'display_errors',1;ini设置“显示启动错误”,1;错误报告e_ALL;,刷新页面并用上面的内容回复?该代码将告诉PHP输出它遇到的任何错误;要读取文件$name;?您好,谢谢您的帮助,本页只是一个测试,以了解情况。在real page中,我只发送信息,我尝试了你的建议,但仍然不起作用。很抱歉听到这个消息。。。我已经更新了我的答案,看一看,看看你是否可以修复你的代码。另外,我在您的代码中还发现了一个错误:$name中已经有了.csv,但是当您设置内容处置标题时,您会在末尾再次添加csv。同样的事情,不起作用!我真的不明白问题出在哪里!
$(function() {
$('#CSV').click(function(){
$('#wait-animation').show();
var where="<?php Print($where) ?>";
var table="<?php Print($id) ?>";
//var table="thcu_cabtemphpc";
alert("Export in progress");
alert(query);
document.location.href = 'exportCSV.php?where='+where+'&table='+table;
$('#wait-animation').hide();
});
});
<?php
include('connection.php');
header("Last-Modified: " . @gmdate("D, d M Y H:i:s",$_GET['timestamp']) . " GMT");
header("Content-type: text/x-csv");
// If the file is NOT requested via AJAX, force-download
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
header("Content-Disposition: attachment; filename=search_results.csv");
}
$table=$_GET['table'];
$where=$_GET['where'];
$day = gmdate("d-M-Y");
$offset = +2 * 3600; // timezone offset for UTC-13
$utcTime = gmdate( 'd.m.Y H:i:s' );
$milliseconds ="".round(microtime(true) * 1000);
$val= substr($milliseconds,8,10);
$valor = gmdate( 'd-m-Y_H-i-s-'.$val, time() + $offset );
$filename= $day."_".$table."data_export_".$valor.".csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='monitoring' AND TABLE_NAME='".$table."'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$result = mysql_query("select * from ".$id." where ".$where);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
return $filename;
exit;
?>