简体   繁体   English

将数据导出为Excel文件

[英]export data as excel file

I can easily export data as excel by simple code but i got problem when i need to call the export.php by j query code data is not download as export.php file code as below 我可以通过简单的代码轻松将数据导出为ex​​cel,但是当我需要通过j调用export.php时出现问题,查询数据未下载为export.php文件代码,如下所示

<?php
include '../../config.php';
function cleanData(&$str)
{
    if($str == 't') $str = 'TRUE';
    if($str == 'f') $str = 'FALSE';
    if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
        $str = "'$str";
    }
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
    $str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}

$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv<span>; charset=UTF-16LE</span>");

$out = fopen("php://output", 'w');

$flag = false;
$result = mysql_query("SELECT * FROM employee") or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result))) {
    if(!$flag) {
        fputcsv($out, array_keys($row), ',', '"');
        $flag = true;
    }
    array_walk($row, 'cleanData');
    if($row['photo']!='')
    {
        $row['photo']="http://localhost/admin/employee_image/".$row['photo'];
    }
    fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;

there is any way to call this file by jquery? 有什么办法可以通过jQuery调用该文件?

No you cannot do this by Javascript using jQuery or any other library, AJAX calls data in Javascript engine inside the browser. 不,您不能使用jQuery或任何其他库通过Javascript来执行此操作,AJAX会在浏览器内部的Javascript引擎中调用数据。

But you can use HTML5 download attribute: 但是您可以使用HTML5下载属性:

<a href="your_file.xls" download="YourFile.xls">Download Excel</a>

And give proper headers in PHP: 并在PHP中提供适当的标题:

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=your_file.xls"); 
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);

EDIT: 编辑:

Although the above will work, I take my words back as I found this: 尽管上面的方法行得通,但我发现这句话后还是回想一下:

http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/ http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/

Made by https://stackoverflow.com/users/455556/john-culviner , ask him for help if you need https://stackoverflow.com/users/455556/john-culviner制作 ,如果需要,请向他寻求帮助

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM