使用PHP的MySQL到Excel生成 [英] MySQL to Excel generation using PHP
问题描述
<?php
// DB Connection here
mysql_connect("localhost","root","");
mysql_select_db("hitnrunf_db");
$select = "SELECT * FROM jos_users ";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>
上面的代码用于从MySQL数据库
生成Excel电子表格,但是我们收到以下错误:
The code above is used for generating an Excel spreadsheet from a MySQL database, but we are getting following error:
该文件你试图打开'users.xls',是一个
不同于文件扩展名指定的格式
验证该文件是否已损坏,并且来自受信任的
源代码打开f ile,你现在要打开文件
吗?
The file you are trying to open, 'users.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?
有什么问题,我们如何解决? / p>
What is the problem and how do we fix it?
推荐答案
您没有真正生成Excel文件。您正在使用标签作为分隔符生成等于.csv文件。
You're not really generating an Excel file. You're generating what amounts to a .csv file using tabs as the seperator.
要生成真实Excel文件,请使用 PHPExcel 。
To generate a 'real' Excel file, use PHPExcel.
这篇关于使用PHP的MySQL到Excel生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!