I am exporting a list from my database using PHPExcel.
But the cells are not evenly spaced as shown in image.
Question: How can I make sure that each cell is automatically evenly spaced in PHPExcel
I have tried the answers here but not work properly
PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically
Controller Code
<?php
class Events extends MX_Controller {
private $error = array();
public function __construct() {
parent::__construct();
}
public function generate_excel() {
$query = $this->db->get('event');
$excelresults = $query->result_array();
require (APPPATH . 'third_party/PHPExcel-1.8/Classes/PHPExcel.php');
require (APPPATH . 'third_party/PHPExcel-1.8/Classes/PHPExcel/Writer/Excel2007.php');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("");
$objPHPExcel->getProperties()->setLastModifiedBy("");
$objPHPExcel->getProperties()->setSubject("");
$objPHPExcel->getProperties()->setCreator("");
$objPHPExcel->getProperties()->setDescription("");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue("A1", 'Event');
$objPHPExcel->getActiveSheet()->SetCellValue("B1", 'Event Title');
$objPHPExcel->getActiveSheet()->SetCellValue("C1", 'Event Date');
$objPHPExcel->getActiveSheet()->SetCellValue("D1", 'Event Start Time');
$excelrow = 2;
foreach ($excelresults as $excelresult => $excelvalue) {
$objPHPExcel->getActiveSheet()->SetCellValue("A" . $excelrow, $excelvalue['event']);
$objPHPExcel->getActiveSheet()->SetCellValue("B" . $excelrow, $excelvalue['event_title']);
$objPHPExcel->getActiveSheet()->SetCellValue("C" . $excelrow, $excelvalue['event_date']);
$objPHPExcel->getActiveSheet()->SetCellValue("D" . $excelrow, $excelvalue['event_start_time']);
$excelrow++;
}
$filename = 'Bowling-Events-For ' . date('Y') . '.xlsx';
$objPHPExcel->getProperties()->setTitle("Riwaka Bowling Club Events");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' .$filename. '"');
header('Cache-Control: max-age=0');
$Writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$Writer->save('php://output');
exit;
}
}
Solved found solution
Did some more google searching from answer here
PHPExcel auto size column width
foreach (range('A', $objPHPExcel->getActiveSheet()->getHighestDataColumn()) as $col) {
$objPHPExcel->getActiveSheet()
->getColumnDimension($col)
->setAutoSize(true);
}
Related
I am attempting to send out an email anytime a woocommerce product has its images changed in any way.
I started off by attempting to get the $_POST of the image gallery, but I think I am calling it the wrong thing… I have tried the following:
$images = $_POST[‘image_ids’];
$images = $_POST[‘gallery_image_ids’];
Then I am comparing that value to the current image ids:
$oldImages = $product->get_gallery_image_ids();
If they do not match I am using wp_mail to send an email to various people.
I am doing all this inside a custom php function using:
add_action(‘pre_post_update’, ‘content_change_email’, 10, 2);
function content_change_email($post_ID, $data)
{
}
I assume the problem is originating with the
$images = $_POST[‘image_ids’];
$images = $_POST[‘gallery_image_ids’];
part of the code.
Can someone let me know what the correct meta field name for the gallery images is?
I solved my own problem…
I used a custom meta field to record the IDs for all the images, including the featured image then compared that to the current gallery images to see if they had changed, if they did then update the custom meta value with the new numbers and send an email to let people know the pictures changed.
code is as follows:
// send email when images change for a product
add_action( 'woocommerce_update_product', 'imagecheck_on_product_save', 10, 1 );
function imagecheck_on_product_save( $product_id ) {
$product = wc_get_product( $product_id );
// do something with this product
$metaImages = get_post_meta( $product_id, '_gallery_image_ids', true );
$currentImages = $product->get_gallery_image_ids();
$imageIDs = get_post_thumbnail_id( $product_id );
if ($imagesIDs != "" )
{
$imageIDs = $imageIDs . ", ";
foreach($currentImages as $value){
$imageIDs = $imageIDs . $value . ", ";
}
if ( $metaImages != $imageIDs ) {
update_post_meta( $product_id, '_gallery_image_ids', esc_attr( $imageIDs ) );
global $current_user;
wp_get_current_user();
$email = $current_user->user_email;
$lastuser = $current_user->user_firstname;
if ( $product->get_sku() != "" )
{
$memail = "<pre>USER: " . $lastuser . " made the following changes:</br>
Meta gallery images: " . $metaImages . "</br>
</br>
Actual gallery images: " . $imageIDs . "
" . $memail . "</pre>";
$headers = array('Content-Type: text/html; charset=UTF-8');
$subject = "PICTURES CHANGED - SKU: " . $product->get_sku();
$to = "(insert who you want to send to here)";
wp_mail( $to, $subject, $memail, $headers );
}
}
}
}
I'm new in Laravel. I attached my code whenever I update the form it gives same error. Please check my code throughly and let me know where is the error.
public function updateCategory(Request $request) {
$catname = $request->catname;
if($catimg = $request->hasFile('updatecatimg')) {
File::cleanDirectory(public_path().'/images/'.$catname);
$catimg = $request->file('updatecatimg');
$catimgnm = $catimg->getClientOriginalName();
$storeTo = public_path() . '/images/' . $catname;
File::makeDirectory($storeTo, $mode = 0777, true, true);
$catimg->move($storeTo, $catimgnm);
}
Category::where('cat_id', $request->catid)->update(['cat_name' => $catname, 'cat_img' => $catimgnm, 'status' => $request->status]);
return back();
}
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AddCategory extends Model
{
protected $table = 'cms_category';
protected $primaryKey = 'cat_id';
}
Folder
DB
Error
please help me...
Here is your updated answer. Category::findOrFail() will find the category object, using it, we can update specific field only and use save() function to update the object.
public function updateCategory(Request $request)
{
$catId = $request->catid;
$category = Category::findOrFail($catId);
$oldCategory = $category->cat_name;
rename(public_path() . '/images/' . $oldCategory, public_path() . '/images/' . $request->catname);
$category->cat_name = $request->catname;
if ($request->hasFile('updatecatimg')) {
File::cleanDirectory(public_path() . '/images/' . $request->catname);
$catImg = $request->file('updatecatimg');
$category->cat_img = $catImg->getClientOriginalName();
$storeTo = public_path() . '/images/' . $request->catname;
File::makeDirectory($storeTo, $mode = 0777, true, true);
$catImg->move($storeTo, $request->catname);
}
$category->save();
return back();
}
You should try this code.
This is your edit file
<input type="hidden" name="old_image" id="old_image"
value="{{isset($contact->cat_img)?$contact->cat_img:''}}">
After:
use File;
public function updateCategory(Request $request) {
if ($request->hasFile('updatecatimg')){
$image_path = public_path('/images/'.$request->old_image);
if(File::exists($image_path)){
unlink($image_path);
}
$file = $request->file('updatecatimg');
$catimgnm = $file->getClientOriginalName();
$destinationPath = public_path('/images/');
$file->move($destinationPath, $catimgnm );
$contact = "YOUR MODEL NAME"::find($request->cat_id);
$contact->cat_img =$catimgnm ;
$contact->save();
}
}
I hope this code is working in your Controllers.
I am trying to use image url instead of base64. i kindof figured a way how to get images out of the editor and save it inside the directory, but i am trying to insert it into database. i get this error.
Object of class DOMElement could not be converted to string
below i have added the store function inside my controller
public function store(Request $request)
{
//
$data = $request->all();
if (!$request->has('published')) {
$data['published'] = 0;
} else {
$data['published'] = 1;
}
if (!$request->has('featured')) {
$data['featured'] = 0;
} else {
$data['featured'] = 1;
}
$img = null;
if ($request->hasfile('title_img')) {
$image = $request->file('title_img');
$name = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . '/uploads/blogs/', $name);
$img = '/uploads/blogs/' . $name;
}
/* summernote */
$detail=$data['description'];
$dom = new \DomDocument();
$dom->loadHtml($detail, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
$data = $img->getAttribute('src');
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name= "/uploads/summernote/" . time().$k.'.jpeg';
$path = public_path() . $image_name;
file_put_contents($path, $data);
$img->removeAttribute('src');
$img->setAttribute('src', $image_name);
}
$detail = $dom->saveHTML();
/* summernote */
$data['title_img'] = $img;
$data['user_id'] = auth()->user()->id;
$title = $data['title'];
$data['slug'] = Str::slug($title);
auth()->user()->posts()->create($data);
return Redirect::route('admin.blog.index')->withSuccess('Whoopie!! New Blog Added!');
}
I hope i can get some help regarding this. Thanks in advance
I am using DOMPDF to generate invoices.
1 invoice at time is perfect.
But i want to print (from a while) all invoices between date
all is perfect
But Dompdf print only the last invoice.
The dompdf code
require_once("dompdf_config.inc.php");
$date1 = "2008-01-01";
$date2 = "2009-01-01";
$user = "User_1";
$sql=mysql_query("SELECT * FROM invoices WHERE datum BETWEEN '$date1' AND '$date2' AND user='$user' ORDER BY nummer ");
while ($rows=mysql_fetch_array($sql))
{
$num=$rows[number];
$datum=$rows[data];
$pay=$rows[pay];
// Need to get the user info from other table
$Query2 = "SELECT * from user WHERE user='$user'";
while ($rows2=mysql_fetch_array($Result2))
{
$name = $rows2[name];
//ETC...
// Now we generate the html invoice
$html =
'<html><body>'.
//the invoice html
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
}
}
$dompdf->stream("Invoice.pdf");
I want to get all invoices ( sometimes 5, sometimes 50 ) in 1 pdf file.
How to ?
I close my whiles at end of files, but don't help.
Hope you can help.
The way your code is written right now you render your first document then don't do anything with it. So the second pass through the while loop will overwrite the first pass. There are a few ways to achieve what you want, but the easiest would be to compile all your HTML into a single document then render that.
Using your code as a start:
require_once("dompdf_config.inc.php");
$date1 = "2008-01-01";
$date2 = "2009-01-01";
$user = "User_1";
$invoices = array();
$sql=mysql_query("SELECT * FROM invoices WHERE datum BETWEEN '$date1' AND '$date2' AND user='$user' ORDER BY nummer ");
while ($rows=mysql_fetch_array($sql)) {
$num=$rows[number];
$datum=$rows[data];
$pay=$rows[pay];
// Need to get the user info from other table
$Query2 = "SELECT * from user WHERE user='$user'";
while ($rows2=mysql_fetch_array($Result2)) {
$name = $rows2[name];
//ETC...
// Force page break between invoices
if ( strlen( $html ) > 0 ) { $html .= '<div style="page-break-before: always;"></div>'; }
// Now we generate the html invoice
$invoices[] = '<!-- the html invoice -->';
}
}
$html = '<html><body>' . implode( '<div style="page-break-before: always;"></div>' , $invoices ) . '</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("Invoice.pdf");
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.