Using an existing spreadsheet as a template PHPspreadsheet

rpm192 picture rpm192 · Jan 9, 2018 · Viewed 7.6k times · Source

Objective

I want to use an existing Excel sheet, as a template to create an invoice.

  • Cell styling, such as coloring have to be included
  • An image (logo) has to be included
  • Standard data such as company address has to be included

I've read something about cfspreadsheet, but I'm not entirely sure how to use it.

Question A:

Is there a way to use a template file? Or do you know any alternatives?

Question B

Is it possible to use $_POST data with this library?

Example

$data = $_POST['example'];

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', '$data');

Answer

Cédric MEYER picture Cédric MEYER · Feb 15, 2018

I am not 100% sure, but according to PhpSpreadsheet's doc, you can read a local file (your pre-made template) with :

$inputFileName = './sampleData/example1.xls';

/** Load $inputFileName to a Spreadsheet Object  **/
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);

Or in case you already know the file type (.xlsx or .xsl) :

$inputFileType = 'Xls'; // Xlsx - Xml - Ods - Slk - Gnumeric - Csv
$inputFileName = './sampleData/example1.xls';

/**  Create a new Reader of the type defined in $inputFileType  **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/**  Load $inputFileName to a Spreadsheet Object  **/
$spreadsheet = $reader->load($inputFileName);

You can also wrap all of that in a try catch if you want.

Then you just have to make changes the same way you would populate a Spreadsheet you created, populating cells with data you get from pretty much where you want with php, examples :

  • Classic variable $foo = 'bar';
  • $_GET / $_POST / $_REQUEST
  • From a Database