<?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;
}
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.
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;
?>
I have created php coding to generate excel file. data are grab from SQL tables but the result are displayed with the HTML tags to the csv file. please see the attached image file which shows the output of below coding.
//genarate report
$out = '';
$filename_prefix = 'showroom_report';
$filename = $filename_prefix."_".$fromDate."-".$toDate;
$pay_array = array();
$showroom_array = array();
$location_id_array = array();
$pay_sql = "SELECT abans_crm.pay_mode.pay_mode,
Count(abans_crm.customers.purchase_type) AS mode_count,
abans_crm.customers.location_id
FROM
abans_crm.customers
INNER JOIN abans_crm.pay_mode ON abans_crm.customers.purchase_type = abans_crm.pay_mode.mode_id
WHERE
DATE(
abans_crm.customers.purchase_date
) >= '$fromDate'
AND DATE(
abans_crm.customers.purchase_date
) <= '$toDate'
GROUP BY
abans_crm.pay_mode.pay_mode";
$pay_result = mysql_query($pay_sql) or die(mysql_error());
if (mysql_num_rows($pay_result) > 0) {
while($row = mysql_fetch_assoc($pay_result)) {
array_push($pay_array, $row);
array_push($location_id_array, $row['location_id']);
}
}
$location_id_unique = array_unique($location_id_array);
$location_id_result = implode(", ", $location_id_unique);
//load showroom names
$showroom_sql = "SELECT
sh_sso.showrooms.showroom_id,
sh_sso.showrooms.showroom_name
FROM
sh_sso.showrooms
WHERE
sh_sso.showrooms.showroom_id IN ($location_id_result)";
$showroom_result = mysql_query($showroom_sql) or die(mysql_error());
while($row = mysql_fetch_assoc($showroom_result)){
array_push($showroom_array, $row);
}
echo "<table border=1 >\n";
echo "<thead><tr class=\"tableizer-firstrow\"><td colspan=6>Enquiries Report - $fromDate-to-$toDate</td></tr></thead><tbody>\n";
echo " <tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>\n";
echo " <tr><td>SHOWROOM</td><td colspan=4>PAYMENT METHOD</td><td rowspan=2>Total</td></tr>\n";
echo " <tr>"
. "<td> </td>"
. "<td>CASH</td>"
. "<td>CREDIT CARD</td>"
. "<td>HIRE PURCHASE</td>"
. "<td>LEASE</td>"
. "</tr>\n";
$cash_val = 0;
$credit_val = 0;
$hire_val = 0;
$lease_val = 0;
$row_total = 0;
for ($i=0; $i < count($showroom_array); $i++) {
$cash_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Cash');
$credit_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Credit Card');
$hire_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Hire Purchase');
$lease_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Lease');
include_once("../../../includes/sh_cms_functions.php");
$row_total = $row_total + $cash_val;
$row_total = $row_total + $credit_val;
$row_total = $row_total + $hire_val;
$row_total = $row_total + $lease_val;
echo "<tr>"
. "<td>".$showroom_array[$i]['showroom_name']."</td>"
. "<td>".$cash_val."</td>"
. "<td>".$credit_val."</td>"
. "<td>".$hire_val."</td>"
. "<td>".$lease_val."</td>"
. "<td>".$row_total."</td>"
. "</tr>\n";
$row_total = 0;
}
echo "</tbody></table>\n";
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-Encoding: UTF-8");
header("Content-type: text/csv; charset=UTF-8");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;
mysql_close();
}
above coding will generate CSV file.
You have HTML in the output, just simply remove it.
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;
}
?>
I am trying to export record from db to excel using PHP (Codeignitor) and then Import the same excel file again using PHP (Codignitor)
Export Code IS:
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename=' . date('d-m-Y') . '.xls');
$export .= '<table border="1">';
$export .= '<tr>';
$export .= '<td>Gate Name</td>';
$export .= '<td>ID</td>';
$export .= '<td>Name</td>';
$export .= '<td>Rank</td>';
$export .= '<td>Time</td>';
$export .= '<td>Entry Type</td>';
$export .= '<td>Work Place</td>';
$export .= '<td>Car Type</td>';
$export .= '<td>Car Number</td>';
$export .= '<td>Inspector Name</td>';
$export .= '</tr>';
foreach ($result as $row) {
$export .= '<tr>';
$export .= '<td>' . $row->gate_name . '</td>';
$export .= '<td>' . $row->soldier_id . '</td>';
$export .= '<td>' . $row->soldier_name . '</td>';
$export .= '<td>' . $row->soldier_rank . '</td>';
$export .= '<td>' . $row->time . '</td>';
$export .= '<td>' . $row->entry_type . '</td>';
$export .= '<td>' . $row->work_place . '</td>';
$export .= '<td>' . $row->vehicle_type . '</td>';
$export .= '<td>' . $row->vehicle_number . '</td>';
$export .= '<td>' . $row->inspector_name . '</td>';
$export .= '</tr>';
}
$export .= '</table>';
echo $export;
When I try to emport the downloaded file using This PHP Library - SimpleXLSX.
$SimpleXLSX = new SimpleXLSX($filename);
$data = $SimpleXLSX->rows();
the $data is empty
this library work if I create an excel file by self using MS Excel.
if I try to get file content by using
print_r(file_get_contents($filename));
It return the content with HTML code
Like
<table border="1">
<tr>
<td>Gate Name</td>
<td>ID</td>
<td>Name</td>
<td>Rank</td>
<td>Time</td>
<td>Entry Type</td>
<td>Work Place</td>
<td>Car Type</td>
<td>Car Number</td>
<td>Inspector Name</td>
</tr>
<tr>
<td>Gate 2</td>
<td>1111</td>
<td>فارس الغامدي</td>
<td>ملازم اول</td>
<td>28/02/1435 07:01:00</td>
<td>دخول</td>
<td>قطاع رفحاء</td>
<td>جيب</td>
<td>Tuy 124</td>
<td>عبدالله</td>
</tr>
</table>
I think the problem is with header() function or encoding when Creating Excel file.
Please help me.
Thanks.
SimpleXLSX will read XLSX files and print HTML code, but you cannot convert HTML code to XLSX format using SimpleXLSX. Here's an example of how to do it in PHPExcel:
<?php
$date = date("m-d-Y-g-i-s");
// Include and instantiate PHPExcel object.
include '../lib/PHPExcel/PHPExcel.php';
include '../lib/PHPExcel/PHPExcel/Writer/Excel2007.php';
$objPHPExcel = new PHPExcel();
// Set metadata.
$objPHPExcel->getProperties()->setTitle("Price List $date");
$objPHPExcel->getProperties()->setSubject("$date Price List");
$objPHPExcel->getProperties()->setDescription("The active price list for $date.");
// Set active sheet index at zero.
$objPHPExcel->setActiveSheetIndex(0);
// Determine limit and offset.
if($_GET['limit'] > 0 && $_GET['offset'] > 0) {
$limit = $_GET['limit'];
$offset = $_GET['offset'];
} else {
$limit = 10000;
$offset = 0;
}
// Query the database.
$query = mysql_query("SELECT * FROM `items` LIMIT $offset, $limit") or die(mysql_error());
$c = 0; // Initialize index at zero.
// Set column dimensions.
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
// Loop through data and insert it into their respective columns.
while($row = mysql_fetch_array($query)) {
$c++;
$objPHPExcel->getActiveSheet()->getCell("A$c")->setValueExplicit(stripslashes($row[strStock]), PHPExcel_Cell_DataType::TYPE_STRING);
$objPHPExcel->getActiveSheet()->SetCellValue("B$c", stripslashes(html_entity_decode($row[strDescription])));
$objPHPExcel->getActiveSheet()->SetCellValue("C$c", stripslashes($row[curPrice]));
}
$objPHPExcel->setActiveSheetIndex(0);
// Send headers to download XLSX file.
header('Content-Type: application/vnd.ms-excel');
if(isset($_GET[part]) && isset($_GET[of])) {
header('Content-Disposition: attachment;filename="Price List (Part '.$_GET[part].' of '.$_GET[of].') '.$date.'.xlsx"');
}
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');exit;
?>
Edit: Sorry, this is the code for PHPExcel, not SimpleXLSX. Here is the documentation for PHPExcel.