can i overwrite an excel file using php? - php

I created the file using PHPExcel at say C:\path\goes\here\filename.xls
When I try to access it using header(), it creates a file filename(1) , filename(2) and so on.
(PS : When i say overwrite, I mean to erase previous content and add new data).
<?php
include 'PHPExcel.php';
require_once ("C:\\xampp\\htdocs\\excel_mailer_2\\PHPMailer-master\\class.phpmailer.php");
$path = "C:\\Users\\Manish\\Downloads";
$file_name = $_GET['file_name'];
$DB_server = "localhost";
$DB_username = "root";
$DB_password = "";
$DB_dbname = "timetracker";
$DB_tablename = "tt_users";
$conn = mysqli_connect ($DB_server, $DB_username, $DB_password, $DB_dbname);
if (mysqli_connect_errno()) {
die ("Connection Failed!");
}
$sql = "SELECT *";
$sql .= " FROM $DB_tablename";
if ($result = mysqli_query($conn,$sql));
else die("Couldn't execute query:<br />" . mysqli_error(). "<br />" . mysqli_errno());
$file_ending = ".xls";
$filename = $file_name.$file_ending;
//header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename");
/*******Start of Formatting for Excel*******/
$sep = "\t";
$flag = true;
$col_names = "";
while($row = mysqli_fetch_assoc($result)) {
$data_insert = "";
foreach($row as $field=>$data) {
if ($flag)
$col_names .= $field.$sep;
if(!isset($data))
$data_insert .= "NULL".$sep;
elseif ($data != "")
$data_insert .= $data.$sep;
else
$data_insert .= "".$sep;
}
if ($flag) {
$flag = !$flag;
$col_names .= "\t";
echo (trim($col_names));
echo "\n";
}
$data_insert .= "\t";
echo (trim($data_insert));
echo "\n";
}
?>

Hi write your filename in header function using this
header('Content-Disposition: attachment; filename="filename.xls"');

you can use php basename() function to get the file names at that specific path and then check if the file you are creating already exists.
if it already exists then delete the old file and create the new file.
https://www.w3schools.com/php/func_filesystem_basename.asp
and this should be done before you call header("Content-Disposition: attachment; filename=$filename");

Related

PHP Export to CSV does not send all data to the file

I am exporting to CSV from my php reporting website. I have reports that are more than 80k rows. When I export one of them the whole data set does not get exported. I have tried several times with a report that is 88k+ rows and it exports 87k+ rows and then stops part way through the last row that is exported.
What is going on? The query that pulls the data from MSSQL is correct (I've checked).
Here's my Export file:
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('DBConn.php');
include 'Helper/LogReport.php';
if(isset($_GET['Id']))
{
$id = $_GET['Id'];
$query = $conn->prepare('SELECT QName, tsql from pmdb.QDefs WHERE Id = ' . $id);
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);
}
else
{
$query = $conn->prepare("SELECT QName, tsql from pmdb.QDefs WHERE QName = '" .$TableName. "'");
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);
}
// Create and open file for writing
$filepath = 'exports/';
$filename = $qdef['QName'] . '.csv';
try
{
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset:UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}
//define separators
$sep = ","; //separator
$br = "\r\n"; //line break
// Use returned tsql field as query for dataset
$tsql = $qdef['tsql'];
if(isset($DataReturn))
{
if(strpos($DataReturn['Order'],'EDIT'))
{
$DataReturn['Order'] = str_replace('EDIT','Id',$DataReturn['Order']);
}
$tsql = $tsql . $DataReturn['WhereClause'] . $DataReturn['Order'] . $DataReturn['Limit'];
}
$query = $conn->prepare($tsql);
$query->execute();
// Output data to CSV file
$headers = NULL;
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
//Write column headings to file
if (is_null($headers))
{
$headers = array_keys($row);
if ($headers[0] == 'ID')
$headers[0] = 'Id';
foreach($headers as $Header)
{
echo $Header. ",";
}
echo $br;
}
//Write data
$modRow = preg_replace('/ \d{2}:\d{2}:\d{2}\.\d{3}/', '', $row);
$modRow = preg_replace( "/\r|\n/", "", $modRow );
foreach($modRow as $RowPrint)
{
echo '"' .trim(unserialize(serialize($RowPrint))). '"' .$sep;
}
echo $br;
}
I don't see anything that would stop the data stream from completing the export.
EDIT
I have tried the fputcsv() method like this:
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('DBConn.php');
include 'Helper/LogReport.php';
//print_r($_GET);
if(isset($_GET['Id']))
{
$id = $_GET['Id'];
$query = $conn->prepare('SELECT QName, tsql from pmdb.QDefs WHERE Id = ' . $id);
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);
}
else
{
$query = $conn->prepare("SELECT QName, tsql from pmdb.QDefs WHERE QName = '" .$TableName. "'");
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);
}
// Create and open file for writing
$filepath = 'exports/';
$filename = $qdef['QName'] . '.csv';
try
{
$openFile = fopen($filepath . $filename,'a');
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset:UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}
//define separators
$sep = ","; //separator
$br = "\r\n"; //line break
// Use returned tsql field as query for dataset
$tsql = $qdef['tsql'];
if(isset($DataReturn))
{
if(strpos($DataReturn['Order'],'EDIT'))
{
$DataReturn['Order'] = str_replace('EDIT','Id',$DataReturn['Order']);
}
$tsql = $tsql . $DataReturn['WhereClause'] . $DataReturn['Order'] . $DataReturn['Limit'];
}
$query = $conn->prepare($tsql);
$query->execute();
// Output data to CSV file
$headers = NULL;
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
//Write column headings to file
if (is_null($headers))
{
$headers = array_keys($row);
if ($headers[0] == 'ID')
$headers[0] = 'Id';
fputcsv($openFile, $headers);
}
//Write data
$modRow = preg_replace('/ \d{2}:\d{2}:\d{2}\.\d{3}/', '', $row);
$modRow = preg_replace( "/\r|\n/", "", $modRow );
fputcsv($openFile, $modRow, ',','"');//print_r($modRow);
foreach($modRow as $RowPrint)
{
error_log(date("Y/m/d h:i:sa "). ' RowPrint: ' .$RowPrint. '\n',3,'C:\Temp\LogPHP.txt');
}
echo $br;
}
// Close file
fclose($openFile);
This just creates an empty file.
UPDATE
I ran a couple of reports for one that should have 103k+ rows. They both stopped between 61000 and 62000 rows. I did a character count and they both have around 40 million. I don't see anything about a 40million character limit.
I got it working and figured out how to get the fputcsv to work.
I needed to add an exit() to the end of the export. Now it not only sends all the data fputcsv works as well. I got the answer from another question that I ask about getting fputcsv to work.

Save Excel Export to File Location PHP

I am trying to get the code below to save to a file location on the server, can anyone help. Currently it just downloads via browser but i want to run a cron and save in a file location.
<?php
// Connection
$conn=mysql_connect('**','**','**');
$db=mysql_select_db('SHP',$conn);
$filename = "stockbook.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
file_put_contents("http://kempfenterprises.com/dash/reports/stockbook.xls");
$user_query = mysql_query("select * from troy.stockbook ");
// 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";
}
?>
Thanks in advance
You can use file_put_contents to write file in server.
http://php.net/manual/en/function.file-put-contents.php
<?php
$conn=mysql_connect('**','**','**');
$db=mysql_select_db('SHP',$conn);
$sql = "select * from troy.stockbook";
$qur = mysql_query($sql);
// Enable to download this file
$filename = "stockbook.csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv");
$display = fopen("php://output", 'w');
$flag = false;
while($row = mysql_fetch_assoc($qur)) {
if(!$flag) {
// display field/column names as first row
fputcsv($display, array_keys($row), ",", '"');
$flag = true;
}
fputcsv($display, array_values($row), ",", '"');
}
fclose($display);
?>
this is using fopen how can i now add a location where i want to save it
<?php
$conn = mysql_connect('**', '**', '**');
$db = mysql_select_db('SHP', $conn);
$sql = "select * from troy.stockbook";
$qur = mysql_query($sql);
// Enable to download this file
$filename = "stockbook.csv";
$display = fopen("php://output", 'w');
$data = "";
$flag = false;
while ($row = mysql_fetch_assoc($qur)) {
if (!$flag) {
// display field/column names as first row
$data.=implode("\t", array_keys($row)) . "\n";
$flag = true;
}
$data.=implode("\t", array_values($row)) . "\n";
}
file_put_contents($filename, $data);
exit();
?>

Exporting to CSV from MySQL via PHP

I am trying to bug fix a PHP script that should export values from a MySQL database to a CSV file.
The PHP file is returning a blank CSV file & I can't figure out why & I've been stuck on this for quite a while, so any help would be much apprwciated.
Code below:
<?
include('../../../inc/config.php');
$period = $_GET['pid'];
$psql = "SELECT month, year FROM survey_period WHERE sid = " . $period;
$pres = mysql_query($psql, $dcon);
$prow = mysql_fetch_array($pres);
$pmonth = $prow['month'];
$pyear = $prow['year'];
$query="SELECT
sid,
date,
stove_id,
name,
gender,
marital_status,
occupation_of_household,
cz_stove AS km_stove,
happy_with_cz_stove AS happy_with_km_stove,
cz_stove_in_use AS km_stove_in_use,
know_how_to_use,
FROM survey_usage WHERE period = " . $_GET['pid'];
$result = mysql_query($query, $dcon);
//header('Content-Disposition: attachment;filename=export.csv');
$filename = 'usage-'.$pid.'-'.$pmonth.'-'.$pyear;
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";
}
?>
hey i have a code you can use it like this
<?PHP
// Define database connection variable dynamically
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = ""; //MySQL Password
$DB_DBName = "test1"; //MySQL Database Name
$DB_TBLName = "tabletest"; //MySQL Table Name
$filename = "excelfilename"; //File Name
//create MySQL connection
$sql = "Select * from csvtable";
$Connect = #mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() );
//select database
$Db = #mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() );
//execute query
$result = #mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() );
function cleanData(&$str)
{
if ($str == 't')
$str = 'TRUE';
if ($str == 'f')
$str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;
while ($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"'); $flag = true;
}
array_walk($row, 'cleanData');
// insert data into database from here
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end
?>
The issue is that you are not writing anything to the csv file before opening it.
Use this code
$fp = fopen($filename, 'w');
$result = mysql_query($query);
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
fputcsv($fp, $headers);
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
header('Content-Type: text/csv');
header( "Content-disposition: filename=".$filename);
readfile($filename);
Thanks to everyone for your suggestions, problem now solved, turned out to be a simple comma in the wrong place - "know_how_to_use," changed to " know_how_to_use" solved the problem. Thanks #Tintu C Raju for pointing me in the right direction

Exporting mysql html table to excel file

I am trying to query a mysql database and display data in a table.I now want to take the table and make a button that allows you to export it to an excel file.now you were able to export to excel,but its showing an error Notice: Undefined variable: data
Below is my code:
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "export";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
$values =mysql_query( "SELECT name,email,phone,nationality,dob FROM users order by id");
$header = "Name" . "\t";
$header .= "Email" . "\t";
$header .= "Phone" . "\t";
$header .= "Nationality" . "\t";
$header .= "DOB" . "\t";
while( $row = mysql_fetch_assoc($values)){
$row1 = array();
$row1[] = $row['name'];
$row1[] = $row['email'];
$row1[] = $row['phone'];
$row1[] = $row['nationality'];
$row1[] = $row['dob'];
$data .= join("\t", $row1)."\n";
}
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=expot.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
exit();
?>
Because you never initialize the $data variable.
Put:
$data = '';
at the beginning of your code, before the while cycle.
Your code contains the statement:
$data .= join("\t", $row1)."\n";
This is where you're concatenating a string to an existing variable $data. However, no such variable exists. You should add somewhere near the top of your code:
$data = "";
to initialize the $data variable.

Export MySQL data to Excel in PHP

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 ) );
}
}

Categories