简体   繁体   English

使用 Excel::import 在 Maatwebsite / Laravel Excel 3.1 上导入 CSV

[英]Import CSV on Maatwebsite / Laravel Excel 3.1 using Excel::import

I've upgraded Maatwebsite/Laravel-Excel to 3.1 from 2.1.我已将 Maatwebsite/Laravel-Excel 从 2.1 升级到 3.1。 Some of the method are deprecated.某些方法已被弃用。

Here is the code on version 2.1.这是 2.1 版的代码。

$data = Excel::load($path, function($reader) {})->get()->toArray();

It's working when I used 2.1 but after I upgraded, it's error当我使用 2.1 时它可以工作,但升级后,它是错误的

Call to undefined method Maatwebsite\\Excel\\Excel::load()调用未定义的方法 Maatwebsite\\Excel\\Excel::load()

For version 3.1, i tried to change to对于 3.1 版,我尝试更改为

$data = Excel::import($path, function($reader) {})->get()->toArray();

I know this probably not the correct syntax.我知道这可能不是正确的语法。

Here my full code when developing using 2.1.这是我使用 2.1 开发时的完整代码。

$path = $request->file('csv_file')->getRealPath();

    if ($request->has('header')) {
        $data = Excel::import($path, function($reader) {})->get()->toArray();
    } else {
        $data = array_map('str_getcsv', file($path));
    }

    if (count($data) > 0) {
        if ($request->has('header')) {
            $csv_header_fields = [];
            foreach ($data[0] as $key => $value) {
                $csv_header_fields[] = $key;
            }
        }
        $csv_data = array_slice($data, 0, 8);

        $csv_data_file = CsvData::create([
            'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
            'csv_header' => $request->has('header'),
            'csv_data' => json_encode($data)
        ]);
    } else {
        return redirect()->back();
    }

    return view('import.import_field', compact( 'csv_header_fields', 'csv_data', 'csv_data_file'));

How to fix this error on version 3.1?如何在 3.1 版上修复此错误?

Actually there is no need to create any extra classes for the Excel import in Maatwebsite/Laravel-Excel version 3. Basically you can do the whole CSV to array conversion almost in a same way as in version 2:实际上,在 Maatwebsite/Laravel-Excel 版本 3 中,不需要为 Excel 导入创建任何额外的类。基本上,您可以以与版本 2 中几乎相同的方式进行整个 CSV 到数组的转换:

    $path = $request->file('csv_file')->getRealPath();
    $data = \Excel::toArray('', $path, null, \Maatwebsite\Excel\Excel::TSV)[0];

The first parameter of the import() method is not the path to the file anymore in 3.1, but the class name of the Import file you have to create. import()方法的第一个参数在 3.1 中不再是文件的路径,而是你必须创建的导入文件的类名。

In this import file you can define how you want to read the sheet, and to what format you want to convert it, for example a model or a collection.在此导入文件中,您可以定义您希望如何阅读工作表,以及您希望将其转换为何种格式,例如模型或集合。

The easiest way to migrate from 2.1 to 3.1 is to create such an Import class by running (in your case):从 2.1 迁移到 3.1 的最简单方法是通过运行(在您的情况下)创建这样的导入类:

php artisan make:import CsvDataImport 

If you want to read all to rows at once, as in your question's code, you could use the ToCollection Concern in your import file:如果您想一次读取所有行,如在您的问题代码中,您可以在导入文件中使用ToCollection Concern:

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class CsvDataImport implements ToCollection
{
    public function collection(Collection $rows)
    {
        // Use the $rows collection to create your CsvData model.
    }
}

In your Controller you can call the import like this:在您的控制器中,您可以像这样调用导入:

use App\Imports\CsvDataImport;
use Maatwebsite\Excel\Excel;    

Excel::import(new CsvDataImport, $path);

You can read more about importing to a collection here您可以在此处阅读有关导入集合的更多信息

Do Not get back to downgrade, you can easily use new updated version( "maatwebsite/excel": "~3.1.0" ) with easiest import method.不要返回降级,您可以使用最简单的导入方法轻松使用新的更新版本( “maatwebsite/excel”:“~3.1.0” )。

Update Your Composer.json..更新您的 Composer.json..

 "require": {
    **"maatwebsite/excel": "~3.1.0"**
},

Steps To Use New Version..使用新版本的步骤..

  • Create Import to run this command in cmd创建导入以在 cmd 中运行此命令

php artisan make:import UsersImport

  • It will Create Import in app\\imports\\UserImport.php它将在 app\\imports\\UserImport.php 中创建导入

    <?php namespace App\\Imports; use Illuminate\\Support\\Collection; use Maatwebsite\\Excel\\Concerns\\ToCollection; use Maatwebsite\\Excel\\Concerns\\WithHeadingRow; class UserImport implements ToCollection,WithHeadingRow { public function collection(Collection $rows) { return $rows; } // headingRow function is use for specific row heading in your xls file public function headingRow(): int { return 3; } } ?>
  • In Your Controller file..在您的控制器文件中..

     use Excel; public function importExcel(Request $request) { $import = new UsersImport(); $data = \\Excel::import($import, request()->file('import_file')); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM