I'm building an application in Laravel 5.5, with matwebsite/excel plugin where I'm having an array element to be exported into csv file. I'm able to get the values when I assign single string to key inside an array, but currently I have child array element which is present into the array, which is giving me blank excel sheet once included the same.
Without array elements:
public function investor(Request $request)
{
$record_set = [];
$tables = json_decode($request->investorTable);
foreach($tables as $table)
{
$record_set[] = array(
'schedule' => $table->schedule,
'Event type' => $table->event_type,
'Venue' => $table->venue,
'Nature' => $table->nature,
);
}
return Excel::create('investor', function($excel) use ($record_set) {
$excel->sheet('mySheet', function($sheet) use ($record_set) {
$sheet->fromArray($record_set);
});
})->download('csv');
}
this is working perfect but I want to place an array element whose name key I want to export, I don't know how to implement when I implement it it gives me blank sheet,
$record_set[] = array(
'schedule' => $table->schedule,
'Company Name' => $table->companyName,
'Contact Person' => $table->contact_participants,
'Event type' => $table->event_type,
'Venue' => $table->venue,
'Nature' => $table->nature,
);
my complete array element is something like this:
and the table looks into my html something like this:
I want exactly same output in excel, help me out with this.
Thanks.
You can use
Export to Excel5 (xls)
Excel::create('Filename', function($excel) {
})->export('xls');
// or
Export to Excel2007 (xlsx)
->download('xls');
Export to Excel2007 (xlsx)
->export('xlsx');
// or
->download('xlsx');
Export to CSV
Export to CSV
->export('csv');
// or
->download('csv');
Please refer that documentation
http://www.maatwebsite.nl/laravel-excel/docs/export
Related
i'm using maatwebsite laravel excel to import some data from excel to database. But i want to add some custom ID with incremental value for each row of data.
For now, i'm able to import data with some input value form together.
DataImport file
class DataImport implements ToModel, WithStartRow{
public function model(array $row)
{
return new Tempdat([
'employee_id' => ??? (combination of client_code +1)
'name' => $row[1],
'gender' => $row[2],
'bod' => $this->transformDate($row[3]),
'engagement_code' => request('engagement_code'), //from input form
'client_code' => request('client_code'), //from input form
]);
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
public function startRow(): int
{
return 2;
} }
DataController file
public function ImportExcel(Request $request)
{
$this->validate($request,[
'file' => 'required|mimes:xls,xlsx',
'engagement_code' => 'required',
]);
$file = $request->file('file');
$clientCode = request('client_code');
$engagementCode = request('engagement_code');
$todayDate = date('dFY');
$file_name = $engagementCode.'_'.$todayDate.$file->getClientOriginalName();
$file->move('tempdat',$file_name);
Excel::import(new DataImport, public_path('/tempdat/'.$file_name));
return redirect()->route('dashboard.tempdat.index');
}
What i'd like to do is to add "employee code" which is combination of "client_code" + 1 for every row. for example if client_code is ABCD and there is 3 rows of data imported then the employee_code will be :
ABCD0001
ABCD0002
ABCD0003
...
i'm already searching for count rows but nothing found yet.
Counting rows will bring you problems whenever you remove a single record from the table: You won't be able to insert new rows if your primary employee_id field has UNIQUE key, or you will start inserting duplicated IDs.
Generating the ID in PHP isn't my recomendation either since you could face integrity problems if two records are trying to be stored simultaneously.
I would use the default model's model_id field with autoincrement to make sure that I won't have problems with id assignation, and inmediatly after saving the record I would update the id for the employee_id field which can be also keyed as "primary" in order to be indexed and accessed efficiently.
For example:
class MyModel extends Model {
public function save() {
if(parent::save()) {
$this->update['employee_id' => "ABCD".$this->id];
}
}
}
I haven't still realized how the Excel library you're using handles the model, but I supposed it can be specified somewhere along the process.
I am able to generate incremental id in laravel excel using this:
https://github.com/haruncpi/laravel-id-generator
$config = [
'table' => 'table_name',
'length' => 7,
'field' => 'employee_id',
'prefix' => request('client_code'),
'reset_on_prefix_change' => true,
];
$employee_id = IdGenerator::generate($config);
so, everytime import executed, employee_id will generated on its own following with client_code prefix (ex: ABCD001, ... )
How can I save an array of data into individual rows in Laravel ?
Here's how my UI looks like
once i click the save button in the controller Store function gets the data
public function store(Request $request, $venue, CustomProduct $customProduct)
{
dd($request->Availability);
}
This is how the data looks like
I'm wondering how can i save this to my database ?
This is how my database table looks like
Please suggest me a way that i can save this to my table
Use this example:
$days = ["monday","thursday","wednesday","tuesday","friday","saturday","sunday"];
forach($request->Availability as $key => $value){
CustomProductAvalibility::create([
'day_id' => array_search($key), // array_search($key) returns day id
'starts_at' => $value["start"],
'ends_at' => $value["end"],
'custom_product_id' => '...' // your custom product id
]);
}
I have a model called CroppedDocumentField, that have below $casts setup:
protected $casts = [
'content' => 'array'
];
The migration looks like this:
Schema::create('cropped_document_fields', function(Blueprint $table){
$table->increments('id');
$table->unsignedInteger('document_id');
$table->json('content')->nullable();
});
In my database, the content column seems to be stored like a string:
"{\"1\": [{\"row\": \"Bill Tc\\n\"}, {\"row\": \"Nathar\\n\"}, {\"row\": \"75839\\n\"}]}"
If I echo that out:
$document = CroppedDocumentField::Find(56);
dd(is_array($document->content));
This returns false.
When I insert the JSON to my database, I read it from a .txt file, that contains the JSON string:
{"1": [{"row": "Bill Tc\n"}, {"row": "Nathar\n"}, {"row": "75839\n"}]}
Then I insert it:
$file = "mytext.txt";
$content = file_get_contents($file);
//Add the text content
$this->document->cropped()->create([
'content' => $content
]);
In my document model, I simply have a relationship to the CroppedDocumentField model:
//Document.php:
public function cropped()
{
return $this->hasMany(CroppedDocumentField::class);
}
What am I doing wrong here?
I tried casting json to array on my project and it worked as expected, what I believe the problem is the way you store the content. Please try changing it to this and let me know:
//Add the text content
$this->document->cropped()->create([
'content' => json_decode($content) // convert string to json
]);
So basically got laravel project and got to export tables in excel. I'm using this for the export. Till now i only export from array or in my case.
public function exportGames()
{
$export = Games::all();
Excel::create('Games Data', function($excel) use($export){
$excel->sheet('Games', function($sheet) use($export){
$sheet->fromArray($export);
});
})->export('xlsx');
}
This however returns full table data, which include some field I to be gone (timestamps etc.). Also relational tables is not possible to display (only in the actual table on the page). Spend hours in the documentation still don't understand how to do it. Wanna rip my hair off. How do modify columns to export. Thanks in advice.
Seems simple enough:
$export = Games::select(['client_game_id', 'client_game_name', 'gameid', 'description', 'game_type', 'db_name', 'short_name'])->get();
You'll only see those columns in your exported XLS file.
You can do this way
$export = Games::all();
Excel::create('Games Data', function($excel) use($export){
$excel->sheet('Games', function($sheet) use($export){
foreach ($export as $key => $value) {
$exports[] = array('email' => $value['email'], 'name' =>$value['name']);
}
$sheet->fromArray($exports);
});
})->export('xlsx');
I have an array of arrays of data.
so the basic format is
$sheet = array(
array(
'a1 data',
'b1 data',
'c1 data',
'd1 data',
),
array(
'a2 data',
'b2 data',
'c2 data',
'd2 data',
),
array(
'a3 data',
'b3 data',
'c3 data',
'd3 data',
)
);
When I am passed the array I have no idea how many columns or rows there will be.
What I want to do is using php excel create an excel sheet out of the array.
from what I have seen, the only way to set data is to use
$objPHPExcel->getActiveSheet()->setCellValue('A1', $value);
So my question is
How would you loop over the cells?
remembering that there could be say 30 columns and say 70 rows which would be AD70 So, how do you loop that?
Or is there a built in function to turn an array to a sheet?
You can set the data from an array like so:
$objPHPExcel->getActiveSheet()->fromArray($sheet, null, 'A1');
fromArray works with 2D arrays. Where the 1st argument is the 2D array, the second argument is what to use if there is a null value, and the last argument is where the top left corner should be.
Otherwise you would need to loop through the data:
$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
foreach($columns as $column => $data) {
$worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
}
}
$rowID = 1;
foreach($sheet as $rowArray) {
$columnID = 'A';
foreach($rowArray as $columnValue) {
$objPHPExcel->getActiveSheet()->setCellValue($columnID.$rowID, $columnValue);
$columnID++;
}
$rowID++;
}
or
$objPHPExcel->getActiveSheet()->fromArray($sheet);
As far as I know, you don't need to know the height and width of the final Excel worksheet when populating a worksheet using PHP excel. You can just use a nested foreach loop to read all the nested arrays and use appropriate variables to build up the cell references and add them to the worksheet. The plugin will handle the size.