I'm using matlab excel plugin for convert excel to array. My code is:-
public static function ImportExcel($table="", $path=""){
$data = array();
Excel::load($path, function ($reader) use($data) {
$data = $reader->toArray();
//here data has all excel data in array.
});
return $data; //but here it shows empty array.
}
Check my comments in code. Inside the Excel::load data has array of all data. But its scope is only inside the Excel::load. I need it outside.
The load has an internal function, thus the variables are enclosed inside that function and it also cannot access variables from outside this function, unless they are passed to the function with the use statement. In other words, $data inside the function does not reference to the $data outside it. In order to fix this you will have to add $data to the use statement like this:
public static function ImportExcel($table="", $path=""){
$data = array();
Excel::load($path, function ($reader) use($table, $data) {
$data = $reader->toArray();
//here data has all excel data in array.
});
return $data; //but here it shows empty array.
}
try this way
$data = Excel::load($path, function ($reader) use($table) {
$data = $reader->toArray();
//here data has all excel data in array.
});
otherwise create array before and after clousers
$array = [];
Excel::load($path, function ($reader) use($table, $array) {
$array = $reader->toArray();
//here data has all excel data in array.
});
third way doing like that
$results = Excel::load($path);
$data = $results->toArray();
I write an answer with more detail for another persons who wants to use Maatwebsite\Excel :
if ($request->hasFile('imported_file')){
$updateFile = $request->file('imported_file');
$path = $updateFile->getRealPath();
$fileExtension = $updateFile->getClientOriginalExtension();
$formats = ['xls', 'xlsx', 'ods', 'csv'];
if (! in_array($fileExtension, $formats)) {
return back()->with("status", 'The uploaded file format is not allowed.');
}
$data = Excel::load($path, function ($reader) {}, 'UTF-8')->get();
if (! empty($data) && $data->count()) {
$data = $data->toArray();
foreach ($data as $perData) {
// Do whatever you like on per data in your imported data
}
}
}
Related
I'm making an export data to excel based on employee_id filter, month and year of absence:
.
when the filter is submitted the data appears in the table below:
I have managed to get the data, but when the Download Excel button is clicked, the contents are just empty Excel, like this:
the data does not enter the excel.
My Controller:
public function rekapabsensiExcel(Request $request)
{
$idkaryawan = $request->id_karyawan;
$bulan = $request->query('bulan',Carbon::now()->format('m'));
$tahun = $request->query('tahun',Carbon::now()->format('Y'));
// simpan session
$idkaryawan = $request->session()->get('idkaryawan');
$bulan = $request->session()->get('bulan');
$tahun = $request->session()->get('tahun',);
// dd($idkaryawan,$bulan,$tahun );
if(isset($idkaryawan) && isset($bulan) && isset($tahun))
{
$data = Absensi::where('id_karyawan', $idkaryawan)
->whereMonth('tanggal', $bulan)
->whereYear('tanggal',$tahun)
->get();
// dd($data);
}else{
$data = Absensi::all();
}
return Excel::download(new RekapabsensiExport(['data'=>$data, 'idkaryawan'=>$idkaryawan]),'rekap_absensi_bulanan.xlsx');
}
My RekapAbsensiExport.php:
<?php
namespace App\Exports;
use App\Models\Absensi;
use Maatwebsite\Excel\Concerns\FromCollection;
class RekapabsensiExport implements FromCollection
{
protected $id_karyawan;
// function __construct($id_karyawan) {
// $this->id_karyawan = $id_karyawan;
// }
public function headings(): array {
return [
"No. ID","ID Karyawan","NIK","Tanggal","Jam Kerja","Jam Masuk","Jam Pulang",
"Scan Masuk","Scan Pulang","Normal","Riil","Terlambat","Plg Cepat","Absent",
"Lembur","Jml Jam Kerja","pengecualian","Harus C/I","Harus C/O","Departemen",
"Hari Normal","Akhir Pekan","Hari Libur","Jml Kehadiran","Lembur Hari Normal",
"Lembur Akhir Pekan","Lembur Hari Libur"
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return Absensi::where('id_karyawan',$this->id_karyawan)->get();
}
}
What part did I go wrong? Please help
Currently, you get no response to this statement because $this->id_karyawan is null as you have not properly passed the value through.
return Absensi::where('id_karyawan', $this->id_karyawan)->get();
Above, you are passing an array of values to the Export class. But your commented-out constructor function is only configured to accept a single parameter. If we stick to single parameters, you could do something like this.
return Excel::download(new RekapabsensiExport($data, $idkaryawan),'rekap_absensi_bulanan.xlsx');
Then your export constructor would look like this.
protected $data;
protected $id_karyawan;
function __construct($data, $id_karyawan) {
$this->data = $data;
$this->id_karyawan = $id_karyawan;
}
I'm getting all active countries via the service id country.repository
public function getCountries(Context $context): EntityCollection
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));
return $this->countryRepository->search($criteria, $context)->getEntities();
}
This gives me this CountryCollection:
How can I access each element to get the id and the name?
I tried to loop over
public function test($context): array
{
$countryIds = $this->getCountries($context);
$ids = [];
foreach ($countryIds as $countryId) {
$ids[] = $countryId['id'];
}
return $ids;
}
Obviously this doesn't work. It gives this error:
Cannot use object of type Shopware\Core\System\Country\CountryEntity
as array
If you are only interested in the ids of the countries you can use
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));
$ids = $this->countryRepository->searchIds($criteria, $context)->getIds();
searchIds() will only return the ids of the entities and not all of their properties, the benefit is that not all values have to be loaded from the DB and hydrated, therefore searchIds() is faster then the normal search().
You need to call the function like this
public function test($context): array
{
$countries = $this->getCountries($context);
$ids = [];
foreach ($countries as $country) {
$ids[] = $country->getId();//or $country->getName()
}
return $ids;
}
Usually you need to open the entity file. In your case it is CountryEntity.php to check the function to get the id or other fields there.
why when import excel, my data I added is not saved to the database ?
i import excel with type xlsx
My controller
public function importDataPegawai(Request $request)
{
Excel::import(new ImportPegawai, $request->file('upload-pegawai'));
return redirect('dashboard-admin')->with('success','Berhasil Upload Data Pegawai');
}
My Import
<?php
namespace App\Imports;
use App\Models\PegawaiModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Auth;
use DB;
class ImportPegawai implements ToModel, WithStartRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
foreach ($row as $data){
$data = DB::table('tbl_pegawai')->where('nip', $row[0])->get();
if (empty($data)) {
return new PegawaiModel([
'nip' => $row[0],
'nama_lengkap' => $row[1],
'pangkat' => $row[2],
'gol' => $row[3],
'jabatan' => $row[4],
'unit_kerja' => $row[5]
]);
}
}
}
public function startRow(): int
{
return 3;
}
}
When i dd($data) the result is like this
result dd
i got the data from my excel upload.
What's the problem ? why my data cannot save in the database
This code will return an Collection, which is an object, objects are always not empty.
DB::table('tbl_pegawai')->where('nip', $row[0])->get();
If you switch to first() it will return a model or null, effectively doing what you intended to.
DB::table('tbl_pegawai')->where('nip', $row[0])->first();
I have been in this situation before and figured that it can be caused by different factors. You might want to try the following:
Save the file you're about to upload to Excel 97-2003 Workbook format first.
Make sure the columns you're inserting data into is included in protected $fillable under App\PegawaiModel.
If certain cells in your spreadsheet are empty, make a validation for it.
Ex.
if ($row[0] === null) {
$row = null;
}
or if it's a string column that's not nullable, you can do
if ($row[0] === null) {
$row = 'NO DATA';
}
In my Excel sheet has a Gender column. I want to get only "Male" entries but when importing the data via maatwebsite, my code displays all the results.
How can I filter the results properly?
$data = Excel::load($path, function ($reader){
$results = $reader->get(array('user_url','gender'=>'Male')))->take(10);
if (!empty($results)) {
foreach ($results as $val => $link) {
$userid = $link['fb_unique_id'];
print_r($userid);
}
}
}
my code export into excel works fine, 1 to 10 rows export if I filters rows that my code export filtered rows as my criteria. If I click to next page e.g 11 to 20 and then click on export button, export only first page 1 to 10 rows.
in my admin view export button code:
<div id='menub'><?php $this->widget('zii.widgets.CMenu', array(
'encodeLabel'=>false,
'htmlOptions'=>array(
'class'=>'actions'),
'items'=>array(
array(
'label'=>'<img align="absmiddle" alt = "'.Yii::t('internationalization','Export'). '" src = "'.Yii::app()->request->baseUrl.'/images/export.jpg" />',
//'label'=>'Export',
'url'=>array('expenses/excel'),
),
),
));
above link call to excel method in expenses controller.
code in my controller:
public function actionExcel() {
$issueDataProvider = $_SESSION['report-excel'];
$i = 0;
$data = array();
//fix column header.
//Could have used something like this - $data[]=array_keys($issueDataProvider->data[0]->attributes);.
//But that would return all attributes which i do not want
//$data[]=array_keys($issueDataProvider->data[0]->attributes);
$data[$i]['expenses_type_id'] = 'Type';
$data[$i]['amount'] = 'Amount';
$data[$i]['exp_date'] = 'Date';
$data[$i]['description'] = 'Description';
$i++;
//populate data array with the required data elements
foreach($issueDataProvider->data as $issue)
{
$data[$i]['expenses_type_id'] = $issue->expensesType->name;
$data[$i]['amount'] = $issue['amount'];
$data[$i]['exp_date'] = $issue['exp_date'];
$data[$i]['description'] = $issue['description'];
$i++;
}
Yii::import('application.extensions.phpexcel.JPhpExcel');
$xls = new JPhpExcel('UTF-8', false, 'test');
$xls->addArray($data);
$xls->generateXML('test_file');
}
I save data in
$_SESSION['report-excel']
and in my Model:
public function getSearchCriteria()
{
$criteria=new CDbCriteria;
if(!empty($this->from_date) && empty($this->to_date))
{
$criteria->condition = "exp_date >= '$this->from_date'"; // date is database date column field
}elseif(!empty($this->to_date) && empty($this->from_date))
{
$criteria->condition = "exp_date <= '$this->to_date'";
}elseif(!empty($this->to_date) && !empty($this->from_date))
{
$criteria->condition = "exp_date >= '$this->from_date' and exp_date <= '$this->to_date'";
}
$criteria->with = 'expensesType';
$criteria->join = 'LEFT JOIN expenses_type p ON t.expenses_type_id = p.id';
//s$criteria->compare('id',$this->id,true);
$criteria->compare('p.name',$this->expenses_type_id,true);
$criteria->compare('amount',$this->amount,true);
$criteria->compare('exp_date',$this->exp_date,true);
$criteria->compare('description',$this->description,true);
$criteria->order ='exp_date DESC';
return $criteria;
}
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$data = new CActiveDataProvider(get_class($this), array(
'pagination'=>array('pageSize'=> Yii::app()->user->getState('pageSize',
Yii::app()->params['defaultPageSize']),),
'criteria'=>$this->getSearchCriteria(),
));
$_SESSION['report-excel']=$data;
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$this->getSearchCriteria(),
));
every thing is works fine but on pagination.
kindly help.
CActiveDataProvider holds a set of items(all).So when you call actionExcel() the $page param is lost. So when you do actionAdmin() in your controller or search() in your model save your $_GET['page'] to an other session value. then set it when you do actionExcel().
$_GET['page'] = $_SESSION['your_session_page_value'];
Hope this helps
Best Regards