本文整理汇总了PHP中Maatwebsite\Excel\Facades\Excel::filter方法的典型用法代码示例。如果您正苦于以下问题:PHP Excel::filter方法的具体用法?PHP Excel::filter怎么用?PHP Excel::filter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Maatwebsite\Excel\Facades\Excel
的用法示例。
在下文中一共展示了Excel::filter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: importdata
public function importdata(Request $request)
{
$results = null;
// $results = $reader->get();
//
// $ret = $results->toArray();
$file = $request->file('exelimport');
$request->file('exelimport')->move(storage_path() . '/public/import/', 'import.xlsx');
//$request->file('exelimport')
// $results = Excel::load($request->file('exelimport'))->toArray();
$ret = Excel::filter('chunk')->load(storage_path('/public/import/import.xlsx'))->chunk(250, function ($results) {
$data = array();
// $results = $reader->toArray();
foreach ($results as $index => $value) {
// $EMP_ID = $value["emp_id"];
// $PERIOD = $value["period"];
// $user = DB::table('TBL_MEMBER_BENEFITS')->where('EMP_ID', $EMP_ID)->where('PERIOD', $PERIOD)->count();
// $allquery = "SELECT COUNT(EMP_ID) AS total FROM TBL_MEMBER_BENEFITS WHERE EMP_ID= '".$EMP_ID."' AND (PERIOD='".$PERIOD."' OR PERIOD IS NULL)";
// $all = DB::select(DB::raw($allquery));
// $total = $all[0]->total;
$date = new Date();
// array_push($data,'asd','asda');
// if ($total == 0) {
array_push($data, array('EMP_ID' => $value["emp_id"], 'INVESTMENT_PLAN' => $value["investment_plan"], 'EQUITY' => $value["equity"], 'DEBT' => $value["debt"], 'EQUITY_FUNDS' => $value["equity_funds"], 'BOND_FUNDS' => $value["bond_funds"], 'INVESTMENT_MONEY' => $value["investment_money"], 'REFERENCE_DATE' => $value["reference_date"], 'MEMBER_STATUS' => $value["member_status"], 'CREATE_DATE' => $date));
// }
}
// var_dump($data);
DB::table('TBL_INFORMATION_FROM_ASSET')->insert($data);
//DB::insert(DB::raw($insert));
});
return response()->json(array('success' => true, 'html' => $ret));
}
示例2: importdata
public function importdata(Request $request)
{
$results = null;
// $results = $reader->get();
//
// $ret = $results->toArray();
$file = $request->file('exelimport');
$request->file('exelimport')->move(storage_path() . '/public/import/', 'import.xlsx');
//$request->file('exelimport')
// $results = Excel::load($request->file('exelimport'))->toArray();
$ret = Excel::filter('chunk')->load(storage_path('/public/import/import.xlsx'))->chunk(250, function ($results) {
$data = array();
// $results = $reader->toArray();
foreach ($results as $index => $value) {
$EMP_ID = $value["emp_id"];
$PERIOD = $value["period"];
// $user = DB::table('TBL_MEMBER_BENEFITS')->where('EMP_ID', $EMP_ID)->where('PERIOD', $PERIOD)->count();
$allquery = "SELECT COUNT(EMP_ID) AS total FROM TBL_MEMBER_BENEFITS WHERE EMP_ID= '" . $EMP_ID . "' AND (PERIOD='" . $PERIOD . "' OR PERIOD IS NULL)";
$all = DB::select(DB::raw($allquery));
$total = $all[0]->total;
// array_push($data,'asd','asda');
if ($total == 0) {
array_push($data, array('EMP_ID' => $value["emp_id"], 'FULL_NAME' => $value["full_name"], 'PATH_CODE' => $value["path_code"], 'DEP_CODE' => $value["dep_code"], 'DIV_CODE' => $value["div_code"], 'SEC_CODE' => $value["sec_code"], 'PATH_NAME' => $value["path_name"], 'DEP_NAME' => $value["dep_name"], 'DIV_NAME' => $value["div_name"], 'SEC_NAME' => $value["sec_name"], 'HIRE_DATE' => $value["hire_date"], 'END_DATE' => $value["end_date"], 'POSITION_CODE' => $value["position_code"], 'POSITION_NAME' => $value["position_name"], 'JOB_LINE' => $value["job_line"], 'LEVEL_CODE' => $value["level_code"], 'EXE_NAME' => $value["exe_name"], 'EXE1_NAME' => $value["exe1_name"], 'AGE_YEAR' => $value["age_year"], 'AGE_DAY' => $value["age_day"], 'JOB_YEAR' => $value["job_year"], 'JOB_DAY' => $value["job_day"], 'EMPLOYER_CONTRIBUTION_1' => $value["employer_contribution_1"], 'EMPLOYER_EARNING_2' => $value["employer_earning_2"], 'MEMBER_CONTRIBUTION_3' => $value["member_contribution_3"], 'MEMBER_EARNING_4' => $value["member_earning_4"], 'TAX_1' => $value["tax_1"], 'TAX_12' => $value["tax_12"], 'TAX_124' => $value["tax_124"], 'TAX_1234' => $value["tax_1234"], 'GRATUITY' => $value["gratuity"], 'GRATUITY_TAX' => $value["gratuity_tax"], 'RECORD_DATE' => $value["record_date"], 'PERIOD' => $value["period"]));
}
}
// var_dump($data);
DB::table('TBL_MEMBER_BENEFITS')->insert($data);
//DB::insert(DB::raw($insert));
});
return response()->json(array('success' => true, 'html' => $ret));
}
示例3: importdata
public function importdata(Request $request)
{
$results = null;
// $results = $reader->get();
//
// $ret = $results->toArray();
$file = $request->file('exelimport');
$request->file('exelimport')->move(storage_path() . '/public/import/', 'import.xlsx');
//$request->file('exelimport')
// $results = Excel::load($request->file('exelimport'))->toArray();
$ret = Excel::filter('chunk')->load(storage_path('/public/import/import.xlsx'))->chunk(250, function ($results) {
$data = array();
foreach ($results as $index => $value) {
//
$im_date_start = $value["change_saving_rate_date"];
$ret_data_start = str_replace("'", "", $im_date_start);
$im_date_modify = $value["effective_date"];
$ret_data_modify = str_replace("'", "", $im_date_modify);
// var_dump($ret_data_start);
$date_start = new Date($ret_data_start);
$date_modify = new Date($ret_data_modify);
$EMP_ID = $value["emp_id"];
// $PERIOD = $value["period"];
$allquery = "SELECT COUNT(EMP_ID) AS total FROM TBL_USER_SAVING_RATE WHERE EMP_ID= '" . $EMP_ID . "' AND CHANGE_SAVING_RATE_DATE='" . $date_start . "'";
$all = DB::select(DB::raw($allquery));
$total = $all[0]->total;
if ($total == 0) {
array_push($data, array('EMP_ID' => $value["emp_id"], 'USER_SAVING_RATE' => $value["user_saving_rate"], 'CHANGE_SAVING_RATE_DATE' => $date_start, 'EFFECTIVE_DATE' => $date_modify, 'MODIFY_COUNT' => $value["modify_count"], 'MODIFY_BY' => $value["modify_by"]));
}
}
DB::table('TBL_USER_SAVING_RATE')->insert($data);
});
return response()->json(array('success' => true, 'html' => $ret));
}
示例4: importdata
public function importdata(Request $request)
{
$results = null;
// $results = $reader->get();
//
// $ret = $results->toArray();
$file = $request->file('exelimport');
$request->file('exelimport')->move(storage_path() . '/public/import/', 'import.xlsx');
//$request->file('exelimport')
// $results = Excel::load($request->file('exelimport'))->toArray();
$ret = Excel::filter('chunk')->load(storage_path('/public/import/import.xlsx'))->chunk(250, function ($results) {
foreach ($results as $index => $value) {
//
// $rest = substr("abcdef", -1); // returns "f"
// $rest = substr("abcdef", -2); // returns "ef"
// $rest = substr("abcdef", -3, 1);
$im_date_start = $value["contribution_start_date"];
$ret_data_start = str_replace("'", "", $im_date_start);
$im_date_end = $value["contribution_end_date"];
$ret_data_end = str_replace("'", "", $im_date_end);
$im_date_modify = $value["contribution_modify_date"];
$ret_data_modify = str_replace("'", "", $im_date_modify);
// var_dump($ret_data_start);
// var_dump($ret_data_start);
$date_start = new Date($ret_data_start);
$date_end = new Date($ret_data_end);
$date_modify = new Date($ret_data_modify);
$update = array('EMP_ID' => $value["emp_id"], 'CONTRIBUTION_START_DATE' => $date_start, 'CONTRIBUTION_END_DATE' => $date_end, 'CONTRIBUTION_MODIFY_DATE' => $date_modify, 'CONTRIBUTION_RATE_OLD' => $value["contribution_rate_old"], 'CONTRIBUTION_RATE_NEW' => $value["contribution_rate_new"]);
DB::table('TBL_EMPLOYEE_INFO')->where('EMP_ID', "=", $value["emp_id"])->update($update);
}
});
return response()->json(array('success' => true, 'html' => $ret));
}
示例5: importData
/**
*
*/
public function importData($url, $program_id, $feed_id, $custom_categorie)
{
$fileLocation = storage_path() . '/' . $program_id . '.' . $feed_id . '.csv';
$this->downloadAndSaveFeed($url, $fileLocation);
$this->filterBestand($fileLocation);
$chunkSize = Config::get('daisycon.chunksize', 500);
Excel::filter('chunk')->load($fileLocation)->chunk($chunkSize, function ($results) use($program_id, $feed_id, $custom_categorie) {
foreach ($results as $row) {
/**
* Lege values eruit filteren
*/
$arr = array_filter($row->toArray());
try {
/**
* Merge 'program_id' in gegevens uit XML
*/
$inserted_array = array_merge($arr, array('program_id' => $program_id, 'feed_id' => $feed_id, 'custom_categorie' => $custom_categorie));
Data::create($inserted_array);
} catch (Exception $e) {
dd($e->getMessage());
}
}
});
Data::where(function ($query) {
$query->whereTitle('title')->orWhere('title', 'like', '#%');
})->delete();
Data::whereTemp(0)->update(array('temp' => 1));
\File::delete($fileLocation);
}
示例6: importdata
public function importdata(Request $request)
{
$results = null;
// $results = $reader->get();
//
// $ret = $results->toArray();
$file = $request->file('exelimport');
$request->file('exelimport')->move(storage_path() . '/public/import/', 'import.xlsx');
//$request->file('exelimport')
// $results = Excel::load($request->file('exelimport'))->toArray();
$ret = Excel::filter('chunk')->load(storage_path('/public/import/import.xlsx'))->chunk(250, function ($results) {
$data = array();
// $results = $reader->toArray();
foreach ($results as $index => $value) {
$EMP_ID = $value["emp_id"];
// $PERIOD = $value["period"];
// $user = DB::table('TBL_MEMBER_BENEFITS')->where('EMP_ID', $EMP_ID)->where('PERIOD', $PERIOD)->count();
$allquery = "SELECT COUNT(EMP_ID) AS total FROM TBL_USER_BENEFICIARY WHERE EMP_ID= '" . $EMP_ID . "'";
$all = DB::select(DB::raw($allquery));
$total = $all[0]->total;
$date = new Date();
// array_push($data,'asd','asda');
if ($total == 0) {
array_push($data, array('EMP_ID' => $value["emp_id"], 'FULL_NAME' => $value["full_name"], 'FILE_NO' => $value["file_no"], 'FILE_PATH' => $value["file_path"], 'CREATE_DATE' => $value["create_date"], 'CREATE_BY' => $value["create_by"], 'FILE_NAME' => $value["file_name"]));
}
}
// var_dump($data);
DB::table('TBL_USER_BENEFICIARY')->insert($data);
//DB::insert(DB::raw($insert));
});
return response()->json(array('success' => true, 'html' => $ret));
}
示例7: import
/**
*
*/
public function import(Request $request)
{
Excel::filter('chunk')->load($request->only('file')['file'], 'UTF-8')->chunk(100, function ($language) {
// Loop through all rows
$language->each(function ($row) {
$default = Locale::find(1);
$locales = Locale::lists('id', 'name');
$langs = [];
foreach ($row as $lang => $translation) {
if (array_key_exists(ucfirst($lang), $locales->toArray())) {
// if imported lang exist
$ilang_id = $locales[ucfirst($lang)];
//
if ($ilang_id == $default->id) {
$langs[ucfirst($lang)]['translation'] = $translation;
$langs[ucfirst($lang)]['id'] = $ilang_id;
} else {
$langs['child'][ucfirst($lang)]['translation'] = $translation;
$langs['child'][ucfirst($lang)]['id'] = $ilang_id;
}
}
}
$new_trans = LocaleTranslation::firstOrNew(['locale_id' => $langs[$default->name]['id'], 'translation' => $langs[$default->name]['translation']]);
$new_trans->save();
foreach ($langs['child'] as $cland => $ctrans) {
$new_ctrans = LocaleTranslation::firstOrNew(['locale_id' => $ctrans['id'], 'translation_id' => $new_trans->id]);
$new_ctrans->translation = $ctrans['translation'];
$new_ctrans->save();
}
});
});
return redirect()->route('admin.language.index')->withFlashSuccess('Imported');
}
示例8: handle
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$order_id = $this->order->id;
//
try {
//解析文件 录入数据库
Excel::filter('chunk')->selectSheets('Sheet1')->load(public_path($this->order->sub_file))->chunk(300, function ($results) use($order_id) {
foreach ($results as $row) {
if ($row['序号'] != null) {
$subOrder = new SubOrder();
$subOrder->order_id = $order_id;
$subOrder->excel_id = (int) $row['序号'];
$subOrder->fw_number = $row['国外运单号'];
$subOrder->name = $row['姓名'];
$subOrder->mobile = $row['电话'];
$subOrder->address = $row['地址'];
$subOrder->zip_code = $row['邮编'];
$subOrder->weight = $row['重量'];
$subOrder->id_number = $row['身份证号'];
try {
$subOrder->save();
} catch (\Exception $exception) {
return array('success' => false, 'errors' => array($exception->getMessage()));
}
//存入订单产品
$product = new OrderProduct();
$product->sub_order_id = $subOrder->id;
$product->name = $row['品名'];
$product->count = $row['数量'];
try {
$product->save();
} catch (\Exception $exception) {
return array('success' => false, 'errors' => array($exception->getMessage()));
}
} else {
//存入子订单
$subOrder = SubOrder::where('excel_id', (int) $row['子序号'])->where('order_id', $order_id)->first();
//TODO 检查子订单是否存在
//存入订单产品
$product = new OrderProduct();
$product->sub_order_id = $subOrder['id'];
$product->name = $row['品名'];
$product->count = $row['数量'];
try {
$product->save();
} catch (\Exception $exception) {
return array('success' => false, 'errors' => array($exception->getMessage()));
}
}
}
});
} catch (\Exception $e) {
return array('success' => false, 'errors' => array($e->getMessage()));
}
//文件解析成功 更新子订单数量
//获取分单数量
$sub_total = SubOrder::where('order_id', $this->order->id)->count();
$this->order->sub_total = $sub_total;
$this->order->save();
}
示例9: importFromExcel
/**
* @param $pathToExcel
* @return array
*/
private function importFromExcel($pathToExcel)
{
$all = [];
$result = Excel::filter('chunk')->load($pathToExcel, function (LaravelExcelReader $reader) {
$reader->noHeading();
$reader->skip(3);
$this->startProgressBar($reader->getTotalRowsOfFile());
})->chunk(100, function ($rows) {
foreach ($rows as $row) {
if (null !== $row[0] && null !== $row[2] && $row[2] !== 'Номер') {
$this->advanceProgressBar();
$this->exportToDb([$row[0], $row[1], $row[2], $row[3]]);
} else {
}
}
}, $this->async);
}
示例10: run
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
DB::table('locations')->truncate();
$location = [['name' => 'Myanmar', 'pcode' => 'MMR', 'type' => 'country', 'lat' => 16.799999, 'long' => 96.150002, 'mya_name' => 'မြန်မာ', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]];
Location::buildTree($location);
//$files = [
// 'locations/Myanmar/Ayeyarwady.csv'
// ];
/**
$files = 'locations/Myanmar';
$excel = Excel::batch($files, function($rows, $file) {
$this->rows[$rows->title] = $rows->each(function($row) {});
});
$nested_set = $this->locations->merge_excel_import($this->rows);
$parent = Location::where('pcode', '=', 'MMR')->first();
//dd($parent->location);
$imported = $parent->makeTree($nested_set); // => true
*
*/
$files = 'locations/Myanmar';
$excel = Excel::batch($files, function ($rows, $file) {
$i = 5000;
Excel::filter('chunk')->load($file)->chunk(5000, function ($results) use($file, &$i) {
$row = $this->locations->arrayToNestedSet('MMR', $results);
echo "{$i} rows completed\n";
return $i += 5000;
});
echo $file . "completed\n";
//$parent = Location::where('pcode', '=', 'MMR')->first();
//$imported = $parent->makeTree($nested_set_children);
});
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
示例11: postImportUserRole
public function postImportUserRole(Request $request)
{
$getSheetName = Excel::load(Request::file('file4'))->getSheetNames();
foreach ($getSheetName as $sheetName) {
//if ($sheetName === 'Product-General-Table') {
//selectSheetsByIndex(0)
//DB::statement('SET FOREIGN_KEY_CHECKS=0;');
//DB::table('users')->truncate();
//Excel::selectSheets($sheetName)->load($request->file('file'), function ($reader)
//Excel::selectSheets($sheetName)->load(Input::file('file'), function ($reader)
//Excel::filter('chunk')->selectSheetsByIndex(0)->load(Request::file('file'))->chunk(50, function ($reader)
Excel::filter('chunk')->selectSheets($sheetName)->load(Request::file('file4'))->chunk(50, function ($reader) {
$readerarray = $reader->toArray();
//var_dump($readerarray);
foreach ($readerarray as $row) {
/*
$userbulk = new User;
$userbulk->name = $row['user'];;
$userbulk->email = $row['email'];
$userbulk->password = bcrypt($row['pass']);
//$userbulk->created_at = date(2015-12-22);
//$userbulk->updated_at = date(2015-12-22);
$userbulk->save();
*/
}
});
}
return redirect('/');
}
示例12: cliImport
public function cliImport($file, $org)
{
set_time_limit(0);
Excel::filter('chunk')->load($file, 'UTF-8')->chunk(100, function ($locations) use($file, $org) {
// Loop through all rows
//dd($locations);
$locations->each(function ($row) use($org) {
//$this->plocations->setPcode($org, $locations);
$this->setPcode($row, $org);
});
});
}
示例13: cliImport
public function cliImport($file, $org, $role)
{
$excel = Excel::filter('chunk')->load($file, 'UTF-8')->chunk(50, function ($participant) use($file, $org, $role) {
//$this->makeNestedSetArray($participant, $org, $role);
$participant->each(function ($row) use($role, $org) {
$this->arrayToNestedSet($row, $org, $role);
});
});
//dd($excel)->all();
//$excel = Excel::load($file, 'UTF-8')->all();
//$this->makeNestedSetArray($excel, $org, $role);
}
示例14: import
public function import(Request $request)
{
exit;
$path = $request->input('path');
set_time_limit(600);
// Excel::filter('chunk')->selectSheetsByIndex(0)->load($path)->noHeading()->chunk(1000, function($result){
// $data = $result->toArray();
// unset($data[0]);
// if ($data) {
// foreach ($data as $k=>$v) {
// $in[] = array(
// 'user_name'=>$v[0],
// 'sno'=>$v[1],
// 'gender'=>$v[2],
// 'id_card'=>$v[3],
// 'birthday'=>$v[4],
// 'nation'=>$v[5],
// 'grade'=>$v[6],
// 'degree'=>$v[7],
// 'major'=>$v[8],
// 'phone'=>$v[9],
// 'learn_center'=>$v[10],
// 'roll_status'=>$v[11],
// 'account_status'=>$v[12],
// 'roll_filled'=>$v[13],
// 'graduation_filled'=>$v[14],
// 'degree_filled'=>$v[15],
// 'fee'=>$v[16],
// 'fee_ed'=>$v[17],
// 'fee_status'=>$v[18],
// 'teaching_way'=>$v[19],
// 'ordered'=>$v[20],
// );
//// $in[] = array(
//// 'user_name'=>$v[0],
//// 'sno'=>$v[1],
//// 'gender'=>$v[2],
//// 'id_card'=>$v[3],
//// 'class_name'=>$v[4],
//// 'grade'=>$v[5],
//// 'major'=>$v[6],
//// 'school'=>$v[7],
//// 'site'=>$v[8],
//// 'degree'=>$v[9],
//// 'course_name'=>$v[10],
//// 'note'=>$v[11],
//// 'ordered'=>$v[12],
//// );
// }
// DB::table('t1')->insert($in);
// }
// });
// exit;
Excel::selectSheetsByIndex(0)->load($path, function ($reader) {
$data = $reader->noHeading()->toArray();
unset($data[0]);
if ($data) {
foreach ($data as $k => $v) {
$in[] = array('user_name' => $v[0], 'sno' => $v[1], 'gender' => $v[2], 'id_card' => $v[3], 'birthday' => $v[4], 'nation' => $v[5], 'grade' => $v[6], 'degree' => $v[7], 'major' => $v[8], 'phone' => $v[9], 'learn_center' => $v[10], 'roll_status' => $v[11], 'account_status' => $v[12], 'roll_filled' => $v[13], 'graduation_filled' => $v[14], 'degree_filled' => $v[15], 'fee' => $v[16], 'fee_ed' => $v[17], 'fee_status' => $v[18], 'teaching_way' => $v[19], 'ordered' => $v[20]);
// $in[] = array(
// 'user_name'=>$v[0],
// 'sno'=>$v[1],
// 'gender'=>$v[2],
// 'id_card'=>$v[3],
// 'class_name'=>$v[4],
// 'grade'=>$v[5],
// 'major'=>$v[6],
// 'school'=>$v[7],
// 'site'=>$v[8],
// 'degree'=>$v[9],
// 'course_name'=>$v[10],
// 'note'=>$v[11],
// 'ordered'=>$v[12],
// );
}
DB::table('t1')->insert($in);
}
// DB::table('t2')->insert($reader->toArray());
});
exit;
Excel::filter('chunk')->selectSheetsByIndex(0)->load($path)->chunk(500, function ($results) {
// DB::enableQueryLog();
// $results = $results->slice(1);
foreach ($results->toArray() as $v) {
print_r($v);
}
// DB::table('t2')->insert($results->toArray());
// exit;
// foreach ($results as $k=>$v) {
//// $data = $v->toArray();//->values()
//
// $in[] = array(
// 'user_name'=>$v[0],
// 'sno'=>$v[1],
// 'gender'=>$v[2],
// 'id_card'=>$v[3],
// 'class_name'=>$v[4],
// 'grade'=>$v[5],
// 'major'=>$v[6],
// 'school'=>$v[7],
//.........这里部分代码省略.........
示例15: import_objects_process
/**
* Handle the posted CSV when importing all objects of a given CtrlClass
* @param integer $ctrl_class_id The ID of the class we're editing
* @param string $filter_string Are we filtering the list? Currently stored as a ~ delimited list of property=>id comma-separated pairs; see below
*
* @return Response
*/
public function import_objects_process(Request $request, $ctrl_class_id, $filter_string = NULL)
{
$ctrl_class = CtrlClass::where('id', $ctrl_class_id)->firstOrFail();
if (!$this->module->enabled('import_objects')) {
// This can only happen if someone is fucking around with the URL, so just bail on them.
\App::abort(403, 'Access denied');
// Should also check that we can import ctrlclass_id...
} else {
if (!$ctrl_class->can('import')) {
\App::abort(403, 'Access denied');
// As above
}
}
$this->validate($request, ['csv-import' => 'required'], ['csv-import.required' => 'Please select a CSV file to upload']);
$csv_file = trim($request->input('csv-import'), '/');
$errors = [];
// Work out what headers we need, what the callback functions are, whether we have a "pre-import" function, etc:
$required_headers = $this->module->run('import_objects', ['get-headers', $ctrl_class_id]);
// Convert all headers into slugged values, as per http://www.maatwebsite.nl/laravel-excel/docs/import#results
// Excel does this on import automatically, so we need compare slugged values with the headers Excel has converted
// Technically this uses the protected function Excel::getSluggedIndex()
// but it's essentially the same as Laravel's str_slug():
$slugged_headers = array_map('str_slug', $required_headers, array_fill(0, count($required_headers), '_'));
$callback_function = $this->module->run('import_objects', ['get-callback-function', $ctrl_class_id]);
// Run the pre-import-function if necessary; this can either prep data, or truncate tables,
// or (in the case of the Argos CAT sheet) bypass the Excel import altogether
if ($pre_import_function = $this->module->run('import_objects', ['get-pre-import-function', $ctrl_class_id])) {
if ($response = $pre_import_function($ctrl_class_id, $filter_string, $csv_file)) {
return $response;
}
}
// Now import the data in chunks:
$loop = 0;
$count = 0;
set_time_limit(0);
// Dammit, it's the LOAD that's taking a while, not the procecssing.
// This is a problem in Argos because it's a 25Mb CSV...
// Ah, it's definitely still quicker to chunk though
// Not sure if this is required or not, but it's been useful in the past
// Found the tip here: https://github.com/Maatwebsite/Laravel-Excel/issues/388
ini_set('auto_detect_line_endings', true);
Excel::filter('chunk')->load($csv_file)->chunk(250, function ($results) use(&$count, $loop, $ctrl_class_id, $errors, $required_headers, $slugged_headers, $callback_function) {
if ($loop++ == 0) {
// First pass so check headers etc
$first_row = $results->first()->toArray();
$csv_headers = array_keys($first_row);
if (count($results) == 0) {
$errors['csv-import'] = 'That CSV file doesn\'t appear to contain any data';
} elseif (count($csv_headers) != count($required_headers)) {
// Can fairly easily run an array diff here...
$errors['csv-import'] = 'That CSV file doesn\'t seem to have the correct number of columns';
} elseif ($csv_headers != $slugged_headers) {
// ... and here
$errors['csv-import'] = 'That CSV file doesn\'t seem to have the correct column titles';
}
}
if (!$errors) {
$response = $callback_function($results);
// Again, we may need the filter string here in some cases...?
if ($response === false) {
$errors['csv-import'] = 'Cannot import data';
} else {
if ($response === 0) {
$errors['csv-import'] = 'This import would have no effect; no rows would be processed';
// Is this always right? Might we sometimes import zero rows from the first chunk, even though we'd import rows in subsequent chunks?
} else {
$count += $response;
}
}
}
if ($errors) {
return;
}
// Should exit the chunk, I think
}, false);
// False allows us to pass variables by reference; https://github.com/Maatwebsite/Laravel-Excel/issues/744
if (!empty($errors)) {
return response()->json($errors, 422);
} else {
$message = $count . ' records imported';
$messages = [$message];
$request->session()->flash('messages', $messages);
$back = route('ctrl::import_objects', [$ctrl_class_id, $filter_string]);
return response()->json(['redirect' => $back]);
}
}