GithubHelp home page GithubHelp logo

php-excel-templator's Introduction

PHP Excel Templator

Latest Stable Version Latest Unstable Version License Total Downloads Monthly Downloads Daily Downloads

Инструкция на русском языке (Russian)

It's PHP Spreadsheet extension that allows you to export excel files from an excel template. Using the extension you don’t need to create excel files from scratch using code, set styles and so on.

Demo screenshot:

Demo

Simple example

There is a simplest example of how this might look (using less code). Suppose we have an excel file with the following template variables:

Template

The code will be as follows:

use alhimik1986\PhpExcelTemplator\PhpExcelTemplator;
require_once('vendor/autoload.php'); // if you don't use framework

PhpExcelTemplator::saveToFile('./template.xlsx', './exported_file.xlsx', [
	'{current_date}' => date('d-m-Y'),
	'{department}' => 'Sales department',
]);

As a result, we get:

Exported file

Using this extension, we just create a template file with the styles we need and specify template variables in it. In the code, we just pass the parameters to template variables.

Features

  • We can insert several template variables in one table cell (if the data type is "string")
  • We can insert a one-dimensional array, in this case additional rows will be created in the table
  • We can insert a two-dimensional array, in this case the respective columns and rows are created in the table
  • By specifying the value in the cells, you can change the styles of these cells, even when inserting arrays
  • We can apply the same template on several sheets of the table

Features demo and usage examples are given in the folder "samples".

Restrictions:

  • Possible so-called side effects when using one-dimensional or two-dimensional arrays in one sheet. Especially when it is located asymmetrically. An example of side effects is also given in the folder "samples".

INSTALLATION:

$ composer require alhimik1986/php-excel-templator

Template variable naming rules

The rules can be any, but I can offer my recommendation for naming template variables:

  • {var_name} - for string values
  • [var_name] - for one-dimensional arrays
  • [[var_name]] - for two-dimensional arrays

How to insert a one-dimensional array, so that the table create columns, not rows?

To do this, instead of a one-dimensional array, insert a two-dimensional one as follows:

$param['[[var_name]]'] = [['text 1', 'text 2', 'text 3']];

Using setters

In the example above, the minimum code without setters was used. The data types (for example: a string, a one-dimensional array, or a two-dimensional array) in this code is automatically recognized and the necessary setter is chose. But if we want to use a specific setter, the same code will look like this:

use alhimik1986\PhpExcelTemplator\PhpExcelTemplator;
use alhimik1986\PhpExcelTemplator\params\ExcelParam;
use alhimik1986\PhpExcelTemplator\params\CallbackParam;
use alhimik1986\PhpExcelTemplator\setters\CellSetterStringValue;

require_once('vendor/autoload.php'); // if you don't use framework

$params = [
	'{current_date}' => new ExcelParam(CellSetterStringValue::class, date('d-m-Y')),
	'{department}' => new ExcelParam(CellSetterStringValue::class, 'Sales department'),
];
PhpExcelTemplator::saveToFile('./template.xlsx', './exported_file.xlsx', $params);

At the moment the extension has 3 kinds of setters:

  • CellSetterStringValue (for string values)
  • CellSetterArrayValue (for one-dimensional arrays)
  • CellSetterArray2DValue (for two-dimensional arrays)

You ask, what for specify setters explicitly?

  • First, because it's flexible: let's say you want to create your own setter with your own algorithms that eliminate the side effects, which I mentioned above.
  • Secondly, in each setter, you can pass a callback function in which we can change the styles of the inserted cells. For example, you need to highlight with bold font the employees who made the best sales in this month.

Examples of code that uses all kinds of setters are listed in the folder "samples".

How to set styles without setters?

In most cases to use the setters explicitly is not so convenient. I suppose you want to use minimum code. Therefore, I made it possible to set styles without using setters:

use alhimik1986\PhpExcelTemplator\PhpExcelTemplator;
use alhimik1986\PhpExcelTemplator\params\CallbackParam;
require_once('vendor/autoload.php'); // if you don't use framework

$params = [
	'{current_date}' => date('d-m-Y'),
	'{department}' => 'Sales department',
	'[sales_amount]' => [
		'10230',
		'45100',
		'70500',
	],
];

$callbacks = [
	'[sales_amount]' => function(CallbackParam $param) {
		$amount = $param->param[$param->row_index];
		if ($amount > 50000) {
			$cell_coordinate = $param->coordinate;
			$param->sheet->getStyle($cell_coordinate)->getFont()->setBold(true);
		}
	},
];

PhpExcelTemplator::saveToFile('./template.xlsx', './exported_file.xlsx', $params, $callbacks);

Special setter for special templates (CellSetterArrayValueSpecial)

There are special templates, which require to insert the whole row, and not insert cell with shifting down. Moreover, it's required to merge cells, as well as the cell in which there was a template variable.

Special template

For these templates, a special setter has been created: CellSetterArrayValueSpecial. Examples of code that uses it is given in folder: samples/8_special_template.

Events

The following are possible events and an explanation of why they can be applied:

$events = [
    PhpExcelTemplator::BEFORE_INSERT_PARAMS => function(Worksheet $sheet, array $templateVarsArr) {
        // fires before inserting values into template variables        
    },
    PhpExcelTemplator::AFTER_INSERT_PARAMS => function(Worksheet $sheet, array $templateVarsArr) {
        // fires after inserting values into template variables.
        // It is used if you want to insert values​into a spreadsheet after columns and rows have been created. 
        // For example, when inserting an array of images.
        // If you insert images using $callbacks, then the images can shift to the right due to the fact that on the next line the template variable can create additional columns.
        // See an example: samples/10_images        
    },
    PhpExcelTemplator::BEFORE_SAVE => function(Spreadsheet $spreadsheet, IWriter $writer) {
        // fires before saving to a file. It is used when you need to modify the $writer or $spreadsheet object before saving, for example, $writer->setPreCalculateFormulas(false);        
    },
];
$callbacks = [];
$templateFile = './template.xlsx';
$fileName = './exported_file.xlsx';
$params = [
	// ...
];

PhpExcelTemplator::saveToFile($templateFile, $fileName, $params, $callbacks, $events);

php-excel-templator's People

Contributors

alhimik1986 avatar ma4nn avatar shnoulle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-excel-templator's Issues

Invalid cell coordinate A-1 at

Hi, I receive this error message when I try to render a template with multiple array type columns at once..
Error message: Invalid cell coordinate A-1 at
[descriptions] [quantity] [cost]

example of payload.
$array = [
{descriptions}: ['first','second','third],
{quantity}: [1, 1, 1],
{cost}: [0, 0, 0],
]

If in the template is left only one column it is rendered correctly.

It happens in PhpOffice\PhpSpreadsheet::adjustRowDimensions

using atm alhimik1986/php-excel-templator 1.0.11,
phpoffice/phpspreadsheet : 1.22,

merge cells in two-dimensional arrays

Hi!
Any solutions for use merged cells for two-dimensional arrays...?

'[[sales_amount_by_hours]]' = [
['10000', '20000', '30000', '40000', '50000', '60000', '70000', '80000'],
];
template:
image

result file:
image

want this:
image

thank you

No graph saved

I want to update a template with graph inside.

Then i use for loading

        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        $reader->setIncludeCharts(true);
        $spreadsheet = $reader->load($xlsFile);

And i update/hack alhimik1986\PhpExcelTemplator\getWriter to

	protected static function getWriter(Spreadsheet $spreadsheet)
	{
		$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
		$writer->setIncludeCharts(true);
		return $writer;
	}

But graph still don't shown … :/ any idea ?

Option for CellSetterArrayValueSpecial to fill down formulas alongside it

If I have a table like so:
image

And it is filled using the CellSetterArrayValueSpecial setter, I would like it to carry the formula down with the rows too.

Currently you end up with:

image

Which is not great as the formula is then not used.

I was wondering if it was possible to do this using callbacks on say Threshold but it would need to know how many rows to fill it down and I can't see how to get that in the params.

Any suggestions

Small bug fix - BEFORE_SAVE proposal

Hello,

In the function saveSpreadsheetToFile, you need to change

    if (isset($events['beforeSave']) AND is_callable($events['beforeSave'])) {
        $events['beforeSave']($spreadsheet, $writer);
    }

to

if (isset($events[self::BEFORE_SAVE]) AND is_callable($events[self::BEFORE_SAVE])) {
        $events[self::BEFORE_SAVE]($spreadsheet, $writer);
}

Otherwise BEFORE_SAVE event are never called.

Excel форматирование не работает

Форматирование ячеек в элементах даты не работает эффективно.
Например, когда yyyy / mm / dd установлен в ячейке, в которой задано {current_date},
В следующем коде это будет гггг - мм - дд.
Можно ли применить форматирование ячеек, установленное в Excel?

PhpExcelTemplator::saveToFile($import , $export, [
	'{current_date}' => date('Y-m-d')
]);

[feature] Allow export graph

Allow (more easily) export graph

Currently : to import/export graph : a possible solution was using \PhpOffice\PhpSpreadsheet\IOFactory directly for writer.

    $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
    $reader->setIncludeCharts(true);
    $spreadsheet = $reader->load($xlsFile);
    $params = require('./params.php'); // Or any other way to do param
    foreach($spreadsheet->getSheetNames() as $sheetName) {
        $sheet = $spreadsheet->getSheetByName($sheetName);
        $templateVarsArr = $sheet->toArray();
        PhpExcelTemplator::renderWorksheet($sheet, $templateVarsArr, $params, array(), array());
    }
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->setIncludeCharts(true);
    header('Content-Disposition: attachment; filename="'.$fileName);
    header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Pragma: public');
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    $writer->save('php://output');

Maybe adding an option on outputSpreadsheetToFile and saveSpreadsheetToFile ?

I don't wee how to do it in events, right ?

формулы

Еще вопрос появился: есть возможность использовать стандартные формулы excel?
Например, одна ячейка заполняется по шаблону, соседняя вычисляется по формуле, заданной на этапе редактирования шаблона.

Заполнение статичных данных в таблице.

Здравствуйте! Подскажите пожалуйста, можно ли как-то заполнить статичные данные и формулы которые изначально стоят в шаблоне, чтобы они тоже протягивались вниз вместе с данными массива.

Screenshot_57

PhpSpreadsheet introduced a breaking change in 1.13.0

They've changed the signature of public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pSheet) by adding return type hint of void.

This projects should add a version restriction for the library:

"require": {
  "phpoffice/phpspreadsheet": ">=1.4 <1.13"
}

Meanwhile problem can be solved by composer require phpoffice/phpspreadsheet:1.12.* in one's own project which will override the broken version.

Template with image

I tried to use your library, but with the xlsx template with an image inside, after saving the image disappears

Fields in header not modified

I made a small template with your basic template as base and it's working
But if the fields are in the Header of the page in Excel, fields are not updated, while the same fields are updated if they are on the page.
Just to be sure I have put the same fields in the footer and in a normal cell

exit в функциях

Зачем в конце этих функций exit?
PhpExcelTemplator::outputSpreadsheetToFile
PhpExcelTemplator::saveSpreadsheetToFile

Не сохраняется файл

Подскажите пожалуйста, в чем может быть проблема. Ajax'ом вызываю файл с таким содержимым

require_once('vendor/autoload.php');
$filename = date("Y-m-d");

$templateFile = $_SERVER['DOCUMENT_ROOT'].'templates/shabl_nacl.xlsx';
$fileName = $SERVER['DOCUMENT_ROOT'].'tmp/exported_file'.$filename.'.xlsx';

$path=$_SERVER['DOCUMENT_ROOT'];
$source=$_SERVER['DOCUMENT_ROOT']."/templates/shabl_nacl.xlsx";

$now = new DateTime();

$params = [
'{clinfo}' => new ExcelParam(CellSetterStringValue::class, $now->format('d-m-Y')),
'{docnm}' => new ExcelParam(CellSetterStringValue::class, 'Sales department'),
];

PhpExcelTemplator::saveToFile($templateFile, $fileName, $params);
по итогу должен сохраниться файл, но этого не происходит. Что я делаю не так?

Originally posted by @Liphanes in #1 (comment)

Cells pushed down after first table

I just had it installed with composer and run some of examples. Single table example worked, but when tested 4_side-effects it generated very messed file. Tried basic example, but added second table - the same. First table is OK, but then cells are messed up.

This:

Screenshot_4

Produced this:

Screenshot_3

styles_without_setters

Добрый день.

А как можно ошибки отловить?
PhpExcelTemplator::saveToFile($templateFile, $fileName, $params); - нет проблем.
PhpExcelTemplator::saveToFile($templateFile, $fileName, $params, $callbacks); - нет файла.

Generate the result within the brackets []

I'm a beginner, and I'm not able to generate the result within the brackets []. Would anyone know what I should do?


foreach($sql as $sql){
$input = $sql['CGS_EMPRESA_CLIENTE_CTR_PPU_COD'];
}

PhpExcelTemplator::saveToFile('../excel_templates/'.$file_template, '../temp/'.$file_export,  
[
    '{Cliente}' => $row_ctr['CGS_EMPRESA_CLIENTE_NOME'],
    '{Contrato_Num}' => $row_ctr['CGS_EMPRESA_CLIENTE_CTR_NUMERO'],
    '{Contrato_Nome}' => $row_ctr['CGS_EMPRESA_CLIENTE_CTR_NOME'],
    '[Codigo]' => [array($input)], //['Value1','Value2']
]);
    
//Download
header("Location: ../temp/$file_export");
}

Formula cells have their contents changed

Not sure if this bug has appeared/fixed somewhere, but I couldn't find any help, and I've been trying it all day:

I have this loop in my code:
foreach($report as $prod){ $sheetParams['{id_produto}'][$idx] = $prod['codigo']; $sheetParams['{product_name}'][$idx] = $prod['titulo']; $sheetParams['preco_compra'][$idx] = $prod['preco_compra']; $sheetParams['preco_venda'][$idx] = $prod['precoVenda']; $sheetParams['qde'][$idx] = (int)$prod['qde']; $sheetParams['[subtotalcompra]'][$idx] = '=E'. ($idx+6) . '*C'.($idx+6); $sheetParams['[subtotalvenda]'][$idx] = '=E'. ($idx+6) . '*D'.($idx+6); $sheetParams['[lucro_bruto]'][$idx] = '=G'. ($idx+6) . '-F'.($idx+6); $idx++; }

After filling the arrays, I send it using

PhpExcelTemplator::saveToFile($templateFile, $fileName, $sheetParams);

one of the arrays ([subtotalcompra]) gets the values:
[[subtotalcompra]] => Array ( [0] => '=E6*C6' [1] => '=E7*C7' )

whereas the other ([subtotalvenda]) is

[[subtotalvenda]] => Array ( [0] => '=E6*D6' [1] => '=E7*D7' )

The template file uses them in 2 columns, which should be the multiplication formulas for each row, but only the first row gets the correct values, '=E6*C6' and '=E6*D6'

The other cells get their values as '=E9*D9' and the cell to the right has '=E10*D10'

The indexes for each cell are changed as if the cell count somehow interferes in the string used for the formulas.
Even weirder is that the values are changed as if some regex acts on the string, changing every cell in the resulting spreadsheet.

I could even trace some data change into phpoffice/phpspreadsheet but was unable to find what could be happening before the data changed.

Comments in english

Currently, phpdoc comments are in Russian, make hard to understand.

Are you OK for an english translation ?

Проблемы с обработанным файлом

Здравствуйте.
Во-первых, файл увеличивается более чем в 2 раза после обработки библиотекой (5 кбайт шаблон, 12 кбайт обработанный, хотя в него вставляется всего пара слов).

Во-вторых, при открытии обработанного файла выскакивает следующая ошибка:
"Предупреждение при загрузке документа test2.xlsx:
Данные не могут быть загружены полностью, т.к. превышено максимальное количество столбцов в листе."
Но при этом файл все равно открывается, переменные заменяются, и никаких излишних столбцов нет.
Для открытия использую LibreOffice Calc

Слетает объединение ячеек при вставке массива

Вот пример разметки

A B C D E
[] [] [>] [<] []

C и D обеденены.

Если у нас больше одной строки, то все следующие строки будут разъеденные.
На выходе получим что колонка D будет пустая

A B C D E
[] [] [>] [<] []
[] [] [><] []
[] [] [><] []
[] [] [><] []

Можно ли использовать Open Office и формат .ODS ?

Добрый день!
Очень хорошая, простая в освоении библиотека получилась.
Пробовал работать в связке с MS Excel - всё устраивает.
Но есть острая необходимость создавать файлы формата ODS из шаблона ODS...
Читал. что PhpExcel поддерживает эти и другие схожие форматы файлов. Где можно, если возможно, сделать такие настройки в Вашем проекте?
Спасибо!

too many rows

I am generating an excel and in the parameters I pass an array with 60 items but the excel is generated with approximately 500 unnecessary rows
my code:
`$academicperiods = Academicperiod::where('status', 'Vigente')->firstOrFail();
$periodname=$academicperiods->period_name;
$periodcode = $academicperiods->period_code;
$finalperiodname='ASIGNATURAS A APERTURARSE EN EL PERÍODO '.$periodname.' ('.$periodcode.') ';
//ASIGNATURAS A APERTURARSE EN EL PERÍODO MARZO 2020 - JULIO 2020 (SI-2020)

        $params = [
            '{period}'=>new ExcelParam(CellSetterStringValue::class, $finalperiodname),
            '[subjectgrade]' => new ExcelParam(CellSetterArrayValue::class, $subjectgrade),
            '[subjectdepartment]' => new ExcelParam(CellSetterArrayValue::class, $subjectdepartment),
            '[subjectname]' => new ExcelParam(CellSetterArrayValue::class, $subjectname),
            '[subjectcredits]' => new ExcelParam(CellSetterArrayValue::class, $subjectcredits),
            '[total]' => new ExcelParam(CellSetterArrayValue::class, $total),
            '[spaces]' => new ExcelParam(CellSetterArrayValue::class, $spaces),
            '[observations]' => new ExcelParam(CellSetterArrayValue::class, $observations)
        ];

        $saveAs = 'storage/files/3/Proyecciones de Matrícula/ReporteProyecciónMatrícula.xlsx';

        PhpExcelTemplator::saveToFile($documentTemplate, $saveAs, $params);`

all the arrays have 60 items but my excel is exported with 500+-

Multiple merged cell callback errors,will be a lot more lines

template
image

$params    = [
            "[departmentName]"                              => array_pluck($list, 'department'),
            "[name]"                                        => array_pluck($list, 'name'),
            ]    

result

image

Looking from the source code, I found out that there are more cells from the updateCellReference.
My English is not good. Is there any problem with me?

Группировка строк и/или колонок

Данные:

$data = [
    'android' => [
        ['lenovo 898t', 2, 50],
        ['htc one', 3, 100]
    ],
    'apple' => [
        ['iphone 4s', 4, 100],
        ['iphone 5s', 6, 200]
    ]
];

предполагаемый шаблон:
image

что хочется получить
image

В документации не нашел как сформировать объединяющую ячейку по вертикали или горизонтали. @alhimik1986
example.xlsx

setPreCalculateFormulas

Есть ли процедура, чтобы сделать $ writer-> setPreCalculateFormulas (false) с PhpExcelTemplator :: saveToFile ()?

Вставляются пустые строки

При вставке в шаблон вставляется X строк с данными и потом еще столько же пустых строк

Максимально простой пример, где видно этот баг

<?php

namespace App\controllers;

use alhimik1986\PhpExcelTemplator\PhpExcelTemplator;

/*
Шаблон Excel максимально простой
в ячейке A1 Имя
в ячейке A2 [NAME]
*/

class Excel
{

    public function index(): void
    {    
        $templateFile = './template/register.xlsx';
        $fileName = './register.xlsx';
        
        $data['[NAME]'] = [
            'Ivan',
            'Nata',
            'Irina',
        ];

        PhpExcelTemplator::saveToFile($templateFile, $fileName, $data);
    }

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.