John Davidson

How to use PHP spreadsheet in drupal 7 for reading excel file and storing in database


I'm new in Drupal 7, I want to use PHP Spreadsheet in my project, but how much i know that PHP spreadheet module is available in Drupal 8, and for Drupal 7 we need to use it's library, so I followed this steps for PHP spreadsheet

  1. Download the PhpSpreadsheet library and extract it inside your site's libraries folder:

  • sites/all/libraries/PhpSpreadsheet

  1. Run "composer install" in folder libraries/PhpSpreadsheet to install all the dependencies

so what i need to do next and how to start using it in our custom module this things I'm not getting and which steps I need to follow, Please help me in this.

My Answer:
composer install in the PhpSpreadsheet directory to install the required dependencies___Create a custom module in Drupal 7 and add the following code to read an Excel file and store its data in the database:

function mymodule_read_excel_file($file_path) {
require_once DRUPAL_ROOT . '/sites/all/libraries/PhpSpreadsheet/vendor/autoload.php';

$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_path);
$sheet = $spreadsheet->getActiveSheet();

$data = [];
foreach ($sheet->getRowIterator() as $row) {
$rowData = [];
foreach ($row->getCellIterator() as $cell) {
$rowData[] = $cell->getValue();
$data[] = $rowData;

// Store data in the database
foreach ($data as $row) {
'column1' => $row[0],
'column2' => $row[1],
// Add more columns as needed

You can call the `mymodule_read_excel_file()` function with the path to the Excel file as a parameter to read the file and store its data in the database. Make sure to replace `'my_table'`, `'column1'`, `'column2'`, etc. with your actual table and column names.

Remember to also add the necessary permissions and validation checks in your custom module to ensure the security and integrity of your data.

Rate this post

3 of 5 based on 6848 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us