Insert Columns In Xlsx Files

| June 27, 2022 | 592 views | PhpSpreadsheet

Insert additional columns in xlsx files in PhpSpreadsheet.

Requirements:

  • Composer
  • PHP 7.2 or newer

Result without inserting new columns.

Step 1.

Setup dependencies.

{
    "require": {
        "phpoffice/phpspreadsheet": "^1.3"
    }
}

Step 2.

Install phpspreadsheet.

$ composer install

Step 3.

Create a new PHP file, and start coding.

<?php

// Autoload dependencies
require 'vendor/autoload.php';

// Import the core class of PhpSpreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;

// Import the Xlsx writer class
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();

// Retrieve the current active worksheet
$sheet = $spreadsheet->getActiveSheet();

/**
 * Loop through 'Column A - D'.
 */
foreach (range('A', 'D') as $letter) {
    // Set some data to 'Column A - D' of 'Row 5'
    $sheet->setCellValue($letter . '5', 'Column ' . $letter);
}

/**
 * Insert 2 new columns before column 'C'.
 * 
 * The created data above from column 'C'
 * will now be moved to column 'E'.
 */
$spreadsheet->getActiveSheet()->insertNewColumnBefore('C', 2);
$sheet->setCellValue('C5', 'New C5');
$sheet->setCellValue('D5', 'New D5');

// Write a new .xlsx file
$writer = new Xlsx($spreadsheet);

// Save the new .xlsx file
$writer->save('insert-columns-in-xlsx-files.xlsx');

Test.

Run the following codes.

$ php insert-columns-in-xlsx-files.php

Result.

Open the generated file insert-columns-in-xlsx-files.xlsx.

References:

0 Comments

Leave a Reply

Your email address will not be published.