如何在Laravel中将导出导入Excel

时间:2018-10-08 03:41:51

标签: php excel laravel web-scraping laravel-5.7

我在itsolutionstuff.com网站上找到了此代码。

我用了这个...

Route::post('importExcel', 'MaatwebsiteDemoController@importExcel');

然后将其挂起以使用我的路线...

Route::post('barang', 'BarangController@importExcel')->name('barang');

对于Controller,我选择了此代码是因为我需要它...

public function importExcel(Request $request)
{
    $request->validate([
        'import_file' => 'required'
    ]);

    $path = $request->file('import_file')->getRealPath();
    $data = Excel::load($path)->get();

    if ($data->count()) {
        foreach ($data as $key => $value) {
            $arr[] = ['title' => $value->title, 'description' => $value->description];
        }

        if (!empty($arr)) {
            Item::insert($arr);
        }
    }

    return back()->with('success', 'Insert Record successfully.');
}

然后我根据自己的餐桌设计进行了更改...

public function importExcel(Request $request)
{
    $request->validate([
        'import_file' => 'required'
    ]);

    $path = $request->file('import_file')->getRealPath();
    $data = Excel::load($path)->get();

    if ($data->count()) {
        foreach ($data as $key => $value) {
            $arr[] = [
                'kode_barang' => $value->kode_barang,
                'nama_barang' => $value->nama_barang,
                'kategori_id' => $value->kategori_id,
                'jumlah_barang' => $value->jumlah_barang,
                'harga_satuan' => $value->harga_satuan,
                'tanggal_inputan' => $value->tanggal_inputan,
                'deskripsi' => $value->deskripsi,
                'status' => $value->status,

            ];
        }

        if (!empty($arr)) {
            Item::insert($arr);
        }
    }

    return back()->with('success', 'Insert Record successfully.');
}

我还将其添加到我的视图中...

<form action="{{ route('barang') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
    @csrf
    @if ($errors->any())
        <div class="alert alert-danger">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    @if (Session::has('success'))
        <div class="alert alert-success">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
            <p>{{ Session::get('success') }}</p>
        </div>
    @endif
    <input type="file" name="import_file"/>
    <button class="btn btn-primary">Import File</button>
</form>

结果如下:
enter image description here

但是,它说记录已成功插入,但是数据未插入到我的表中enter image description here

这是我的Excel CSV格式...
enter image description here

为什么数据没有插入数据库?我的代码中仍然存在错误/不完整/拼写错误吗?

我什至试图更改项目 ...

 if(!empty($arr)){
                Item::insert($arr);
            }
        }

        return back()->with('success', 'Insert Record successfully.');
    }

...对 Barang 仍然告诉我它是成功的,没有将数据插入数据库。

if(!empty($arr)){
                    Barang::insert($arr);
                }
            }

            return back()->with('success', 'Insert Record successfully.');
        }

如果您听不懂我说的话,我深表歉意。感谢您的关注。

1 个答案:

答案 0 :(得分:1)

确保您的csv具有标题。Maatwebsite\Excel\Excel将抓住第一行作为标题,然后其余的将成为您的项目。

您的csv有一行

R4B6, MONITOR LENOVO, ELEKTRNIK, 1,-,10/4/2018,-,Aktif` 

,该类认为其为标头,并返回以下对象。如您所见,item似乎为空。

RowCollection {#722 ▼
  #heading: array:8 [▶]
  #title: "Worksheet"
  #items: []
}

但是如果添加了标题

heading1,heading2,heading3,heading4,heading5,heading6,heading7,heading8,
R4B6, MONITOR LENOVO, ELEKTRNIK, 1,-,10/4/2018,-,Aktif

返回以下对象

RowCollection {#730 ▼
  #heading: array:8 [▼
  0 => "heading1"
  1 => "heading2"
  2 => "heading3"
  3 => "heading4"
  4 => "heading5"
  5 => "heading6"
  6 => "heading7"
  7 => "heading8"
]
#title: "Worksheet"
#items: array:1 [▼
  0 => CellCollection {#736 ▶}
]}

您还可以通过在控制器中进行改进来提高代码

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

$rows = collect(Excel::load($path)->get())->map(function ($row) {
    return [
        'kode_barang' => $row->heading1,
        'nama_barang' => $row->heading2,
        'kategori_id' => $row->heading3,
        'jumlah_barang' => $row->heading4,
        'harga_satuan' => $row->heading5,
        'tanggal_inputan' => $row->heading6,
        'deskripsi' => $row->heading7,
        'status' => $row->heading8,
      ];
    });

Item::insert($rows);

return back()->with('success', 'Insert Record successfully.');

欢呼