Skip to content

Instantly share code, notes, and snippets.

@bablukpik
Forked from r-sal/PHPExcel_Basics.md
Created January 23, 2017 07:16
Show Gist options
  • Select an option

  • Save bablukpik/07439a866b0927b7b96bd6625b2aa80d to your computer and use it in GitHub Desktop.

Select an option

Save bablukpik/07439a866b0927b7b96bd6625b2aa80d to your computer and use it in GitHub Desktop.
PHPExcel Notes and code snippets

Basics

Creating a new PHPExcel Object.

$this->PHPExcel = new PHPExcel();

Working with sheets

Creating a new sheet:
`$this->activeSheet = $this->PHPExcel->createSheet();`
Getting the active Sheet:
```$this->activeSheet = $this->PHPExcel->getActiveSheet();```

Creating a new sheet: $this->activeSheet = $this->PHPExcel->createSheet();
Getting the active Sheet: $this->activeSheet = $this->PHPExcel->getActiveSheet();
Renaming a worksheet: $this->activeSheet->setTitle($title);

Setting the active sheet:

$sheetIndex = 2;
$this->PHPExcel->setActiveSheetIndex($sheetIndex)

Setting column width
Setting width for a single column:

$this->activeSheet
    ->getColumnDimension($colString)
    ->setWidth($width);

Setting the default width for all columns on a sheet:

$this->activeSheet
    ->getDefaultColumnDimension()
    ->setWidth($width);

Setting row height
Setting the default row height for an entire sheet:

$this->activeSheet
    ->getDefaultRowDimension()
    ->setRowHeight($height);

Writing to cells

Text can be added to a cell using setCellValue($colRow, $data)
$colRow - The column and row to write to (i.e. 'A2')
$data - The data to write

    $this->activeSheet->setCellValue($colRow, $data);       
    $this->activeSheet->setCellValueByColumnAndRow($column, $row, $data);  
    $this->activeSheet->setCellValueExplicit($coord, $value, $dataType);  
    $this->activeSheet->setCellValueExplicitByColumnAndRow($col, $row, $value, $dataType);  

Writing from arrays

A 2-dimensional array can be written to the current sheet usng fromArray($twoDimArray)

  • $twoDimArray - the 2D array to be written
  • $useWhenNull - what to use if there is a null value
  • $topLeftCorner - where the top left corner should be.
$this->activeSheet->fromArray($sheet);  
$this->activeSheet->fromArray($sheet, "", $colRow);  

Or the array can be written manually by looping through the array and calling setCellValue

foreach($rows as $row => $columns) {
    foreach($columns as $column => $data) {
        $this->activeSheet->setCellValue($column.$row, $data);
    }
}

Adding styles

Setting default styles for the active sheet

$this->activeSheet
    ->getDefaultStyle()
    ->applyFromArray($this->defaultStyle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment