I'm trying to export a csv file with Maatwebsite\Excel and Laravel 9.
As a response, I get my datas and headings in console > network , but no download occurs.
Here's my code :
Exports
namespace App\Exports;
use App\Models\Data;
use Illuminate\Support\Facades\Schema;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
class DataExport implements FromCollection, WithHeadings
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return Data::all();
}
public function headings():array{
return[
Schema::getColumnListing('data')
];
}
}
And my controller (1st try) :
public function download_file_csv()
{
Excel::store(new DataExport, 'dataTemplate.csv');
Excel::download(new DataExport,'dataTemplate.csv',\Maatwebsite\Excel\Excel::CSV, [
'Content-Type' => 'text/csv',
]);
}
and 2nd try
public function download_file_csv()
{
Excel::store(new DataExport, 'dataTemplate.csv');
return Excel::download(new DataExport,'dataTemplate.csv');
}
The file with datas and headings is properly stored in my public folder...
Thanks in advance,
Related
Dotrying to export my daanswerdata through laravel excel. https://docs.laravel-excel.com/3.1/getting-started/- this is the documentation I used for reference. At first, it is running successfully, but when I open the exported file, it exports the path of the image instead of exporting the actual images. Is there a way to export the image(the png file)?
This is exported file
this is the local path folder where the image saved
this is how its look like in my database .
here is my code:
1.Export.php
<?php
namespace App\Exports;
use App\Models\signature;
use Maatwebsite\Excel\Concerns\FromCollection;
//frow laravel excel drawing(image export)
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
class SignatureExport implements FromCollection, WithHeadings, WithColumnWidths
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return signature::all();
}
public function drawings()
{
$drawing = new Drawing();
$drawing->setName('signature');
$drawing->setDescription('This is my signatuer');
$drawing->setPath(public_path('/uploads/signatures'));
$drawing->setHeight(90);
$drawing->setCoordinates('D1');
return $drawing;
}
public function headings(): array
{
return [
'id',
'name',
'description',
'signature',
'created_at',
'updated_at',
];
}
public function columnWidths(): array
{
return [
'A' => 30,
'B' => 30,
'C' => 30,
'D' => 30,
'E' => 30,
];
}
}
2.Export Controller
public function exportexcel()
{
return Excel::download(new SignatureExport, 'signaturelist.xlsx');
}
Do I miss anything? any answer is appreciated.
problem solved with the answers that are being accepted .
but ther is new problem came out
instead of 3 image , only 1 image exported sucessfully
<?php
namespace App\Exports;
use App\Models\signature;
use Maatwebsite\Excel\Concerns\FromCollection;
//frow laravel excel drawing(image export)
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use Maatwebsite\Excel\Concerns\WithDrawings;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
class SignatureExport implements FromCollection, WithHeadings, WithColumnWidths, WithDrawings
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return signature::all();
}
public function drawings()
{
$drawing = new Drawing();
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('signature');
$drawing->setDescription('This is my signatuer');
$drawing->setPath(public_path('/uploads/signatures/62ac8a575af1a.png'));
$drawing->setHeight(90);
$drawing->setCoordinates('D1');
return $drawing;
}
public function headings(): array
{
return [
'id',
'name',
'description',
'signature',
'created_at',
'updated_at',
];
}
public function columnWidths(): array
{
return [
'A' => 30,
'B' => 30,
'C' => 30,
'D' => 30,
'E' => 30,
];
}
}
what should i do to get all image being exported?
In your SignatureExport class file you are missing the WithDrawings implements
class SignatureExport implements WithDrawings //like this
So your SignatureExport class should look something like this
class SignatureExport implements FromCollection, WithHeadings, WithColumnWidths, WithDrawings
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
This import is just to instance $drawing = new Drawing(); object.
For the export file to work you will need to add withDrawing concerns like you are adding WithHeadings and others
I am fixing an existing Symfony 5.4 website running on PHP 8.0.18. The back office is handled by EasyAdmin 3.4.
I can't figure out what's wrong. Like the title says, when I go to edit an "Event" entity, the save buttons won't work at all unless I re-upload a different event picture. No amount of editing the other fields will work, and I can use the save buttons on other entities even if I have made no modification to the entity. I've looked though my configuration and entity setup but so far, I don't get it.
Edit: other entities with ImageField also refuse to be updated unless I've re-uploaded something. I found a temporaty fix by using setRequired(false) in the event crud conf, but an image is definitely required in this case, so I'm just setting myself up for a different kind of failure if I'm not mistaken. Is this really the only way?
Event entity:
<?php
namespace App\Entity;
use App\Repository\EventRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=EventRepository::class)
*/
class Event
{
// ...
/**
* #ORM\Column(type="string", length=255)
*/
private $src;
// ...
public function getSrc(): ?string
{
return $this->src;
}
public function setSrc(string $src): self
{
$this->src = $src;
return $this;
}
// ...
}
Event crud controller:
<?php
namespace App\Controller\Admin;
use App\Entity\Event;
use App\Entity\TranslationString;
use App\Entity\TranslationText;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
class EventCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return Event::class;
}
public function configureCrud(Crud $crud): Crud
{
return $crud
->setSearchFields([
'date',
'end',
'title.fr',
'title.en',
'body.fr',
'body.en',
'alt.fr',
'alt.en',
])
->setDefaultSort(['archived' => 'ASC','date' => 'DESC',]);
}
public function configureFields(string $pageName): iterable
{
return [
DateField::new('date'),
DateField::new('end'),
TextField::new('titleFr'),
TextField::new('titleEn')->hideOnIndex(),
BooleanField::new('isShow'),
BooleanField::new('archived'),
TextareaField::new('bodyFr'),
TextareaField::new('bodyEn')->hideOnIndex(),
ImageField::new('src')
->setBasePath('img/events')
->setUploadDir('www/img/events'),
TextareaField::new('altFr')->hideOnIndex(),
TextareaField::new('altEn')->hideOnIndex(),
];
}
public function createEntity(string $Fqcn): Event
{
return (new Event)
->setAlt(new TranslationText)
->setTitle(new TranslationString)
->setBody(new TranslationText);
}
}
I had the same problem and I think that the following code will help
public function configureFields(string $pageName): iterable {
$imageField = ImageField::new('image', 'Image')->setUploadDir('public/uploads/images/')->setBasePath('uploads/images/');
if ($pageName != 'new') {
$imageField->setRequired(false);
}
return [
TextField::new('title'),
$imageField,
TextEditorField::new('description')->setNumOfRows(20),
UrlField::new('ticketOfficeLink'),
AssociationField::new('eventStates')
];
}
I have to export excel by joining two tables but I can't understand the way to complete this I'll attach the screenshot of my tables and codes. Please help me to solve these issues.
Table One: Decoration
Table Two: Decoration Price
Sample Data
Decoration.php Model Page
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Decoration extends Model
{
protected $table='decoration';
protected $fillable=['deco_print_type','deco_prod_code','deco_supp_code','deco_name','deco_logo_setup_charge','deco_main_type','deco_is_main_type','deco_weight_for_sorting','deco_priority','deco_is_shown_to_clients'];
public static function getDecoration()
{
$Decoration = DB::table('decoration')
->select('deco_print_type','deco_name','deco_prod_code','deco_priority','deco_rank','deco_logo_setup_charge','deco_is_shown_to_clients')
->where('deco_flag','=','1')->orderBy('deco_print_type','ASC')->get()->toArray();
foreach ($Decoration as $deco)
{
$decoPrice = DB::table('decoration_price')
->select('decp_quantity','decp_quantity')
->where('decp_print_type','=',$deco->deco_print_type)
->orderBy('decp_qty_break_leve','ASC')->get()->toArray();
//$Decoration[$i]=$decoPrice;
}
return $Decoration;
}
}
Exports/DecorationExport.php Page code
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Facades\DB;
use App\Decoration;
use App\Decoration_Price;
class DecorationExport implements FromCollection,WithHeadings
{
public function headings(): array
{
// TODO: Implement headings() method.
return [
"Decoration code",
"Decoration name",
"Main decoration",
"Priority",
"Rank",
"Setup Charge",
"Shown_to_clients",
"A2",
"B2",
"A3",
"B3",
"A4",
"B4",
"A5",
"B5",
"A6",
"B6",
"A7",
"B7",
"A8",
"B8",
"A9",
"B9",
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return collect(Decoration::getDecoration());
}
}
Decoration Route Function for download
public function DecoBulkExport()
{
$decoration = new DecorationExport;
return Excel::download($decoration,'Decoration.csv');
}
When I click the export button data file should become like this.
Please Help me or advise me on how to do this
I use laravel-excel version 3.1 .
my code is :
class UsersExport implements FromView
{
private $users;
public function __construct()
{
$this->users = User::query()->select('name' , 'family' , 'mobile' ,'national_code' , 'email' , 'registered_from')->get();
}
public function view(): View
{
return view('test', [
'users' => $this->users
]);
}
}
In my controller I called vies function:
return (new UsersExport())->view();
here I got a view (html page) not excel spreadsheet. what should I do?
You need to add use Exportable; in your UserExport class, then call return (new UsersExport())->download('something.xls');
P. S. It is not a good idea to write query in UserExport constructor. It would be better to get them before calling it, then pass to your new UserExport()
I am using model factories in NewsTableSeeder, but I get this error when I entered db:seed.
I want to know why I can't use create() in my seeder.
Here is my News model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $table = 'news';
protected $primaryKey = 'id';
public function home_news_lists() {
return $this->select('id', 'news_title', 'news_update')
->orderBy('news_update', 'DESC')
->limit(5)
->get();
}
public function lists() {
return News::all();
}
}
Model Factories:
$factory->define(App\Models\News::class, function (Faker\Generator $faker)
{
static $password;
$faker = $faker->create('zh_TW');
return [
'news_title' => $faker->sentence(),
'news_content' => $faker->paragraph(),
'news_author' => $faker->name(),
'news_pageviews' => $faker->numberBetween(1, 100),
'news_file' => ' ',
'news_img' => $faker->imageUrl($width, $height, 'business'),
'created_at' => $faker->dateTimeBetween('2012', 'now', 'zh_TW'),
'updated_at' => $faker->dateTimeBetween('2015', 'now', 'zh_TW')
];
});
NewsTableSeeder :
<?php
use Illuminate\Database\Seeder;
class NewsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Models\News::class, 50)->create();
}
}
I can't tell 100% without seeing exactly the error you got, but I do believe there is no create() method on the $faker object.
I believe what you mean to do is:
$factory->define(App\Models\News::class, function (Faker\Generator $faker)
{
static $password;
$faker = \Faker\Factory::create('zh_TW'); // change to this
return [
...
];
}
I would just create a new faker generator (\Faker\Generator) that gets returned from calling \Faker\Factory::create($locale) and use that instead. Otherwise, I believe your next best option is to override wherever Laravel instantiates the \Faker\Generator $faker object that gets passed into the callback, but that may get hacky if Laravel doesn't provide a clean way to do it.
The create() method is a static call on the \Faker\Factory method. It accepts a locale as the parameter and uses en_US as the default locale.
$faker = $faker->create('zh_TW');
The error message said this code is wrong.
What is your purpose to use this code?