Skip to content

Instantly share code, notes, and snippets.

@jamessom
Created March 26, 2018 03:40
Show Gist options
  • Save jamessom/994a9e48140be6b6e94ff11e92c5366a to your computer and use it in GitHub Desktop.
Save jamessom/994a9e48140be6b6e94ff11e92c5366a to your computer and use it in GitHub Desktop.
Creating and downloading Excel files with Slim

Creating and downloading Excel files with Slim

Maybe you need the possibility to create excel files and automaticly download it.

To be able to create Excel docs I'm using PHPExcel. Here is a tiny example how to create and download the created file directly from your server.

Installation

composer require phpoffice/phpexcel

Controller action

Add a new route and a controller action with this code:

File: config/routes.php

$app->get('/excel', 'App\Controller\ExcelController:downloadExcelAction');
<?php

namespace App\Controller;

use PHPExcel;
use PHPExcel_IOFactory;

class UserController
{
    public function downloadExcelAction(Request $request, Response $response): ResponseInterface
    {
        $excel = new PHPExcel();

        $sheet = $excel->setActiveSheetIndex(0);
        $cell = $sheet->getCell('A1');
        $cell->setValue('Test');
        $sheet->setSelectedCells('A1');
        $excel->setActiveSheetIndex(0);

        $excelWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');

        $excelFileName = __DIR__ . '/file.xlsx';
        $excelWriter->save($excelFileName);

        // For Excel2007 and above .xlsx files   
        $response = $response->withHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $response = $response->withHeader('Content-Disposition', 'attachment; filename="file.xlsx"');

        $stream = fopen('php://memory', 'r+');
        fwrite($stream, file_get_contents($excelFileName););
        rewind($stream);

        return $response->withBody(new \Slim\Http\Stream($stream));
    }
}

Then open the url: http://localhost/project/excel and the download should start automatically.

Downloading CSV files

Creating an CSV file is even simpler.

Create a new route:

$app->get('/csv', 'App\Controller\ExcelController:downloadCsvAction');

Create a new action:

public function downloadCsvAction(Request $request, Response $response): ResponseInterface
{
    $list = array(
        array('aaa', 'bbb', 'ccc', 'dddd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );

    $stream = fopen('php://memory', 'w+');

    foreach ($list as $fields) {
        fputcsv($stream, $fields, ';');
    }
    
    rewind($stream);

    $response = $response->withHeader('Content-Type', 'text/csv');
    $response = $response->withHeader('Content-Disposition', 'attachment; filename="file.csv"');

    return $response->withBody(new \Slim\Http\Stream($stream));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment