My problem looks like this at the front side:
After choosing which of my users I want to export:
I'm sending AJAX request containing their database ids to external file named exportUsers.php.
So this is how back end of my problem looks like:
When data arrive to exportUsers.php, I query the database and make array($data) like this, which I want to export into Excel file.
This is how i tried to trigger download:
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$flag = false;
foreach($data as $row1) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row1)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
echo implode("\t", array_values($row1)) . "\r\n";
}
$filename = "users_data" . date('Ymd') . ".xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=\"$filename\"");
But this is all I see in Network tool of my browser:
But no download was triggered. Please help
Try this
session_start();
include "connection.php";
$sql= mysql_query("select * from table") or die(print "Failed Download :".mysql_error());
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "FileName.xls";
header('Content-type: application/xls');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
//jzend...
exit;
?>
Related
I have a page that allow user to export particular data in .xls file.
Here is the code.
if(isset($_SESSION['name'])){
$user_name=$_SESSION['name'];$sql = "select * from asset_details inner join bank_details on asset_details.user_id=bank_details.user_id inner join merchant_details on asset_details.user_id=merchant_details.user_id inner join merchant_status on asset_details.user_id=merchant_status.user_id inner join merchant_ids on asset_details.user_id=merchant_ids.user_id inner join terminal_details on asset_details.user_id=terminal_details.user_id where asset_details.user_id='$user_name' order by merchant_details.time_date asc" ; $result = mysqli_query($db,$sql); function filterData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// file name for download
$fileName = "report" . date('Ymd') . ".xls";
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($result as $row) {
if(!$flag) {
// display column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
// filter data
array_walk($row, 'filterData');
echo implode("\t", array_values($row)) . "\n";
}
exit;}
The Problem is that while exporting the data it takes column name from database rather than from the column name on the page.
I have code to export mysql query result data into Excel. But Now I use SQL Server.I haven't idea to fetch number of fields name. I find many blogs but they all are display php function of mysql database. I need php function which usefull to get field name and number from SQL Query Result
$header = '';
$result = '';
$exportData = sqlsrv_query($gaSql['link'], $sQuery) or die("$sQuery: " . sqlsrv_errors());
$fields = mysql_num_fields($exportData);
for ($i = 0; $i < $fields; $i++) {
if (in_array(mysql_field_name($exportData, $i), $_POST['optFieldName'])) {
$header .= mysql_field_name($exportData, $i) . "\t";
}
// $header .= mysql_field_name($exportData, $i) . "\t";
}
//
$row = array();
for ($i = 0; $i < mysql_num_rows($exportData); $i++) {
$result_excel = mysql_fetch_array($exportData);
array_push($row, $result_excel);
}
foreach ($row as $rowvalue) {
$line = '';
for ($j = 0; $j < count($_POST['optFieldName']); $j++) {
$value = $rowvalue[$_POST['optFieldName'][$j]];
if ((!isset($value) ) || ( $value == "" )) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$result .= trim($line) . "\n";
}
$result = str_replace("\r", "", $result);
if ($result == "") {
$result = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";
I am using php to export data from Database.My problem is.Data export successfully but it create two blank rows at beginning.I want to remove them.Here is my code
if($_POST){
$output = "";
$table = "schedule"; // Enter Your Table Name
$sql = mysql_query("select * from $table WHERE post_id='".$_POST['schedule_id']."'");
$columns_total = mysql_num_fields($sql);
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.trim($row["$i"]).'",';
}
$output .="\n";
}
$filename = "schedule.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
You should wrap string with spaces with double quotes or any other character.
See the function provided by this answer https://stackoverflow.com/a/3933816/1163444
I have a program that turns a file into an excel file but for some reason my phone and email fields get switched. It looks like this -
firstname lastname email phone
test bi#gmail.com
test d 813-767 leighmimail.com
test Pds 888-413 Bperotects.com
the email and phone should be switched
Code:
<?php
session_start();
$num = $_SESSION['num'];
$firstname = $_SESSION['firstnameexport'];
$lastname = $_SESSION['lastnameexport'];
$email = $_SESSION['emailexport'];
$phone = $_SESSION['phoneexport'];
for($i =0; $i< $num; $i++){
$data[$i] = array(
"firstname" => $firstname[$i] , "lastname" => $lastname[$i], "email" => $email[$i], "phone" => $phone[$i]);
}
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
unset($_SESSION['num'],$_SESSION['firstnameexport'],$_SESSION['lastnameexport'],$_SESSION['emailexport'],$_SESSION['phoneexport']);
?>
Thank you for your time!
Fixed it - all I had to do was switch some of the session variables out so it would give the correct value for the right column.
Thank you for your time!
Am tryng to export data to csv file from mysql. I took the following script but the $result variable have error : mysql_num_fields tells the argument supplied is not valid
$filename = 'myfile.csv';
$result = db_query("SELECT * FROM {loreal_salons}");
drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
$count = mysql_num_fields($result);
for ($i = 0; $i < $count; $i++) {
$header[] = mysql_field_name($result, $i);
}
print implode(',', $header) . "\r\n";
while ($row = db_fetch_array($result)) {
foreach ($row as $value) {
$values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"';
}
print implode(',', $values) . "\r\n";
unset($values);
}
If you don't mind using a temporary file, you can do:
SELECT *
INTO OUTFILE '/tmp/myfile.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM loreal_salons
as your query, then simply do:
header('Content-type: text/csv');
header('Content-disposition: attachment; filename=myfile.csv');
readfile('/tmp/myfile.csv');
unlink('/tmp/myfile.csv');
exit();