Laravel excel từ chế độ xem css

Trong bài đăng này, tôi trình bày cách nhập và xuất dữ liệu tệp Excel số lượng lớn vào và từ ứng dụng Laravel bằng thư viện PhpSpreadsheet. PhpSpreadsheet là một thư viện PHP cung cấp hỗ trợ đọc và viết các loại định dạng tệp khác nhau như Excel, CSV, HTML, SpreadsheetML và LibreOffice Calc, trong số những định dạng khác.  

Trong phát triển web hiện đại, các nhà phát triển có xu hướng xây dựng dựa trên các hệ thống dựa trên dữ liệu bất cứ khi nào có nhu cầu nhập hoặc xuất dữ liệu, trong khi phân tích hoặc báo cáo về nó. Khi làm như vậy, hầu hết các ứng dụng sử dụng tệp CSV hoặc Excel cùng với cơ sở dữ liệu khi xử lý dữ liệu hàng loạt, vì điều này rõ ràng hiệu quả hơn so với nhập dữ liệu, từng mục một.  

điều kiện tiên quyết

Để tiếp tục với hướng dẫn này, bạn cần có một dự án Laravel hiện có hoặc cài đặt một thiết lập dự án mới. Nếu bạn chưa quen với Laravel, hãy làm theo các hướng dẫn này để cài đặt thiết lập dự án mới.

Bước 1 – Tạo bảng

Sau khi cài đặt thành công dự án Laravel, hãy tạo cơ sở dữ liệu và bảng. Chạy tập lệnh SQL sau trong môi trường cơ sở dữ liệu của bạn để tạo bảng ‘tbl_customer’ mà bạn có thể sử dụng để lưu trữ dữ liệu của mình.

--

-- Database: `mydata`

--




-- --------------------------------------------------------




--

-- Table structure for table `tbl_customer`

--




CREATE TABLE `tbl_customer` (

  `CustomerID` int(11) NOT NULL,

  `CustomerName` varchar(250) NOT NULL,

  `Gender` varchar(30) NOT NULL,

  `Address` text NOT NULL,

  `City` varchar(250) NOT NULL,

  `PostalCode` varchar(30) NOT NULL,

  `Country` varchar(100) NOT NULL

) ENGINE=MyISAM DEFAULT CHARSET=latin1;




--

-- Indexes for table `tbl_customer`

--

ALTER TABLE `tbl_customer`

  ADD PRIMARY KEY (`CustomerID`);




--

-- AUTO_INCREMENT for dumped tables

--




--

-- AUTO_INCREMENT for table `tbl_customer`

--

ALTER TABLE `tbl_customer`

  MODIFY `CustomerID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=155;

COMMIT;

 

Bước 2 – Tạo kết nối cơ sở dữ liệu Mysql trong Laravel

Để tạo kết nối cơ sở dữ liệu, hãy mở . ENV và xác định cấu hình cơ sở dữ liệu của bạn.

DB_CONNECTION=mysql

DB_HOST=localhost

DB_PORT=3306

DB_DATABASE=mydata

DB_USERNAME=root

DB_PASSWORD=

 

Bước 3. Cài đặt PhpSpreadsheet trong Laravel

Trong thư mục dự án của bạn, hãy chạy lệnh này trên thiết bị đầu cuối của bạn để cài đặt thư viện PhpSpreadsheet

composer require phpoffice/phpspreadsheet

Bước 4. Tạo tệp xem của bạn (chào mừng. lưỡi. php)

Bên trong thư mục resources/views , hãy tạo lời chào mừng. lưỡi. php chứa biểu mẫu để tải lên tệp excel, bảng để tải dữ liệu đã tải lên từ cơ sở dữ liệu, cũng như nút để xuất dữ liệu. Dán đoạn mã sau vào đây.







   PHPSpreadsheet in Laravel

   

   

   

   








   
       

Handling Excel Data using PHPSpreadsheet in Laravel

   
   
       
           
               
                   

Import Excel Data

               
               
                   @if ($message = Session::get('success'))                        
                                                       {{ $message }}                        
                       
                   @endif                    
                       @csrf                        
                                                       
                                                               @if ($errors->has('uploaded_file'))                                    

                                       {{ $errors->first('uploaded_file') }}                                    

                               @endif                                
                                                                   
                           
                       
                   
               
           
       
   
   
       
           
           
               
                   

Customer Data Table

               
               
                   
                       Export Excel Data                    
                   
                                                                                                                                                                                                                                                                                                               @if(!empty($data) && $data->count())                                @foreach($data as $row)                                                                                                                                                                                                                                                                                                                                                        @endforeach                            @else                                                                                                                                @endif                                                    
Customer NameGenderAddressCityPostal CodeCountry
{{ $row->CustomerName }}{{ $row->Gender }}{{ $row->Address }}{{ $row->City }}{{ $row->PostalCode }}{{ $row->Country }}
There are no data.
                       {!! $data->links() !!}                    
               
           
       
   
       

 

Bước 5. Tạo một bộ điều khiển (ExcelController. php)

Trong thư mục app/Http/Controllers , hãy tạo tệp bộ điều khiển ( ExcelController. php) nơi bạn có thể viết các hàm để tải tệp phiến và dữ liệu từ cơ sở dữ liệu, đồng thời nhập và xuất dữ liệu đã tải lên.

 

Để sử dụng thư viện Phpspreadsheet, bạn phải nhập các không gian tên bí danh của nó trong Bộ điều khiển. Trong trường hợp này, hãy nhập các lớp sau

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use PhpOffice\PhpSpreadsheet\Spreadsheet;

use PhpOffice\PhpSpreadsheet\Reader\Exception;

use PhpOffice\PhpSpreadsheet\Writer\Xls;

use PhpOffice\PhpSpreadsheet\IOFactory;

Bạn cũng sẽ cần sử dụng các phương thức/chức năng sau bên trong bộ điều khiển.  

index() – Đây là phương thức gốc của lớp trình điều khiển này. Bên trong hàm, hãy tạo truy vấn để tìm nạp dữ liệu từ tbl_customer , sẽ được tải trong welcome. lưỡi. php tệp, ở định dạng bảng. Nếu bảng cơ sở dữ liệu trống, bảng trên giao diện sẽ trống.

importData() – Phương thức này có một biến yêu cầu chứa dữ liệu tệp excel đã tải lên. Bên trong hàm, xác thực định dạng tệp và kiểm tra xem nó có chứa dữ liệu bạn cần hay không, sau đó bạn có thể đọc dữ liệu chứa bằng gói PhpSpreadsheet. Thư viện PhpSpreadsheet sử dụng lớp IOFactory để tải dữ liệu excel và trích xuất từng hàng một thành một mảng PHP. Sử dụng  mảng để chèn dữ liệu đã trích xuất vào bảng tbl_customer . Sau khi nhập dữ liệu thành công, chuyển hướng trở lại trang chính, trả về thông báo thành công.

exportData()- Phương thức này truy vấn bảng tbl_customer để tải dữ liệu khách hàng và sử dụng . Nó sẽ tải xuống tệp excel chứa dữ liệu trên PC cục bộ.

orderBy('CustomerID', 'DESC')->paginate(5);

       return view('welcome', compact('data'));

   }




   /**

    * @param Request $request

    * @return \Illuminate\Http\RedirectResponse

    * @throws \Illuminate\Validation\ValidationException

    * @throws \PhpOffice\PhpSpreadsheet\Exception

    */

   function importData(Request $request){




       $this->validate($request, [

           'uploaded_file' => 'required|file|mimes:xls,xlsx'

       ]);




       $the_file = $request->file('uploaded_file');

       try{

           $spreadsheet = IOFactory::load($the_file->getRealPath());

           $sheet        = $spreadsheet->getActiveSheet();

           $row_limit    = $sheet->getHighestDataRow();

           $column_limit = $sheet->getHighestDataColumn();

           $row_range    = range( 2, $row_limit );

           $column_range = range( 'F', $column_limit );

           $startcount = 2;




           $data = array();




           foreach ( $row_range as $row ) {

               $data[] = [

                   'CustomerName' =>$sheet->getCell( 'A' . $row )->getValue(),

                   'Gender' => $sheet->getCell( 'B' . $row )->getValue(),

                   'Address' => $sheet->getCell( 'C' . $row )->getValue(),

                   'City' => $sheet->getCell( 'D' . $row )->getValue(),

                   'PostalCode' => $sheet->getCell( 'E' . $row )->getValue(),

                   'Country' =>$sheet->getCell( 'F' . $row )->getValue(),




               ];

               $startcount++;

           }




           DB::table('tbl_customer')->insert($data);

       } catch (Exception $e) {

           $error_code = $e->errorInfo[1];




           return back()->withErrors('There was a problem uploading the data!');

       }

       return back()->withSuccess('Great! Data has been successfully uploaded.');




   }




   /**

    * @param $customer_data

    */

   public function ExportExcel($customer_data){

       ini_set('max_execution_time', 0);

       ini_set('memory_limit', '4000M');




       try {

           $spreadSheet = new Spreadsheet();

           $spreadSheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);

           $spreadSheet->getActiveSheet()->fromArray($customer_data);




           $Excel_writer = new Xls($spreadSheet);

           header('Content-Type: application/vnd.ms-excel');

           header('Content-Disposition: attachment;filename="Customer_ExportedData.xls"');

           header('Cache-Control: max-age=0');

           ob_end_clean();

           $Excel_writer->save('php://output');

           exit();

       } catch (Exception $e) {

           return;

       }




   }




   /**

    *This function loads the customer data from the database then converts it

    * into an Array that will be exported to Excel

    */

   function exportData(){

       $data = DB::table('tbl_customer')->orderBy('CustomerID', 'DESC')->get();




       $data_array [] = array("CustomerName","Gender","Address","City","PostalCode","Country");

       foreach($data as $data_item)

       {

           $data_array[] = array(

               'CustomerName' =>$data_item->CustomerName,

               'Gender' => $data_item->Gender,

               'Address' => $data_item->Address,

               'City' => $data_item->City,

               'PostalCode' => $data_item->PostalCode,

               'Country' =>$data_item->Country

           );




       }

       $this->ExportExcel($data_array);




   }

}


 

Bước 6. Đặt các tuyến đường

Sau đó, mở đến các tuyến đường/web. php để thiết lập các liên kết đến các chức năng của bộ điều khiển như sau

Route::get('/', '[email protected]');

Route::post('/import', '[email protected]');

Route::get('/export', '[email protected]');

 

Bước 7. Chạy ứng dụng

Bây giờ, hãy đến dấu nhắc lệnh và viết lệnh sau.  

php artisan serve

 

Nếu bạn muốn chạy dự án trên một cổng khác, hãy sử dụng lệnh bên dưới. Chỉ định số cổng ưa thích của bạn

________số 8

 

Lệnh này sẽ trả về url cơ sở của ứng dụng Laravel mà bạn sẽ viết trên trình duyệt của mình và tương tác với nó. Xử lý dữ liệu Excel bằng PHPSpreadsheet trong Laravel

Laravel excel từ chế độ xem css

Phần kết luận

Bài đăng này cung cấp hướng dẫn từng bước về xuất và nhập dữ liệu tệp excel trong dự án Laravel. Logic tương tự có thể được sử dụng để điều chỉnh chức năng theo nhu cầu cụ thể của dự án. Nhận mã đầy đủ