Generating MySQL for Excel 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";
?>
The above code is used to create an Excel spreadsheet from a MySQL database, but we are getting the following error:
The file you are trying to open, 'users.xls', is in a different file extension. Make sure the file is intact and secure before opening the file. Do you want to open the file now?
What is the problem and how do we fix it?
a source to share
It seems that you are creating a tab-delimited file and asserting in your headers that this is the same format as an Excel spreadsheet. This is not an Excel format. And the spreadsheet downloader lets you know that you are misleading people - maybe just yourself.
You should probably look into an export format such as a CSV file; converting from tab delimited to comma delimited won't be difficult.
a source to share
Modify the code to use pure CSV and then return the file to the browser as a filename ending in .csv and content type text / csv.
I've seen people try this before and it only works with certain versions of Office Excel. It does not work on other platforms with other spreadsheet programs or every version of Excel. Use a standard file format, or at least create a proper OLE2 Compound Document that contains the XLS data in the way that Excel expects if you are going to send the file to the browser as this type.
a source to share
Try PEAR (PHP Extensions and Applications Repository) Spreadsheet_Excel_Writer . I am using this to generate Excel files in BIFF format.
a source to share
Your program is looking for a standard .xls
document that is completely different from what you are outputting. Your program outputs a tab-delimited sheet, which is a file .txt
. Try switching your program from tabs to commas as separators and save as .csv
(comma separated value).
a source to share