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:
- Include the relevant Writer class (depending on the file version you want – Excel 2003, 2007 etc.)
- Create a spreadsheet object.
- Select the first worksheet (you can add more if required, but one always exists to begin with).
- Set the values of cells in the worksheet.
- Create a writer object containing the spreadsheet object.
- 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.