Hello World spreadsheet with PHPExcel

Back in October I posted about PHPExcel, a library which allows you to read and write Excel spreadsheets in PHP with minimum fuss. Today I’m going to show you a simple Hello World example for creating a basic spreadsheet which you can open in Excel and LibreOffice.

The basic steps for creating a file are:

  1. Include the relevant Writer class (depending on the file version you want – Excel 2003, 2007 etc.)
  2. Create a spreadsheet object.
  3. Select the first worksheet (you can add more if required, but one always exists to begin with).
  4. Set the values of cells in the worksheet.
  5. Create a writer object containing the spreadsheet object.
  6. Save the writer object to disc.

A simple Hello World example follows:

<?php

require_once 'PHPExcel.php';
require_once 'PHPExcel/Writer/Excel2007.php';

$spreadsheet = new PHPExcel();
$spreadsheet->setActiveSheetIndex(0);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->SetCellValueByColumnAndRow(0, 1, 'Hello World');

$writer = new PHPExcel_Writer_Excel2007($spreadsheet);
$writer->save('hello-world.xlsx');

?>

As you can hopefully see from the example, writing basic data is a simple task, and the ability to set cell values by numeric column/row indexes makes iteration easy. The only thing to be aware of is that column numbering starts at 0, but rows start at 1. For example, a cell reference of A1 (top-left cell) is 0,1, not 0,0 or 1,1.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.