I want to create a an XLS file with some info from the database and the data i want to retrieve from the database are all Greek characters.I have this code and when i execute the code i got only some symbols.Anyone knows what i have to change to get Greek characters properly?
Edit: The problem is both with the data that i retrieve from the Mysql Database and the headings
Here is the code
$sql = "SELECT tmima,sex,surname,address,postcode,phone1,phone2 FROM student"; //the query
$result = $db->prepare($sql);
$result->execute();
$column = $result->columnCount();
$header = "";
$head = array("Τμήμα","Φ","Επίθετο","Όνομα","Μητρώο"); //headings of the XLS
for($i = 0; $i < $column;$i++ ){
$header .= $head[$i]."\t";
}
$data = "";
while($row = $result->fetch(PDO::FETCH_ASSOC)/*mysql_fetch_row($rec)*/){
$line = '';
foreach($row as $value){
if((!isset($value)) || ($value == " ")){
$value = "\t";
}else{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}//end of if-else
$line .= $value;
}//end of foreach
$data .= trim( $line ) . "\n";
}//end of while($row = mysql_fetch_row($rec))
$data = str_replace("\r" , "" , $data);
if ($data == ""){
$data = "\n No Record Found!\n";
}
header('Content-Description: File Transfer');
header('Content-Type: application/ms-excel; charset=utf8');
header("Content-Disposition: attachment; filename=Student_data.xls");
//header("Content-Transfer-Encoding: binary ");
header("Expires: 0");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Pragma: public");
print "$header\n$data";
no the data i get from the Mysql qquery is with greek characters
Make sure your database connection is UTF-8 encoded. See UTF-8 all the way through on how to do that.
Related
I am currently trying to automate monthly invoices of orders to my application with its backend using PHP and SQL Server.
I referred to various other questions of people who were using MySQL as their backend but it still doesn't work and fails to create an excel file. I tried creating a CSV file and it worked but it fetched a single record.
My PHP code is as follows:
<?php
include 'db_connect.php';
$filename = "excelfilename";
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sql = "SELECT *
FROM Trn_Order tro
INNER JOIN Trn_Place_Order tpo ON tro.Order_Id = tpo.Order_Id
INNER JOIN Mst_User_Login mul ON tro.User_Id = mul.User_Id
WHERE tro.Status != 'Rejected'
AND tro.Added_On LIKE '2022-01%'
ORDER BY tro.Order_Id ASC";
$result = sqlsrv_query($conn, $sql);
$sep = '\t';
for ($i = 0;$i < sqlsrv_num_fields($result);$i++) {
echo sqlsrv_get_field($result, $i) . '\t';
}
echo '\n';
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_BOTH)) {
$schema_insert = "";
for ($j = 0;$j < sqlsrv_num_fields($result);$j++) {
if (!isset($row[$j])) {
$schema_insert = $schema_insert."NULL" . $sep;
} elseif ($row[$j] != "") {
$schema_insert = $schema_insert. "$row[$j]" . $sep;
} else {
$schema_insert = $schema_insert."" . $sep;
}
}
$schema_insert = str_replace($sep . "$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert = $schema_insert. "\t";
echo trim($schema_insert);
echo '\n';
}
?>
** Working Code **
<?php
date_default_timezone_set('Asia/Kolkata');
include 'db_connect.php';
$FileName = "MonthlyExcelReport.csv";
$fp = fopen('php://output', 'w');
$Fetch_Month = $_POST["Fetch_Month"];
$sql = "SELECT tro.Order FROM Trn_Order tro
INNER JOIN Mst_User_Login mul
ON tro.User_Id = mul.User_Id
WHERE tro.Status != 'Rejected' AND tro.Added_On LIKE '2022-01%' ORDER BY tro.Order_Id ASC";
$resec = sqlsrv_query($conn, $sql);
while ($export= sqlsrv_fetch_array($resec, SQLSRV_FETCH_ASSOC))
{
if (!isset($headings))
{
$headings = array_keys($export);
fputcsv($fp, $headings, ',', '"');
}
fputcsv($fp, $export, ',', '"');
}
fclose($fp);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.$FileName.'');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize("php://output"));
readfile("php://output");
?>
Thanks to everybody who suggested a solution.
I found a working solution with #ADyson guidance.
Due to clashing column names the excel had issues after being created, which was fixed by using alias or referencing the tablename.
The working code is as follows :
<?php
date_default_timezone_set('Asia/Kolkata');
include 'db_connect.php';
$FileName = "MonthlyExcelReport.csv";
$fp = fopen('php://output', 'w');
$Fetch_Month = $_POST["Fetch_Month"];
$sql = "SELECT tro.Order_Id,ml.User_Name FROM Trn_Order tro
, Mst_User_Login ml
WHERE tro.User_Id = ml.User_Id and tro.Status != 'Rejected' AND tro.Added_On LIKE '2022-01%' ORDER BY tro.Order_Id ASC";
$resec = sqlsrv_query($conn, $sql);
while ($export = sqlsrv_fetch_array($resec, SQLSRV_FETCH_ASSOC))
{
if (!isset($headings))
{
$headings = array_keys($export);
fputcsv($fp, $headings, ',', '"');
}
fputcsv($fp, $export, ',', '"');
}
fclose($fp);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=' . $FileName . '');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize("php://output"));
readfile("php://output");
?>
I have multiple condition so I am trying to generate a function to download the sql data to Csv File. I am having trouble in downloading the file. Whenever I try to, the page just reloads and file doesnot download. I am not sure what I am doing wrong as when I use echo command, I can see the data displayed on page. Kindly if someone can help and direct me to right way, that would be really helpful.
if(isset($_POST['report'])){
$sql = mysql_query("SELECT rating_postid,rating_posttitle,COUNT(rating_rating) AS Count,AVG(rating_rating) as Average FROM wp_ratings WHERE 1=1
GROUP BY rating_postid,rating_posttitle") or die(mysql_error());
generate_csv($sql);
}
function generate_csv($sql){
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
header("Content-Transfer-Encoding: binary");
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen('php://output','w');
$sep = "";
$comma= "";
foreach($row as $name => $value)
{
$sep .= $comma . '' .STR_REPLACE('','""',$name);
$comma = ",";
}
$sep .= "\n";
fputs($fp,$sep);
mysql_data_seek($sql,0);
while($row = mysql_fetch_assoc($sql))
{
$sep = "";
$comma= "";
foreach($row as $name => $value)
{
$sep .= $comma . '' .STR_REPLACE('','""',$value);
$comma = ",";
}
$sep .= "\n";
fputs($fp,$sep);
}
fclose($fp);
//echo $fp;
}
else
{
echo 'NO RECORDS IN DATABASE';
}
}
I hve to download mysql database to excel sheet. I get following errors when i try to download
Notice: Undefined variable: data in C:\xampp\htdocs\admissions\excel\excel2.php on line 27
Notice: Undefined variable: header in C:\xampp\htdocs\admissions\excel\excel2.php on line 12.
What and where i need to define in header and data.
Here is the code
<?php
ob_start();
mysql_connect('localhost','root','');
mysql_select_db('sjbhsbg');
$sql = "SELECT * from admissions";
$res = mysql_query($sql) or die();
$count = mysql_num_fields($res);
// fetch table header from database
$header = '';
for ($i = 0; $i < $count; $i++){
$header .= mysql_field_name($res, $i)."\t";
}
// fetch data each row, store on tabular row data
while($row = mysql_fetch_row($res)){
$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);
}
$name=date('d-m-y').'-list.xls';
header("Content-type:application/vnd.ms-excel;name='excel'");
header("Content-Disposition: attachment; filename=$name");
header("Pragma: no-cache");
header("Expires: 0");
// Output data
echo $header."\n\n".$data;
?>
$query="select * from admissions";
$result = mysql_query($query) or die('Please Choose any one of the fields to export');
//header('Content-Disposition: attachment;filename=export.csv');
$filename = $title.date("d-m-Y",time());
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
I'm trying to get my MySQL data to Excel file, but I'm having problems with Excel cells. All my text goes to one cell, I would like to have each row value in separate Excel cell. Here is my code:
$queryexport = ("
SELECT username,password,fullname FROM ecustomer_users
WHERE fk_customer='".$fk_customer."'
");
$row = mysql_fetch_assoc($queryexport);
$result = mysql_query($queryexport);
$header = '';
for ($i = 0; $i < $count; $i++){
$header .= mysql_field_name($result, $i)."\t";
}
while($row = mysql_fetch_row($result)){
$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 = "\nno matching records found\n";
}
}
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=exportfile.xls");
header("Pragma: no-cache");
header("Expires: 0");
// output data
echo $header."\n".$data;
mysql_close($conn);`
Just Try With The Following :
PHP Part :
<?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 think this may help you to resolve your problem.
Try this code. It's definitly working.
<?php
// Connection
$conn=mysql_connect('localhost','root','');
$db=mysql_select_db('excel',$conn);
$filename = "Webinfopen.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$user_query = mysql_query('select name,work from info');
// Write data to file
$flag = false;
while ($row = mysql_fetch_assoc($user_query)) {
if (!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
?>
If you just want your query data dumped into excel I have to do this frequently and using an html table is a very simple method. I use mysqli for db queries and the following code for exports to excel:
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo '<table border="1">';
//make the column headers what you want in whatever order you want
echo '<tr><th>Field Name 1</th><th>Field Name 2</th><th>Field Name 3</th></tr>';
//loop the query data to the table in same order as the headers
while ($row = mysqli_fetch_assoc($result)){
echo "<tr><td>".$row['field1']."</td><td>".$row['field2']."</td><td>".$row['field3']."</td></tr>";
}
echo '</table>';
This is new version of php code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_dbname";
//mysql and db connection
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) { //error check
die("Connection failed: " . $con->connect_error);
}
else
{
}
$DB_TBLName = "your_table_name";
$filename = "excelfilename"; //your_file_name
$file_ending = "xls"; //file_extention
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.'.'.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
$sql="SELECT * FROM $DB_TBLName";
$resultt = $con->query($sql);
while ($property = mysqli_fetch_field($resultt)) { //fetch table field name
echo $property->name."\t";
}
print("\n");
while($row = mysqli_fetch_row($resultt)) //fetch_table_data
{
$schema_insert = "";
for($j=0; $j< mysqli_num_fields($resultt);$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";
}
PHPExcel is your friend. Very easy to use and works like a charm.
https://github.com/PHPOffice/PHPExcel
I think you should try with this API
http://code.google.com/p/php-excel/source/browse/trunk/php-excel.class.php
With This
Create a quick export from a database table into Excel
Compile some statistical records with a few calculations and deliver
the result in an Excel worksheet
Gather the items off your (web-based) todo list, put them in a
worksheet and use it as a foundation for some more statistics
magic.**
Try this code:
<?php
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=hasil-export.xls");
include 'view-lap.php';
?>
try this code
data.php
<table border="1">
<tr>
<th>NO.</th>
<th>NAME</th>
<th>Major</th>
</tr>
<?php
//connection to mysql
mysql_connect("localhost", "root", ""); //server , username , password
mysql_select_db("codelution");
//query get data
$sql = mysql_query("SELECT * FROM student ORDER BY id ASC");
$no = 1;
while($data = mysql_fetch_assoc($sql)){
echo '
<tr>
<td>'.$no.'</td>
<td>'.$data['name'].'</td>
<td>'.$data['major'].'</td>
</tr>
';
$no++;
}
?>
code for excel file
export.php
<?php
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=codelution-export.xls");
// Add data table
include 'data.php';
?>
if mysqli version
$sql="SELECT * FROM user_details";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
$no = 1;
while($data = mysqli_fetch_assoc($result))
{echo '
<tr>
<<td>'.$no.'</td>
<td>'.$data['name'].'</td>
<td>'.$data['major'].'</td>
</tr>
';
$no++;
http://codelution.com/development/web/easy-ways-to-export-data-from-mysql-to-excel-with-php/
You can export the data from MySQL to Excel by using this simple code.
<?php
include('db_con.php');
$stmt=$db_con->prepare('select * from books');
$stmt->execute();
$columnHeader ='';
$columnHeader = "Sr NO"."\t"."Book Name"."\t"."Book Author"."\t"."Book
ISBN"."\t";
$setData='';
while($rec =$stmt->FETCH(PDO::FETCH_ASSOC))
{
$rowData = '';
foreach($rec as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData)."\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Book record
sheet.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader)."\n".$setData."\n";
?>
complete code here php export to excel
Posts by John Peter and Dileep kurahe helped me to develop what I consider as being a simpler and cleaner solution, just in case anyone else is still looking. (I am not showing any database code because I actually used a $_SESSION variable.)
The above solutions invariably caused an error upon loading in Excel, about the extension not matching the formatting type. And some of these solutions create a spreadsheet with the data across the page in columns where it would be more traditional to have column headings and list the data down the rows. So here is my simple solution:
$filename = "webreport.csv";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
foreach($results as $x => $x_value){
echo '"'.$x.'",' . '"'.$x_value.'"' . "\r\n";
}
Change to .csv (which Excel instantly updates to .xls and there is no error upon loading.)
Use the comma as delimiter.
Double quote the Key and Value to escape any commas in the data.
I also prepended column headers to $results so the spreadsheet looked even nicer.
Try the Following Code Please.
just only update two values.
1.your_database_name
2.table_name
<?php
$host="localhost";
$username="root";
$password="";
$dbname="your_database_name";
$con = new mysqli($host, $username, $password,$dbname);
$sql_data="select * from table_name";
$result_data=$con->query($sql_data);
$results=array();
filename = "Webinfopen.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
while ($row = mysqli_fetch_assoc($result_data)) {
if (!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
?>
This is baes on John Peter's answer above. The code is working perfectly but I needed it for WordPress. So, I did something like this:
<?php
require '../../../wp-load.php';
$file_name = "registered-users";
$args = array( 'role' => 'client',
'meta_query' => array( array(
'key' => '_dt_transaction_archived',
'compare' => 'NOT EXISTS'
) ),
'order' => 'DESC',
'orderby' => 'ID'
);
$users = get_users( $args );
$file_ending = "xls";
// Header info for browser
header( "Content-Type: application/xls" );
header( "Content-Disposition: attachment; filename=$file_name.$file_ending" );
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
print( "First Name" . $sep );
print( "Last Name" . $sep );
print( "E-Mail" . $sep );
print( "\n" );
// end of printing column names
// start foreach loop to get data
$schema_insert = "";
foreach ($users as $user) {
if ( $user ) {
$schema_insert = "$user->first_name" . $sep;
$schema_insert .= "$user->last_name" . $sep;
$schema_insert .= "$user->user_email" . $sep;
print "\n";
$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 ) );
}
}
Using PHP, I can convert MySQL data or static table data to csv, Excel, JSON, MySQL etc but is there a useful conversion script or tool that can convert table data into other formatted/styled formats such as PDF and/or JPG/PNG using the PHP GD Library or other?
I've used this before to turn a HTML table into a PDF. I generated the table from a MySQL query.
To export to Excel I use the following code:
<?php
/* Define our Database and Table Info */
$username="";
$password="";
$database="";
$table="";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$select = "SELECT * FROM $table";
$export = mysql_query($select);
$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)) OR ($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/x-msdownload");
header("Content-Disposition: attachment; filename=mailinglist.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>
Now be careful with how you include this. It's using the Headers to send the file information to force a download, by doing this you can't have any white space anywhere before these headers are sent otherwise it may throw an error. I usually have this link open as a new window to prevent anything from happening... Again this is just a pretty basic script that can be expanded greatly. Hope this Helps!
<?php
/ Define our Database and Table Info /
$username="";
$password="";
$database="";
$table="";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$select = "SELECT * FROM $table";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . ",";
}
while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = ",";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . ",";
}
$line .= $value;
}
$data .= trim($line)."n";
}
$data = str_replace("r","",$data);
if ($data == "") {
$data = "n(0) Records Found!n";
}
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=mailinglist.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$headern$data";
?>