PHP

Mastering Excel Data Importation in PHP

CK CK 3788 
Created at
Updated at  
558 0 0

You may use an Excel spreadsheet to manage your data for many cases, and had some chances that you want to use it as a direct data source from time to time.

You can use PHP libraries like PHPExcel or PhpSpreadsheet to handle Excel files with multiple sheets. Here's an example using PhpSpreadsheet, which is a newer and more actively maintained library:

First, you'll need to install PhpSpreadsheet using Composer:

composer require phpoffice/phpspreadsheet

Then you can use the following PHP code to import an Excel spreadsheet with multiple sheets into an array:

<?php
require 'vendor/autoload.php'; // Include PhpSpreadsheet's autoloader

use PhpOffice\PhpSpreadsheet\IOFactory;

$filename = 'path_to_your_excel_file.xlsx';

// Load the Excel spreadsheet
$spreadsheet = IOFactory::load($filename);

$data = [];

// Loop through each sheet
foreach ($spreadsheet->getSheetNames() as $sheetName) {
    $sheet = $spreadsheet->getSheetByName($sheetName);
    
    $sheetData = [];
    
    // Loop through each row in the sheet
    foreach ($sheet->getRowIterator() as $row) {
        $rowData = [];
        
        // Loop through each cell in the row
        foreach ($row->getCellIterator() as $cell) {
            // Get the value of the cell
            $rowData[] = $cell->getValue();
        }
        
        // Add the row data to the sheet data
        $sheetData[] = $rowData;
    }
    
    // Add the sheet data to the main data array
    $data[$sheetName] = $sheetData;
}

// Print the data
echo "<pre>";
print_r($data);
echo "</pre>";
?>

Replace 'path_to_your_excel_file.xlsx' with the path to your Excel file. This code will load each sheet of the Excel file into a separate array within the $data array. Each sheet's data will be stored under its sheet name as the key.

Remember to adjust this code according to your specific needs, like error handling, if required.

Tags Data Handling Data Import Excel Excel Files PHP PHP Libraries PhpSpreadsheet Programming Spreadsheets Web Development Facebook X
Comments 0
Similar posts
  1. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    599
  2. Equal Height Blocks in Bootstrap with JavaScript
    713
  3. Create Blob Image in HTML based on the given Text, Width and Height in the Center of the Image without saving file
    986
  4. Building a Simple DNS Server in Delphi with TTL Support
    686
  5. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,078
  6. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    746
  7. Dynamic DNS Made Easy: Building a Python-Based Solution
    796
  8. Simple Java Code to display Hello, World on the web
    568
  9. What Replaced JSP? Modern Java Web Dev Explained (with Examples)
    267
  10. Setup Apache+PHP+MySQL on Centos 6.7
    609
  11. PHP Code can know the current OS is windows or not
    589
  12. Checking similarity between two strings in PHP
    677
  13. Simple PHP calendar
    481
  14. Simple PHP code performance measuring example
    799
  15. Convert plain HTML to XHTML
    458
  16. GD library version in PHP
    509
  17. JSON format control in PHP
    696
  18. mysql optimization – if you are using Word Press, do not turn off persistent connection
    596
  19. File downloading function through PHP code
    535
  20. Image file resizing in PHP
    564
  21. Apache server unstable detection and the related server(mysql, apache) restart automatically
    543
  22. Function can extract file name in string having full path in PHP
    572
  23. How to create private URL on S3/CloudFront with time-limit ?
    920
  24. Uploading files to Amazon S3 with REST API in PHP
    845
  25. Human readable random string for captchas in PHP
    566
  26. How to get the duration between days in PHP
    428
  27. Date format validation in PHP
    578
  28. PHP function converts new line to BR tag
    566
  29. Email Validation Snipet in PHP
    386
  30. PHP socket programming to get content with post method
    412
  1. PHP Code to Fetch current Coinbase Assets (Balances)
    444
  2. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    366
  3. Google Single Sign-On implementation with PHP
    1,381
  4. PHP Superglobal Variables do not require additional syntax to access it
    2,656
  5. Run Python Code with Virtual Environment in PHP
    675
  6. PHP Simplified Operators
    318
  7. PHP Heredoc (aka Nowdoc)
    447
  8. PHP Post Processing by disconnecting HTTP connection and continuing the remaining logics
    1,824
  9. WordPress Remote Posting with PHP
    1,700
  10. Google BigQuery Example to converted Nested FIelds in JSON
    461
  11. Verifying Apple In-App Purchase validation receipt with PHP
    1,803
  12. Useful code for file-based Unit Test in PHP
    507
  13. Function Overloading Implementation in PHP with Magic Mathods
    1,764
  14. PHP Magic - the Null Coalescing Operator (??) - return the value if the give variable is NULL
    1,680
  15. How do I find php.ini on Mac?
    495
  16. How do I determine the client IP type (IPv4/IPv6) in PHP
    840
  17. What is 302 Found Redirection in HTTP 1.1?
    497
  18. Implementing a Versatile DNS Server in PHP: Handling A, AAAA, CNAME, and TXT Records
    624
  19. CentOS 7 PHP Apache Kafka: Installation, Examples, and System Diagram
    311
  20. Apache Kafka Explained: Powering Netflix, Building with PHP
    495
  21. Array of arguments passed to script in PHP
    97
  22. Bob Jenkins' One-At-A-Time hashing algorithm in PHP
    57
  23. 32bits simple hash function in PHP
    44
  24. PHP Code Compression Tool by removing whitespace, strips comments - PHP Minifier/Compressor
    1,426
  25. mcrypt missing when using phpMyAdmin on Centos 6.7
    555
  26. How to set AUTO_INCREMENT ID in mySQL ?
    609
  27. Parsing XML in PHP
    1,194
  28. Unzip a ZIP file in PHP
    506
  29. How to get browser information in PHP?
    859
  30. Get Remote IP Address in PHP
    504
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,898
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Invalid Auction Storms in Ad Tech
    106
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  10. The Two Clocks of Ad Server Architecture
    77
  11. Frequency Cap Architecture Overview
    526
  12. Collecting Proof-of-Play from 100,000 Screens
    152
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  14. What is RedisVL?
    114
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  16. TPU & GPU Cluster Management Tools
    257
  17. The Concept of Scaffolding in AI Agents
    244
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  22. Machine Learning: Training vs. Ranking
    229
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  25. Designing a Data Curation System Around a Vector Database
    230
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    672
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232
  30. Understanding Data Lineage
    271