I am using WP_List_Table class to make a table at back end which fetches records from myCustomTable. Is there any feature/plugin available to export the single & multiple rows to CSV format. I have tried so many plugin but they all come up with the whole table export.
Thanks
yes you can do. this an an example of my code where i use to get the DB table to excel formate. you just replace the DB connection, table,table fields, and query as required this code may helps you
<?php
include '../common/inc.common.php';//db connectivity
$class=$_REQUEST['class_id'];//get the class id
$line .= "\n";
$filename='../app/class_export_student_hsc.csv';// file name
$fp = fopen($filename, "w");
$sql="SELECT t1 . * ,y.aca_year
FROM (
SELECT name,fathername,school_name,edu_disctrict,revenue_disctrict,nationality,religion,caste,castetype,gender,dob,dobword,mark1,stat
FROM **myCustomTable**
)t1, academic_years y
WHERE t1.academic_year=y.refid
AND t1.class =$class
";
$studentArray=$Cobj->run_query($sql);
$line = "";
foreach($studentArray as $name => $valuee) {
$comma = "";
foreach($valuee as $key2 => $value){
$line .= $comma . '"' . str_replace('"', '""', $key2) . '"';
$comma = ",";
}
$line .= "\n";
break;
}
foreach($studentArray as $name => $valuee) {
$comma = "";
foreach($valuee as $key2 => $value){
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
}
fputs($fp, $line);
fclose($fp);
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
}
?>
Related
Exporting MySQL Data to Excel File using the below code:
$i = 0;
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$rowData = '';
foreach ($row as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
$i++;
}
$filename = $i." numbers ".date('d m Y') . ".xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
It successfully exports the file and also opens correctly but there is a dialogue box before it file is opened.
When I use the extension as xlsx, the file is not opening and gives a dialogue box:
Why it is coming and how to remove it?
You have the wrong delimiters for a row use \r\n instead
$i = 0;
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$rowData = '';
foreach ($row as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\r\n";
$i++;
}
If you want you can try
implode("\t", array_values($row)) . "\r\n";
to get your complete rowData to add to setData, php ha sa lot of functions to explore
like implode and array_value.
anther think is , that you should add a header line before using the result of your select.
<?php
require_once("db_connect.php");
$arr = $_GET['arr'];
$selected_header = implode(', ', (array)$arr);
$sql = "SELECT $selected_header FROM release_ ORDER BY id DESC";
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename=CNC-'.date('Ymd').'.xls');
header('Pragma: no-cache');
header('Expires: 0');
$output = '';
$output .= '<table><tr>';
$header_arr = explode(',', $arr);
$len = count($header_arr);
for($a=0; $a<$len; $a++){
$output .= "<th style='width: 100px; text-align: center;'>" . $header_arr[$a] . "</th>";
}
$output .= '</tr>';
$res = mysqli_query($conn, $sql);
/*====this ruins everything=====*/
while($row = $res->fetch_assoc()){
$output = '<tr align="center">';
for($a=0; $a<$len; $a++){
$output .= "<td>" . $header_arr[$a] . "</td>";
}
echo "</tr>\t\n";
}
/*===============================*/
$output .= '</table>';
echo $output;
?>
I am able to get and display the header in the excel file but the content is not displaying at all. I get the whole string of row tag displayed. How am I able to display the data from the database to excel file. Please help.
I have done in my project(Cakephp) you can use like this own way :-
public function ExportToExcel(){
$users_id = $this->Session->read('selected_user_id');
$this->loadModel('User');
$conditions= array('User.usertype !='=>1);
if(!empty($users_id)){
$ids=explode(",",$users_id);
$conditions = array(
'User.id'=>$ids
);
}
$users = $this->User->find('all',array(
'conditions'=>$conditions,
'order'=>array('User.id Desc')
)
);
ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
$filename = "Users" . date("Y.m.d") . ".xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$i = 1;
$row="";
$row_header="S.No."."\t"."Name "."\t"."Email"."\t"."Mobile"."\t"."Address"."\t"."Status"."\n";
if(!empty($users)){
foreach($users as $user){
if($user['User']['status']==1){
$status = "Active";
}
else{
$status = "Inactive";
}
$row .= $i++."\t".$user['User']['firstname'].' '.$user['User']['lastname']
."\t".$user['User']['email']
."\t".$user['User']['phone_number']
."\t".$user['User']['address']
."\t".$status
."\n";
}
}
$this->Session->delete('selected_user_id');
echo($row_header);
echo($row);
die;
}
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;
?>
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();
Say I have stored a query in a variable called $query. I want to create small hyper link called "export as CSV" on the results page. How do i do this?
$query = "SELECT * FROM table_name";
$export = mysql_query ($query ) 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";
ehm ?
Export as CSV
and if you are looking for script wich can do this:
$myArray = array ();
$fp = fopen('export.csv', 'w');
foreach ($myArray as $line) {
fputcsv($fp, split(',', $line));
}
fclose($fp);
CSV = Comma Separated Values = Separate your Values with Commas
you have to echo / print your result line by line, separated with comma (,).
I assume your $query is the result set of your query, which is an associative array:
while($query = mysql_fetch_assoc($rs)) {
// loop till the end of records
echo $query["field1"] . "," . $query["field2"] . "," . $query["field3"] . "\r\n";
}
where $rs is the resource handle.
To let the browser pops up a download box, you must set the header at the beginning of the file (assume your file name is export.csv):
header("Expires: 0");
header("Cache-control: private");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=export.csv");
That's it!
p.s. This method won't leave a physical file in the server. If you intended to generate a file in the server, use traditional fopen and fwrite functions.