Hướng dẫn phpspreadsheet read excel example - ví dụ về đọc phpspreadsheet excel

Tôi đã giới thiệu và hướng dẫn các bạn sử dụng thư viện PHPExcel tại địa chỉ http://gextend.net/threads/tao-bao-cao-excel-voi-thu-vien-phpexcel.17 để tạo các báo cáo Excel và bây giờ tôi tiếp tục hướng dẫn các bạn sử dụng thư viện mới nhất được chính nhà phát triển thư viện PHPExcel đề nghị tên là PhpSpreadsheet. Đây là thư viện có chức năng tương tự như PHPExcel nhưng được cải tiến rất nhiều về kiến trúc mã nguồn cũng như cho hiệu năng tốt hơn.

Thư viện PhpSpreadsheet hỗ trợ nhiều định dạng hơn PHPExcel.

Các định dạng cho phép đọc:

  • Open Document Format/OASIS (.ods).
  • Office Open XML (.xlsx) Excel 2007 and above.
  • BIFF 8 (.xls) Excel 97 and above.
  • BIFF 5 (.xls) Excel 95.
  • SpreadsheetML (.xml) Excel 2003.
  • Gnumeric.
  • HTML.
  • SYLK.
  • CSV.

Các định dạng cho phép ghi:

  • Open Document Format/OASIS (.ods).
  • Office Open XML (.xlsx) Excel 2007 and above.
  • BIFF 8 (.xls) Excel 97 and above.
  • HTML.
  • CSV.
  • PDF.

BIFF 5 (.xls) Excel 95.

SpreadsheetML (.xml) Excel 2003.

Các định dạng cho phép ghi:

Thư viện PhpSpreadsheet yêu cầu PHP phiên bản 5.6+ và các thư viện php_zip, php_xml và php_gd2.

composer require phpoffice/phpspreadsheet

Để sử dụng PhpSpreadsheet các bạn cần phải sử dụng công cụ composer. Các bạn tham khảo tại địa chỉ https://getcomposer.org.

Để cài đặt, các bạn chạy lệnh composer sau:

getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');

Code:

Sau khi composer cài đặt thành công thư viện PhpSpreadsheet, các bạn có thể sử dụng thư viện như ví dụ sau:

PHP:

Các bạn có thể tham khảo thêm về thư viện PhpSpreadsheet tại địa chỉ https://github.com/PHPOffice/PhpSpreadsheet và https://phpspreadsheet.readthedocs.io.

As a Drupal developer, you might have come with a situation where you have to integrate Drupal websites with other third-party system. So here third party systems provide data in a CSV or excel format that we have to show in the Drupal website.

In this case, we have to import this data to one or more content type in Drupal.

composer require phpoffice/phpspreadsheet

There are excel import modules available that will do the job. But in these modules, you can use for direct import to content types. But most of the cases you have to work on each row to clean the data and also various validations on each data and assign to various content type based on conditions in cell values. For these purpose you have to write your own custom code.

So here I am going to explain how we can write our own excel import functionality in our custom module in Drupal 8.

“phpoffice/phpspreadsheet”: “^1.8”

before starting project. Install php spreadsheet  library using the below command in your project folder.

1) Import với phpoffice/phpspreadsheet

Hướng dẫn phpspreadsheet read excel example - ví dụ về đọc phpspreadsheet excel

this will place phpspreadsheet library  in your vendors directory and adds below entry in your project composer.json.

You can see library in phpoffice folder inside your project vendors directory.

Here I have content type called news and trying to upload below sheet into the news content.

digitalnadeem_importexcel.import_excel:
  path: '/admin/structure/digitalnadeem_importexcel/sheet/import'
  defaults:
    _title: 'Upload sheet'
    _form: '\Drupal\digitalnadeem_importexcel\Form\ImportexcelForm'
  requirements:
    _permission: 'Import form'

Now we are going to create form in our custom module to import csv file and create content programmatically using phpspreadsheet library. Here my custom module name is digitalnadeem_importexcel

\src\Form\ImportexcelForm.php

First, we are creating custom form to import CSV or excel sheet.

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

For this, I have created a new entry in routing .yml file in my module.

public function buildForm(array $form, FormStateInterface $form_state) {
 
    $form = array(
      '#attributes' => array('enctype' => 'multipart/form-data'),
    );
    
    $form['file_upload_details'] = array(
      '#markup' => t('The File'),
    );
    
    $validators = array(
      'file_validate_extensions' => array('csv'),
    );
    $form['excel_file'] = array(
      '#type' => 'managed_file',
      '#name' => 'excel_file',
      '#title' => t('File *'),
      '#size' => 20,
      '#description' => t('Excel format only'),
      '#upload_validators' => $validators,
      '#upload_location' => 'public://content/excel_files/',
    );
    
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    return $form;

  }

Next I have created a form  ImportExcelForm.php in my module path.

‘#upload_location’ => ‘public://content/excel_files/

First, you have to include spread sheet library classes as shown below

\sites\default\files\content\excel_files

in buildForm function include the below code to create upload form.

Below the upload location, you have to create in your project directory.

In my case I have created in folder in below path.

getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');
0

So uploaded files will be stored in this path for processing.

As mentioned in form configuration I have provided csv format only allowed in validation. You can provide xlsx in an array if you are uploading a normal excel sheet.

getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');
1

Also added below validation function.

Now we are going to implement import functionality in our submit form handler.

getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');
2

In submit first we are getting file name that uploaded. And generating path to file uploaded directory .

getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');
3

Next we are using phpspreadsheet  functions to get extract cell values from uploaded document.

The below code will iterate through each row and cells and store values in an array say variable $rows.

getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');
4

Here out put of $rows array will be as shown below.

Here I used below sheet to import.

Here first row is header row . this we don’t want to import to the news content .So for removing first row use below array_shift function.

getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');
5

Bây giờ bạn đã hoàn thành với việc thực hiện.Xóa bộ đệm bạn có thể thấy bên dưới biểu mẫu trong khi truy cập URL-& nbsp; http: //your-site.com/admin/structure/digitalnadeem_importexcel/sheet/import http://your-site.com/admin/structure/digitalnadeem_importexcel/sheet/import

Xem nội dung đã nhập trong trang nội dung quản trị viên.

2) Xuất VớI PHPOFFICE/PHPSPREADSHEET

getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');
6

Sự kết luận

Ở đây tôi đã giải thích làm thế nào chúng ta có thể nhập một tờ Excel/CSV duy nhất vào Drupal.Hầu hết hệ thống bên thứ ba có thể có API có thể đặt bảng dữ liệu Excel/CSV vào một thư mục trong một khoảng thời gian thường xuyên.Trong đó & nbsp;trường hợp, & nbsp; làm theo cùng một cách tiếp cận mà tôi đã giải thích ở trên và một công việc tạo ra để lấy tệp từ một vị trí cụ thể.Vì vậy, Cron Job sẽ chèn nội dung từ Excel trong các khoảng thời gian đều đặn.Bằng cách này, bạn có thể tự động hóa toàn bộ quá trình.