您好,我正在使用laravel excel从excel导入文件并获取数据,但列标题正在更改,我需要保持不变。例如:列名称为Mat_Type-1,然后将其转换为mat_type_1。
我想保持不变,以便从列中获取一些数据。
控制器中的功能:
public function uploadexcel(Request $request){
// $this->validate($request, [
// 'importfile' => 'required|mimes:xls,xlsx'
// ]);
echo $path = $request->file('importfile');
$array = Excel::toArray(new ProductsImport, $path);
print_r($array);
}
Excel \ Imports类:
命名空间App \ Imports;
use App\Models\Admin\CarVariant;
use App\Models\Admin\Product;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
class ProductsImport implements ToModel,WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
// dd($row);
}
}
任何帮助深表感谢。尝试了多种选择,但不起作用。
答案 0 :(得分:0)
尝试一下。它来自一个实时项目。我将文件保存到文件夹中并以数组形式获取数据,然后将其按入数据表。数据表名称未更改。
use App\Imports\ProductsImport;
use Maatwebsite\Excel\Facades\Excel;
public function import(Request $request)
{
//Save the File
if($request->hasFile('file'))
{
// Get the file with extension
$filenameWithExt = $request->file('file')->getClientOriginalName();
//Get the file name
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//Get the ext
$extension = $request->file('file')->getClientOriginalExtension();
//File name to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload File
$path = $request->file('file')->storeAS('public/excels', $fileNameToStore);
}
$this->validate($request, [
'file' => 'required|mimes:xlsx,xls',
]);
$products = Excel::toArray(new ProductsImport(), $request->file('file'));
foreach($products[0] as $row) {
// dd($row[1].' '.$row[2]);
$arr[] = [
// If uncomment this id from here, remove [0] from foreach
// 'id' => $row[0],
'image' => $row[1],
'title' => $row[2],
'slug' => $row[3],
'text' => $row[4],
'brand_id' => $row[5],
'category_id' => $row[6],
];
}
if(!empty($arr)){
DB::table('products')->insert($arr);
}
return back()->with('success', 'Excel file uploaded to database successfully');
}
答案 1 :(得分:0)
因此,无论您对该行做什么,它都应该起作用。
我假设您正在为excel文件的每一行创建一个新模型。
public function model(array $row)
{
return new Whatever([
'Mat_Type-1' => $row['mat_type_1'],
'Column_Name-1' => $row['column_name_1'],
'Column_Name-2' => $row['column_name_2'],
]);
}