Created
July 30, 2020 05:34
-
-
Save mudiadamz/1702c7dab058ddf6eb1e9f33e4c31bc2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Http\Request; | |
use Illuminate\Routing\Controller as BaseController; | |
class SpreadsheetController extends BaseController | |
{ | |
function import(Request $request){ | |
$title = "Import Spreadsheet"; | |
$template = url('documents/template-users.xlsx'); | |
if($_POST){ | |
$request->validate([ | |
'file1' => 'required|mimes:xlsx|max:10000' | |
]); | |
$file = $request->file('file1'); | |
$name = time().'.xlsx'; | |
$path = public_path('documents'.DIRECTORY_SEPARATOR); | |
if ( $file->move($path, $name) ){ | |
$inputFileName = $path.$name; | |
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); | |
$reader->setReadDataOnly(true); | |
$reader->setLoadSheetsOnly(["USER DATA"]); | |
$spreadSheet = $reader->load($inputFileName); | |
$workSheet = $spreadSheet->getActiveSheet(); | |
$startRow = 2; | |
$max = 3000; | |
$columns = [ | |
"A"=>"id", | |
"B"=>"name", | |
"C"=>"email", | |
"D"=>"address" | |
]; | |
$data_insert = []; | |
for($i=$startRow; $i<$max; $i++){ | |
$id = $workSheet->getCell("A$i")->getValue(); | |
if(empty( $id)||!is_numeric( $id ))continue; | |
$data_row = []; | |
foreach ($columns as $col=>$field) { | |
$val = $workSheet->getCell("$col$i")->getValue(); | |
$data_row[$field] = $val; | |
} | |
$data_insert[] = $data_row; | |
} | |
\DB::table('users')->truncate(); | |
\DB::table('users')->insert($data_insert); | |
return redirect('spreadsheet/import')->with('success', 'Data imported successfully!'); | |
} | |
} | |
return view("spreadsheet.import", compact("title", "template")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment