<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "username"; //MySQL Username
$DB_Password = "password"; //MySQL Password
$DB_DBName = "databasename"; //MySQL Database Name
$DB_TBLName = "tablename"; //MySQL Table Name
$filename = "excelfilename"; //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$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";
}
?>
I tried to use the Peter's code as above.
The data is exporting nicely but the following error message is being thrown:
The file format and extension of 'database.xls' don't match. The file
could be corrupted or unsafe. Unless you trust its source don't open
it. Do you want to open it anyway?
I have tried with different file extension but could not fix it.
The reason of the error is that you are creating a text file, with field separated by tab, and not an Excel file.
Simply change the lines:
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
with:
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=$filename.txt");
or, alternatively:
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=$filename.csv");
Then you could open this file also from Excel.
Related
I am trying to write data from database to a downloadable excel sheet. 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.
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. What you create with your PHP code is a CSV file. Try changing your file extension to .csv and Content-Type header to text/csv.
Exporting excel file from php show error after download and open the file:
the file you are trying to open is in a different format .xls
I want to download table field and fill data and upload to database again using php code.
I tried many application type. I just want to give user a file with structure which contains database field name and user will add data and will again upload to database using php.
<?php
`session`_start();
include 'db.php';
/*******EDIT LINES 3-8*******/
$DB_TBLName = $_POST["tablename"]; //MySQL Table Name
$filename = $_POST["excelfilename"]; //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "SHOW COLUMNS FROM $DB_TBLName";
//execute query
$result = $conn->query($sql);
$file_ending = "xls";
//header info for browser
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename.xls");
header ('Content-Transfer-Encoding: binary');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
/*header('Content-Type: application/vnd.ms-excel');
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
while($row = $result->fetch_assoc())
{
echo $row['Field'] . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = $result->fetch_assoc())
{
$schema_insert = "";
for($j=0; $j<$result->field_count;$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";
}
?>
I have a php code that selects an query from a postgres db and creates a xls file and downloads the same. The code is as follows :
<?php
$xls_filename = 'filename.xls'; // Define Excel (.xls) file name
$Connect = pg_connect ("host=xxxx port=5432 dbname=xxxx user=xxx password=xxx");
$sql = 'SELECT * FROM "tablename"';
$result = pg_query($sql);
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$xls_filename");
header("Pragma: no-cache");
header("Expires: 0");
// Define separator (defines columns in excel & tabs in word)
$sep = "\t"; // tabbed character
// Start of printing column names as names of fields
for ($i = 0; $i<pg_num_fields($result); $i++) {
echo pg_field_name($result,$i) . "\t";
}
print("\n");
// End of printing column names
// Start while loop to get data
while($row = pg_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<pg_num_fields($result); $j++)
{
if(!isset($row[$j])) {
$schema_insert .= "".$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";
}
}
?>
I want to zip this xls file which is created rather then just downloading it.
How do I create a xls file in the directory instead of downloading it.
The problem is your variable.when your file name has space you have to use quotes like below:
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename='$xls_filename'");
You can use below code that work fine
$fileNames = WWW_ROOT . 'uploads' . DS . 'export' . DS . 'DYNAMIC_FILE_NAME_'. $ANY_DYNAMIC_PART.'.xls';//Dynamic Path of the directory
if (file_exists($fileNames)) {
$file = $fileNames;
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"NEWFILENAME.xls\"");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
readfile($fileNames);exit;
}
The code below exports a .csv file with multiple columns. The column "PRET" is General formatted and it contains the price of products with format xx.xx . I want to turn my values in xx,xx. How can I format the column PRET of type Text or should I replace "." with "," when the file is exported?
<?php
// call export function
exportMysqlToCsv('export_stoc.csv');
// export csv
function exportMysqlToCsv($filename = 'export_stoc.csv')
{
$conn = dbConnection();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//v
$sql_query = "SELECT
produse.DENUMIRE,
clase.CLASA,
furnizori.NUME_J,
furnizori.NUME_F,
stoc.CANTITATE,
produse.PRET,
produse.VALUTA,
stare.STARE
FROM clase
JOIN produse ON produse.ID_CLASA = clase.ID
JOIN furnizori ON produse.ID_FURNIZOR = furnizori.ID
JOIN stoc ON stoc.ID_PRODUS = produse.ID
JOIN stare ON stare.ID = stoc.ID_STARE;
//execute this sql and fetch your results as needed
// Gets the data from the database
$result = $conn->query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
if ($first) {
fputcsv($f, array_keys($row), ';')
$first = false;
}
fputcsv($f, $row, ';');
} // end while
$conn->close();
$size = ftell($f);
rewind($f);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: $size");
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
header("Content-type: text/csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
fpassthru($f);
exit;
}
// db connection function
function dbConnection(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
?>
Thank you!
There are no "formats" in CSV; CSV is just plain-text separated by some separator.
So...
should I replace "." with "," when the file is exported.
...yes.
This code export one file.csv and separated the columns with ","
I have another little problem with this code. Regional settings of my PC are not on the US but on Romanian. This means that with the US separation is done by "," and in Romanian by ";" and Excel takes regional settings of the PC.
What can I do to code to make separation by ";" ?
Thank you!
<?php
// call export function
exportMysqlToCsv('export_csv.csv');
// export csv
function exportMysqlToCsv($filename = 'export_csv.csv')
{
$conn = dbConnection();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql_query = "SELECT id, firstname, lastname FROM MyGuests";
// Gets the data from the database
$result = $conn->query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
if ($first) {
fputcsv($f, array_keys($row));
$first = false;
}
fputcsv($f, $row);
} // end while
$conn->close();
$size = ftell($f);
rewind($f);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: $size");
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
header("Content-type: text/csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
fpassthru($f);
exit;
}
// db connection function
function dbConnection(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
?>
You have to use like below, you can refer put comma as separator in export to CSV in php for more.
$delimiter = ',';
$enclosure = '"';
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
fputcsv($f, $row, $delimiter, $enclosure);
}