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

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 );

Related

How can I save image in subfolder using Amazon aws3 | Laravel

I am using aws to store my images and the code in the controller looks like this:
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public');
The images are being saved in my local storage.
Now though, I want to be able to create a subfolder to keep the images organized.
For my case, it is registering a business. Therefore I want the images to be stored in a subfolder containing the appropriate business id. I tried this:
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public/' . $business->id.
More about the controller is as follows:
$input = $request->all();
$files = isset($input['file']) ? $input['file'] : array ();
$business_names = json_decode($input['business_names'], true);
$business_details = json_decode($input['business_details']);
$share_amount = json_decode($input['share_amount'], true);
$entity = json_decode($input['entity'], true);
$directors = json_decode($input['directors'], true);
$shareholders = json_decode($input['shareholders'], true);
$appointments = json_decode($input['appointments'], true);
$input['user_id'] = Auth::user()->id;
Log::info(Auth::user());
Log::info($request->user());
/* Create Business Record */
$business = new Business;
$business->business_names = json_encode($business_names);
$business->share_amount = $share_amount ?: 0;
$business->entity = $entity ?: '';
$business->business_physical_address = json_encode($business_details->physical_address);
$business->has_business_postal_address = $business_details->has_postal_address;
$business->business_postal_address = json_encode($business_details->postal_address);
$business->user_id = $input['user_id'];
$business->save();
/* Create a new folder in storage/app/files named after the business ID */
Storage::makeDirectory('files/' . $business->id);
/* Upload Files */
// TODO: file storing?
foreach($files as $file) {
if ($file) {
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public/' . $business->id);
// $file->storeAs('files/' . $business->id, $file->getClientOriginalName());
}
}
When I try to save a business now, I see the following error:
C:\xampp\htdocs\startingabandbaby\vendor\league\flysystem\src\Adapter\Local.php(356):
Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8,
'Undefined index...', 'C:\xampp\htdocs...', 356, Array)
Since I was able to store images before, I am assuming that it is something to do with concatenating the business id.
How can I create a subfolder with the business id everytime I create a new business and add all the files in that same folder?
As per our discussion, you can use below 2 solutions:
1) put():
$path = Storage::disk('s3')->put(
'/files/'. $business->id, //path you want to upload image to S3
file_get_contents($request->file('file')), //fileContent
'public' //visibility
2) putFileAs(): To achieve the same thing withputFileAs(), I needed to write it as below. 1st parameter expects the directory name, I left it blank as I'm mimicking the directory name in s3 through the filename.
$path = Storage::disk('s3')->putFileAs(
'', // 1st parameter expects directory name, I left it blank as I'm mimicking the directory name through the filename
'/files/'. $business->id,
$request->file('file'), //3rd parameter file resource
['visibility' => 'public'] //options
);
Hope this will helps you!
After some research I ended up with the following:
$directory = 'public/' . $business->id;
Storage::disk()->makeDirectory($directory);
foreach($files as $file) {
if ($file) {
Storage::disk()->put($directory . '/' .$file->getClientOriginalName(), fopen($file, 'r+'));
}
}

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");

How to upload multiple images and store their name in database with laravel 5.1?

I have created a form for users can upload multiple images,and move uploaded images to 'Upload' folder and store their names in database. This is my code
public function multiple_upload() {
$multiupload = new Multiupload();
// getting all of the post data
$files = Input::file('images');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach($files as $file) {
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'uploads';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
$multiupload->fileimage = $filename;
$multiupload->save();
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('/');
}
else {
return Redirect::to('/')->withInput()->withErrors($validator);
}
}
After upload all images successfully move to 'Uploads' folder but, in database it store only one image name. So how to store all images name in database?
Please help me and thanks you for help.
The reason is that you are reusing the same Multiupload instance in your loop and just overwriting the saved name with the name of next file. You should be creating a new Multiupload instance for every file that gets uploaded.
As #edrzej.kurylo said
You have to add the below line to inside of foreach($files as $file) {
$multiupload = new Multiupload();
Because you are reusing the same Multiupload function again and again. You have to re initialize the Model for every time the loop runs.
You should move your $multiupload = new Multiupload(); into the foreach loop.
foreach($files as $file) {
$multiupload = new Multiupload();
}
I would use for loop in this manner:
if($request->hasFile('images'){
$files = $request->file('images');
for($i=0; $i<count($files); $i++){
$img = new SampleImage();
$name = rand().'.'.$files[$i]->getClientOriginalExtension();
$files[$i]->move('uploads/samples/',$name);
$img->image_name = $name;
$img->save();
}
}

LARAVEL How to get ID value on Auto Increment ID for naming file?

I am trying to renaming uploaded file to same as ID of table Slider for unique name
public function postAddSlider(){
$title = Input::get('title');
$image = Input::file('image');
$link = Input::get('link');
$description = Input::get('description');
$filename = $image->getClientOriginalName(); //<-- i want to change that filename to be id of table Slider
$uploadSuccess = Input::file('image')->move(base_path().'/public/assets/slider/', $filename);
if($uploadSuccess){
$slider = Slider::create(array(
'image' => $uploadSuccess->getRealPath(),
'title' => $title,
'link' => $link,
'description' => $description
));
if($slider){
return Redirect::route('slider-add-get')
->with('message','Slider Added Successfully');
}
}
else{
return Redirect::route('slider-add-get')
->with('message','File Upload Error');
}
}
or do you have other solution to renaming for unique name?
I have no idea what you're schema is like, but if you want to get the id of a model, you have to save it first.
Perhaps you could do something like this:
$slide = new Slide();
$slide->title = Input::get('title');
$slide->url = $temporaryurl;
...etc...
$slide->save();
//once the slide is saved, we can access its id
$slide->url = 'slide-' . $slide->id . $file->getClientOriginalExtension();
$slide->save(); //updates the new url
Or, if you're just looking to generate unique file names, you could use the original filename + the timestamp... Could possibly result in duplicates... very unlikely though (that 2 images would be uploaded with the same filename within the same second).
Or, perhaps, the slide title (stripped of illegal characters, spaces replaced with dashes, etc), plus the timestamp.

codeigniter export csv in windows platform

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.

Resources