codeigniter export csv in windows platform - codeigniter

function export_csv(){
$this->load->helper('csv');
if(isset($_POST['term_val'])&&$_POST['term_val']<>'0'){
$term = $this->Search_model->get_term($_POST['term_val']);
$term = json_decode($term);
}else{
$term=array();
}
$orders = $this->Order_model->get_orders_export($term,'place_order');
if(count($orders)>0){
foreach($orders as $order){
$sublist['order_id']= $order->order_number;
$sublist['ship_to']= $order->ship_firstname.' '.$order->ship_lastname;
$sublist['order_date']= date('d-m-Y H:i:s',strtotime($order->ordered_on));
$sublist['email_to']= $order->ship_email;
$sublist['city']= $order->ship_city;
$sublist['pincode']= $order->ship_zip;
$sublist['ship_address']= $order->ship_address1.' , '.$order->ship_address2;
$sublist['phone']= $order->ship_phone;
$sublist['product_name']= $order->name;
$sublist['product_id']= $order->product_id;
$sublist['status']= $order->status;
$sublist1[]= $sublist;
}
$delimiter = ";";
$newline = "\r\n";
$heading[]=array('order_id'=>'Order Id','ship_to'=>'Ship To','order_date'=>'Order Date','email_to'=>'Email To',
'city'=>'City','pincode'=>'Pincode','ship_address'=>'Ship Address','phone'=>'Phone','product_name'=>'Product Name','product_id'=>'Product ID','status'=>'status');
$get_csv=array_to_csv1($sublist1,$heading,$delimiter, $newline);
ob_start();
$filename = "orders_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
// header("Content-type: text/x-csv");
//header("Content-type: text/csv");
// header("Content-type: application/csv");
// header("Content-Disposition: attachment; filename=orders".date('d-M-Y').".csv");
print_r($get_csv);
}else{
redirect($this->config->item('admin_folder').'/orders');
}
}
The above code is the controller function for export CSV and the image is the action taking place when exporting.
Problem : Actually if we export csv using codeigniter it is showing that image as shown above. If we press export csv using codeigniter it it should not show that image , it should directly export csv into excel .

if you want to generate reports in csv format it is very easy with codeigniter. Your model function
function index(){
return $query = $this->db->get('my_table');
//Here you should note i am returning
//the query object instead of
//$query->result() or $query->result_array()
}
Now in controller
function get_report(){
$this->load->model('my_model');
$this->load->dbutil();
$this->load->helper('file');
// get the object
$report = $this->my_model->index();
//pass it to db utility function
$new_report = $this->dbutil->csv_from_result($report);
//Now use it to write file. write_file helper function will do it
write_file('csv_file.csv',$new_report);
//Done
}
No externals are required everything is available in Codeigntier.
The above method will force the file to be downloaded instead of
being opening. Cheers! If you want to write xml file it is easy too.
Just use xml_from_result() method of dbutil and use write_file('xml_file.xml,$new_report)
Visit these links they will help.
Database Utility Class
And
File Helper

***> 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.

Related

want to generate pdf from laravel request data

i tried to generate pdf from my request data function. but it can't pass variable into my pdf generate function. i get requested data from this function.
public function fetch_data()
{
if(request()->ajax())
{
if(request()->from_date != '' && request()->to_date != '')
{
$data = DB::table('sales')
->whereBetween('dlvd_date', array(request()->from_date, request()->to_date))
->get();
} else {
$data = DB::table('sales')->orderBy('dlvd_date', 'desc')->get();
}
echo json_encode($data);
}
}
i want to get this $data value into my pdf generated function like below.
function convert_sales_data_to_html($data)
{
$sales_data = $data;
dd($sales_data);
$output = '';
return $output;
}
and pass to this function
public function pdf($data)
{
$pdf = \App::make('dompdf.wrapper');
$pdf->loadHTML($this->convert_sales_data_to_html($data))->setPaper('a4', 'landscape');
return $pdf->stream();
}
i tried this so many times but show me errors with missing argument. how can i fix this or have another method to generate pdf from requested data in laravel.
this is my routes
Route::post('salesreport/fetch', 'Report\SalesReportController#fetch_data')->name('salesreport.fetch_data');
Route::get('salesreport/pdf', 'Report\SalesReportController#pdf');

Laravel: export searched data to the excel

I want to export searched data to the laravel below is my controller
public function getUsageData(Request $request)
{
$start_date = $request->get('start_date');
$end_date = $request->get('end_date');
$particulars = DB::table('particulars')
->join('reqs', 'particulars.particular_id', "=", 'reqs.particular_id')
->whereBetween('date_applied', [$start_date, $end_date])
->select('particulars.item_name', 'particulars.unit', 'particulars.price', 'reqs.quantity_issued',
DB::raw('particulars.price*reqs.quantity_issued AS total_cost'))
->get();
if ($particulars->isEmpty()) {
return "No Records Found...................... ";
} else {
$pdf = PDF::loadView('issuer.getUsageReport', ['particulars' => $particulars]);
return $pdf->stream('getUsageReport.issuer');
}
}
I want to retrieve those data to the excel instead of pdf please help
Replace the two PDF lines in the else { ... } statement with:
$list = $particulars->toArray();
//This line adds headers if present in your data
array_unshift($list, array_keys($list[0]));
$callback = function() use ($list) {
$FH = fopen('php://output', 'w');
foreach ($list as $row) {
fputcsv($FH, $row);
}
fclose($FH);
};
return response()->streamDownload($callback,"filename.csv");
Depending on the structure of particulars you may need to do some manipulation to the data first, e.g. flattening. Comment below if so.

force_download not working in codeigniter after writing

tried to auto download file after file created but its not working. file creating and appending data perfectly but download functionality not working
public function getexportfile(){
$this->load->dbutil();
// $this->load->database('DB_utility','dbutil');
//$this->load->helper('download_helper','download');
$this->load->helper('download_helper');
$this->load->helper('file');
error_reporting(0);
ini_set('display_errors', 0);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
## Condition Start
$sWhere = " where condition"; // where conditon
$date = date('Y-m-d');
$filename = 'app/logs/othermarketplace_'.$date.'.csv';
$data = $this->PMP->export($sWhere); // calling model
$result = $this->dbutil->csv_from_result($data);
write_file($filename,$result); // file creating write data perfectly
$data = file_get_contents($filename);
//$path = file_get_contents(base_url().$filename);
//$name = "othermarketplace_'.$date.'.csv";
//force_download($nme, $pth);
force_download($filename,$data);
}
anything i missed?
From docs:
// Contents of photo.jpg will be automatically read
force_download('/path/to/photo.jpg', NULL);
//$data = file_get_contents($filename);
//$path = file_get_contents(base_url().$filename);
//$name = "othermarketplace_'.$date.'.csv";
//force_download($nme, $pth);
if (!is_file($filename)) {
exit('No file found.');
}
force_download($filename, NULL);
Note:
These lines might be doing something weird. Perhaps remove them as they aren't being used:
error_reporting(0);
ini_set('display_errors', 0);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

Creating a Dynamic PDF and Saving it in a folder using Loop with MYSQL and Codeigniter

This is the public function with looping (Edited)
public function generate_salary_slip(){
$this->load->helper('file');
$this->load->library('m_pdf');
$data = [];
$slip = $this->Admin_Login_Model->generate_salary_slip();
//$html = array();
$html='';
if(!empty($slip)){
foreach($slip as $slip_list){
$id = $slip_list->emp_id;
$data['attendance'] = $this->Admin_Login_Model->get_slip_attendance($id);
$data['emp_profile'] = $this->Admin_Login_Model->get_emp_details($id);
$data['late_day'] = $this->Admin_Login_Model->get_late_days($id);
$data['half_days'] = $this->Admin_Login_Model->get_half_days($id);
$data['salary'] = $this->Admin_Login_Model->get_salary_slip($id);
$data['second_half'] = $this->Admin_Login_Model->get_half_Second_days($id);
//$html=$this->load->view('admin/payslip',$data);
$pdfFilePath = date("F_Y")."salary_slip.pdf";
$html .= $this->load->view('admin/payslip', $data, true);
}
$htmlval = $html;
//echo $html;exit;
$this->m_pdf->pdf->WriteHTML($htmlval);
$this->m_pdf->pdf->Output('salary_slips/'.$pdfFilePath, "F");
$this->session->set_flashdata('success','Salary slips saved in directory!');
redirect('admin_attendance_list');
}else{
$this->session->set_flashdata('message','Salary slips not available for this month!');
redirect('admin_attendance_list');
}
}
File is getting saved in the folder, but Only with the First Record. Also, Repeated loop is getting generated, but with same record.
How to create a HTML by loop.
PS: Using MPDF to generate PDF File
Any hep will be highly appreciated.
You need to take the render, writeHtml and Output calls outside the forech loop, there is you problem.
You could save all the data in a var and then render the HTML as you are doing now and then generate the PDF.
EDIT: Your code should look something like this (please read comments below):
$htmlData = array();
if(!empty($slip)){
foreach ($slip as $slip_list) {
//
$htmlData[] = $data;
}
$pdfFilePath = date("F_Y")."salary_slip.pdf";
$html = $this->load->view('admin/payslip', $htmlData, true);
$this->m_pdf->pdf->WriteHTML($html);
$this->m_pdf->pdf->Output('salary_slips/'.$pdfFilePath, "F");

Kohana 3.2 + PHPExcel creates empty document when there are more than 31 rows written.

I'm trying to create a simple excel document that contains a 3-column list. (First Name, Last Name, Email Address)
When I output more than 31 rows, a blank excel file is created. Does anyone know how to fix it?
My code below:
$guests = ORM::factory('guest')
->order_by('last_name', 'ASC')
->find_all()
->as_array();
$columns = array('first_name', 'last_name', 'email');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator('Me')
->setLastModifiedBy('Me)
->setTitle('Guest List')
->setSubject('Guest List')
->setDescription('Title of Report, run on ' . date('m/d/Y H:i:s'));
$objPHPExcel->createSheet(0);
$objPHPExcel->setActiveSheetIndex(0);
foreach($guests as $row => $guest) {
$source = array();
$column = 0;
$next_row = $objPHPExcel->getActiveSheet()->getHighestRow();
foreach($guest->as_array() as $column_name => $data) {
if(in_array($column_name, $columns)) {
$objPHPExcel->getActiveSheet()
->setCellValueByColumnAndRow($column, $next_row+1, $data);
$column++;
// unset($data);
}
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$this->response->body($objWriter->save('php://output'));
$this->response->send_file(TRUE, 'GuestList.xls');
Kohana has a hard time handling the rendered file using the send_file() method, so write the file to disk using the built-in method from PHPExcel. Then use Kohana to deliver the saved file as a download.
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($filename, 'EXCEL2007');
$this->response->send_file( DOCROOT.$filename );

Resources