CodeIgniter: Export data from database into excel and download - php

I'm working on a project, that requires exporting data from MYSQL DB depending on the multiple conditions. I am referring this:
This is my source code:
public function exportExcelData($records)
{
$heading = false;
if (!empty($records))
foreach ($records as $row) {
if (!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "\n";
$heading = true;
}
echo implode("\t", ($row)) . "\n";
}
}
public function fetchDataFromTable()
{
$query =$this->db->get('one_piece_characters'); // fetch Data from table
$allData = $query->result_array(); // this will return all data into array
$dataToExports = [];
foreach ($allData as $data) {
$arrangeData['Charater Name'] = $data['name'];
$arrangeData['Charater Profile'] = $data['profile'];
$arrangeData['Charater Desc'] = $data['description'];
$dataToExports[] = $arrangeData;
}
// set header
$filename = "dataToExport.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
$this->exportExcelData($dataToExports);
}
If I use it without any where clause, it is giving entire table.
If i use only single where clause, it works good.
Bur, if I use multiple where conditions. it gives me a blank excel sheet.
Does anyone have any idea regarding how to make it work with multiple where conditions?

Try using this code on your model file:
function createcsv(){
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename.csv";
$query = "SELECT * FROM YourTable"; //USE HERE YOUR QUERY
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
}

// ecport contect list in csv ,
public function cnt_explode(){
$csvData[] =array( "Name", "Email Id","Mobile No.","Event", "City","location","No of guest","Event Date","Budget",
"Venue Type","Food","Drink","Description","Date");
$data = $this->contact_model->get_contact(NULL);
foreach($data as $cnt){
$csvData[]=array(
$cnt->name ,$cnt->email, $cnt->mobile_no, $cnt->event, $cnt->city, $cnt->location, $cnt->no_guest,$cnt->event_date,$cnt->budget, $cnt->venue_type,
$cnt->food, $cnt->drink, $cnt->description,$cnt->created_on,
);
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=venuexpo_".time().".csv");
header("Content-Transfer-Encoding: binary");
$df = fopen("php://output", 'w');
array_walk($csvData, function($row) use ($df) {
fputcsv($df, $row);
});
fclose($df);
}
///------------ downlode csv done --------------

Related

Pull customer data into all columns in a csv file

This is my current code which pulls all data into a single column. I would like it
to pull data into its own column. Thanks for any help
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
foreach ($query as $k=>$v) {
$_csv_data= $v["email"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["first_name"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["business"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["phone_no"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["shipping_address"]. "\n";
fwrite( $fp, $_csv_data );
}
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
This is my first post on here and I've found all the info here very informative. Thanks for all you do.
EDIT:
Here is the current code with the syntax error
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
# let's get keys into an order that you like
$fields = array('email','first_name','business','phone_no','shipping_address');
foreach ($query as $k=>$v) {
// put the fields for this row into an array
foreach ($fields as $field) {
$data[] = $v[$field];
}
fputcsv($fp, $data);
unset($data);
}
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
For CSVs, instead of fwrite, you can use fputcsv, you just pass it an array of columns to insert in the row.
$array = array('column one contents', 'column two contents');
fputcsv($fp, $array);
I would suggest looking into fputcsv.
php manual
It looks like your code was looping through all the data, printing out the email. Then looping again and printing out the first_name... I haven't tested it, but this uses fputcsv to write the file - I changed only those parts of the code.
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
# let's get keys into an order that you like
$fields = array('email','first_name','business','phone_no','shipping_address');
foreach ($query as $k=>$v) {
// put the fields for this row into an array
foreach ($fields as $field) {
$data[] = $v[$field];
}
$lines[] = $data; // add the row of data to $lines
unset($data);
}
fputcsv($fp, $lines);
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>

create CSV in a different name if file already exists

i have been creating a CSV by using array of data, currently it returns an error if a CSV already exists in the same location.
therefore is there a possibility where i could let it create another in the same location.
example : if theres a csv called report.csv to create a new one with auto generated name like report(1).csv
code
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary");
fclose($fp);
working example finally.. thank you for your ideas
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
if(file_exists($basePath) == false){
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
}
else{
$time_start = time();
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report"."#".$time_start.".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
}

Download csv from codeigniter mysql

I think I'm missing something obvious. I'm trying to export a dataset from a MySQL query to CSV without printing it to the browser.
Here's my code:
<?php
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);
?>
$stories is my array created from the MySQL query.
Currently everything prints to the browser with no errors and no download but I would like to force a CSV download. How can I do this?
final working code:
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output');
$name = 'data.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
You can call model CSV() from your controller as
$this->load->model('Users_model');
$this->Users_model->csv();
and in the model
function csv()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$query = $this->db->query("SELECT * FROM Users");
$delimiter = ",";
$newline = "\r\n";
$data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
force_download('CSV_Report.csv', $data);
}
Your File will start downloading
I can't tell what headers are set from the Codeigniter force_download() function sets. If it is indeed going to the screen I would suspect the necessary headers are missing. You can add the below headers to your code to set correct csv dowload headers (The cache control will ensure fresh data download each time:
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.$name);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
i am use this and its work
header('Content-Type: text/csv; charset=utf-8');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header("Content-Disposition: attachment; filename=backup" . date('y-m-d') . ".csv");
header('Last-Modified: ' . date('D M j G:i:s T Y'));
$outss = fopen("php://output", "w");
$this->db->order_by('ID', 'DESC');
$query = $this->db->get('urls');
foreach ($query->result_array() as $rows) {
fputcsv($outss, $rows);
}
fclose($outss);
return;
If you are trying to generate reports in csv format then it will quite easy with codeigniter.
Place this code in your Controller
function get_report()
{
$this->load->model('Main_Model');
$this->load->dbutil();
$this->load->helper('file');
/* get the object */
$report = $this->Main_Model->print_report();
$delimiter = ",";
$newline = "\r\n";
$new_report = $this->dbutil->csv_from_result($report, $delimiter, $newline);
write_file( 'application/third_party/file.csv', $new_report);
$this->load->view('report_success.php');
}
Put this code into Model
public function print_report()
{
return $query = $this->db->query("SELECT * FROM Table_name");
}
report_success.php is just Successful Notification.
Your Report is being Exported. Thank you
Finally Your "file.csv" is generated.
its basically stored at physical storage.
In CodeIgniter/application/third-party/file.csv
it works.
it will help you.
Here we have sample result set from MySQL and want to export in CSV file.
Step 1: Get MySql data in key value pair.
$data = array(
'0' => array('Name'=> 'Parvez', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
'1' => array('Name'=> 'Alam', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
'2' => array('Name'=> 'Sunnay', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
'3' => array('Name'=> 'Amir', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
'4' => array('Name'=> 'Amir1', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
'5' => array('Name'=> 'Amir2', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
);
Step 2: PHP code to get options type and force to browser download file instead of display.
if(isset($_POST["ExportType"]))
{
switch($_POST["ExportType"])
{
case "export-to-csv" :
// Submission from
$filename = $_POST["ExportType"] . ".csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
ExportCSVFile($data);
//$_POST["ExportType"] = '';
exit();
default :
die("Unknown action : ".$_POST["action"]);
break;
}
}
function ExportCSVFile($records) {
// create a file pointer connected to the output stream
$fh = fopen( 'php://output', 'w' );
$heading = false;
if(!empty($records))
foreach($records as $row) {
if(!$heading) {
// output the column headings
fputcsv($fh, array_keys($row));
$heading = true;
}
// loop over the rows, outputting them
fputcsv($fh, array_values($row));
}
fclose($fh);
}
Step 3: Define html layout for display data in table and button to fire export-to-csv action.
<div>Export to csv</div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="export-form">
<input type="hidden" value='' id='hidden-type' name='ExportType'/>
</form>
<table id="" class="table table-striped table-bordered">
<tr>
<th>Name</th>
<th>Status</th>
<th>Priority</th>
<th>Salary</th>
</tr>
<tbody>
<?php foreach($data as $row):?>
<tr>
<td><?php echo $row ['Name']?></td>
<td><?php echo $row ['Status']?></td>
<td><?php echo $row ['Priority']?></td>
<td><?php echo $row ['Salary']?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Step 3: Now we will use jQuery code to get click event.
<script type="text/javascript">
$(document).ready(function() {
jQuery('#export-to-csv').bind("click", function() {
var target = $(this).attr('id');
switch(target) {
case 'export-to-csv' :
$('#hidden-type').val(target);
//alert($('#hidden-type').val());
$('#export-form').submit();
$('#hidden-type').val('');
break
}
});
});
</script>

Add heading on export using fputcsv php

I am trying to export db rows using fputcsv() in csv file. how i can add heading on first, center align then columns then data my code works well without heading. I know there is many api's but is this possible with in my code.
Here is my code:-
Enquiry Report
id name class func
1 rk ba call()
2 bk bd that()
function exportdata_to_excel($details) {
// filename for download
$filename = date("Y-m-d").".csv";
header('Content-Type: text/csv');
header("Content-Disposition: attachment; filename=\"$filename\"");
$out = fopen("php://output", 'w');
$flag = false;
//$result = $orderDetails;
while($row = mysql_fetch_assoc($details)) {
$arr =array('Enquiry id'=>$row['id'],'Date'=>$row['created_on'],'Name'=>$row['name'], 'Email'=>$row['email'], 'Telephone'=>$row['telephone'], 'Customer Request'=>$row['customer_request'], 'Special Request'=>$row['special_request']);
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($arr), ',', '"');
$flag = true;
}
fputcsv($out, array_values($arr), ',', '"');
}
fclose($out);
exit();
}
This worked for me.
function downloadCSV($data)
{
$filename = date("Y-m-d").".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: UTF-8");
$f = fopen('php://output', 'a');
fputcsv($f, array_keys($data[0]));
foreach ($data as $row)
{
fputcsv($f, $row);
}
fclose($f);
}
Try this after opening the file, you want to write in e.g. i want to write a file at below path:
$fp = fopen('csvfiles/myfile.csv','w')
You have to enter headers separately, so for this make an array of headers like:
$csv_fields=array();
$csv_fields[] = 'Enquiry id';
$csv_fields[] = 'Date';
$csv_fields[] = 'Name';
$csv_fields[] = 'Email';
$csv_fields[] = 'Telephone';
$csv_fields[] = 'Customer Request';
$csv_fields[] = 'Special Request';
After making headers add these headers to the file.
fputcsv($fp, $csv_fields);
while($row = mysql_fetch_assoc($details)) {
fputcsv($fp,$row);
}
fclose($fp);
Also add following headers on top so that file can be viewed easily:
header("content-type: application/force-download");
header('Content-Type: application/csv');
header('Pragma: no-cache');

Laravel 3 create Text (CSV) file

Hello I am trying to grab all the emails from the database, then output them into a text (comma separated) file. Here is what I have done but does not work:
public function get_textfile() {
$emails = Staff::get('email');
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.txt"');
$stream = fopen("php://output", 'w');
foreach($emails as $email) {
fputcsv($stream, $email, ',');
}
fclose($outstream);
}
return (something)?
getting this: Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.
This is my route:
Route::get('textfile', array('as' => 'textfile','uses' => 'admin#textfile'));
try file_put_contents($filename, implode(',', Staff::get('email')));
Collect all of your data into a string and then output it like this:
$data = '';
foreach ($emails as $email)
{
// If you want 1 email per line
$data .= '"'.$email.'"'.PHP_EOL;
// If you want all emails on 1 line
$data .= '"'.$email.'",';
}
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=My Cool File.csv');
header('Pragma: no-cache');
header('Expires: 0');
echo $data;

Categories