简体   繁体   English

使用PHP将MySQL数据保存到Excel工作表

[英]Save MySQL data to Excel sheet using PHP

I am trying to write data from database to a downloadable excel sheet. 我正在尝试将数据库中的数据写入可下载的Excel工作表。 The code is working in the sense that it downloads the file with the desired name. 该代码在某种意义上可以正常工作,即可以下载具有所需名称的文件。 However if I open the Excel sheet the cells are empty and my data is not in the sheet. 但是,如果我打开Excel工作表,则单元格为空,而我的数据不在工作表中。

Here is my code 这是我的代码

require_once('include/connect_pdo.php');
$myschool = $_POST['country'];

$findschool = $conn->prepare("SELECT Query");
$findschool->execute();

$filename = "Name"; 
$file_ending = "xls";

//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename= $filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");

/*******Start of Formatting for Excel*******/   

//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character

//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
    echo mysql_field_name($result,$i) . "\t";
}
print("\n");    

//end of printing column names  
//start while loop to get data
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";
}   

This sorted my problem. 这解决了我的问题。

Header('Content-Description: File Transfer');
Header('Content-Encoding: UTF-8');
Header('Content-type: text/csv; charset=UTF-8');
Header('Content-Disposition: attachment; filename=' . '$filename' . '.csv');
echo "\xEF\xBB\xBF"; // UTF-8 BOM

$output = fopen("php://output", "w");
fputcsv($output, array('Number1', 'Number 2'));
$findschool = $conn->prepare("SELECT Query Here);
$findschool->execute();
while ($result = $findschool->fetch(PDO::FETCH_ASSOC)) {

fputcsv($output, $result);  
}
fclose($output);

XLS is Microsoft's proprietary binary format. XLS是Microsoft专有的二进制格式。 What you create with your PHP code is a CSV file. 用PHP代码创建的是CSV文件。 Try changing your file extension to .csv and Content-Type header to text/csv . 尝试将文件扩展名更改为.csv ,将Content-Type标头更改为text/csv

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

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