<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Customer;
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
class ExcelController extends Controller
{
public function index()
{
return view('excel');
}
public function upload(Request $request)
{
if ($request->hasFile('file')) {
$file = $request->file('file');// get file
$reader = ReaderFactory::create(Type::XLSX); // for XLSX files
$reader->open($file);
// loop semua sheet dan dapatkan sheet orders
foreach ($reader->getSheetIterator() as $sheet) {
if ($sheet->getName() === 'Orders') {
$this->readOrderSheet($sheet);// baca sheet orders
}
}
$reader->close();
}
}
public function readOrderSheet($sheet)
{
//loop untuk setiap baris pada excel
foreach ($sheet->getRowIterator() as $idx => $row) {
if ($idx>1) { // skip baris pertama excel (Judul)
$data = [
'row_id' => $row[0],
'order_id' => $row[1],
'order_date' => $row[2],
'order_priority' => $row[3],
'order_quantity' => $row[4],
'sales' => $row[5],
'discount' => $row[6],
'ship_mode' => $row[7],
'profit' => $row[8],
'unit_price' => $row[9],
'shipping_cost' => $row[10],
'customer_name' => $row[11],
'province' => $row[12],
'region' => $row[13],
'customer_segment' => $row[14],
'product_category' => $row[15],
'product_sub_category' => $row[16],
'product_name' => $row[17],
'product_container' => $row[18],
'prodcut_base' => $row[19],
'ship_date' => $row[20]
];
$customer = new Customer();// buat customer baru
$customer->fill($data);// isi customer dari data excel
$customer->save(); // simpan customer
}
}
}
public function exportExcel()
{
$title = ['Row ID', 'Order ID', 'Order Date', 'Order Priority', 'Order Quantity', 'Sales',
'Discount', 'Ship Mode', 'Profit', 'Unit Price', 'Shipping Cost', 'Customer Name',
'Province', 'Region', 'Customer Segment', 'Product Category', 'Product Sub-Category',
'Product Name', 'Product Container', 'Product Base Margin', 'Ship Date'];
$fileName = 'Export Excel.xlsx';
$writer = WriterFactory::create(Type::XLSX); // for XLSX files
$customers = Customer::all(); // dapatkan seluruh data customer
$writer->openToBrowser($fileName); // stream data directly to the browser
$writer->addRow($title); // tambahkan judul dibaris pertama
foreach ($customers as $idx => $data) {
$writer->addRow($data->toArray()); // tambakan data data per baris
}
$writer->close();
}
}