Git Product home page Git Product logo

excel's Introduction

cewi/excel plugin for CakePHP

The plugin is based on the work of [dakota] (https://github.com/dakota/CakeExcel) and uses PHPExcel for the excel-related functionality.

Installation

You can install this plugin into your CakePHP application using composer.

The recommended way to install composer packages is:

add

"repositories": [
         {
            "type": "vcs",
            "url": "https://github.com/cewi/excel"
        }
    ] 

to your composer.json because this package is not on packagist. Then in your console:

composer require cewi/excel

should fetch the plugin. Load the Plugin in the bootstrap() method in Application.php as ususal:

$this->addPlugin('Cewi/Excel');

RequestHandler Component is configured by the Plugin's bootstrap file. But you could do this also in a controller's initialize method, e.g.:

public function initialize()
	{
        	parent::initialize();
        	$this->loadComponent('RequestHandler', [
            		'viewClassMap' => ['xlsx' => 'Cewi/Excel.Excel']
        	]);
        }

Be careful: RequestHandlerComponent is already loaded in your AppController by default. Adapt the settings to your needs.

You need to set up parsing for the xlsx extension. Add the following to your config/routes.php file before any route or scope definition:

Router::extensions('xlsx');

you can configure this also within a scope:

$routes->setExtensions(['xlsx']);

(Setting this in the plugin's config/routes.php file is currently broken. So you do have to provide the code in the application's config/routes.php file)

You further have to provide a layout for the generated Excel-Files. Add a folder xlsx in src/Template/Layout/ subdirectory and within that folder a file named default.ctp with this minimum content:

<?= $this->fetch('content') ?>

You can create Excel Workbooks from views. This works like in dakota's plugin. Look there for docs.

Additions in this Plugin:

1. ExcelHelper

Has a Method 'addworksheet' which takes a ResultSet, an Entity, a Collection of Entities or an Array of Data and creates a worksheet from the data. Properties of the Entities, or the keys of the first record in the array are set as column-headers in first row of the generated worksheet. Be careful if you use non-standard column-types. The Helper actually works only with strings, numbers and dates.

Register xlsx-Extension in config/routes.php file before the routes that should be affected:

Router::extensions(['xlsx']);

Example (assumed you have an article model and controller with the usual index-action)

Include the helper in ArticlesController:

public $helpers = ['Cewi/Excel.Excel'];

add a Folder 'xlsx' in Template/Articles and create the file 'index.ctp' in this Folder. Include this snippet of code to get an excel-file with a single worksheet called 'Articles':

$this->Excel->addWorksheet($articles, 'Articles');

create the link to generate the file somewhere in your app:

<?= $this->Html->link(__('Excel'), ['controller' => 'Articles', 'action' => 'index', '_ext'=>'xlsx']); ?>

done. The name of the file will be the lowercase plural of the entity with '.xslx' added, e.g. 'articles.xlsx'. If you like to change that, add

$this->Excel->setFilename('foo');

in the Template file. The filename now will be 'foo.xlslx'.

2. ImportComponent

Takes a excel workbook, extracts a single worksheet with data (e.g. generated with the helper) and generates an array with data ready for building entities. First row must contain names of properties/database columns.

Include the Import-Component in the controller:

 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('Cewi/Excel.Import');
 }

than you can use the method

prepareEntityData($file = null, array $options = [])

E.g. if you've uploaded a file:

move_uploaded_file($this->getRequest()->getData('file.tmp_name'), TMP . DS . $this->getRequest()->getData('file.name'));
$data = $this->Import->prepareEntityData(TMP . $this->getRequest()->getData('file.name'));

and you'll get an array with data like you would get from the Form-Helper.

You then can generate and save entities in the Controller:

$entities = $table->newEntities($data);
foreach ($entities as $entity) {
     $table->save($entity, ['checkExisting' => false])
}

If your table is not empty and you don't want to replace records in the database, set 'append'=>true in the $options array:

$data = $this->Import->prepareEntityData($file, ['append'=> true]);

If there are more than one worksheets in the file you can supply the name or index of the Worksheet to use in the $options array, e.g.:

$data = $this->Import->prepareEntityData($file, ['worksheet'=> 0]);

or

$data = $this->Import->prepareEntityData($file, ['worksheet'=> 'Articles']);

excel's People

Contributors

casmo avatar cewi avatar dewwwald avatar

Stargazers

 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

excel's Issues

Generating excel is slow. Trying to overwrite method

Hey guys, I'm having problem with slow generation of excel file. Data are from DB as basic ResultSet. In my test set I have 8 rows with 5 cells and generating excel is taking around 20 seconds. I also checked, if it wasn't DB related problem but no, it's somewhere in Excel generation. I also tried not to use 'addWorksheet()' method and code it by myself, but all i can do is create new sheet in my view file with $this->PHPExcel, but when I try to set data with 'fromArray()' or with loop and method 'setCellValue' I get empty sheet - no data in result excel. Can you please help me?

PHPExcelHelper could not be found.

Hi guys,
I am trying to use this plugin, but the problem " PHPExcelHelper could not be found. "

In AppController
$this->loadComponent('RequestHandler',['viewClassMap' => ['xlsx' => 'Cewi/Excel.Excel']]);

In my Controller
public $helpers = ['Cewi/Excel.Excel'];

in my view:
$this->Excel->addWorksheet($matches, 'controllersStatus');

phpexcel is in:
vendor/phpoffice/phpexcel

i think this can be solved with
require_once(ROOT. DS .'vendor'.DS.'phpoffice/phpexcel/Classes');

but nothing happen i dont where to put the require_once sentence! some help will be amazing.
thanks

composer require failed

Thanks for this plugin. I am trying to run composer require Cewi/Excel after adding
"repositories": [
{
"type": "vcs",
"url": "https://github.com/cewi/excel"
}
],
on my composer.json but i get the following error
"[InvalidArgumentException] Could not find package Cewi/Excel at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability"

Please help

Problems to use the plugin

Hello,
I have problems to use your plugin (cakePHP v3.1)
To enable the extensions I add this line to routes.php file: "Router :: extensions (['xlsx']);"
The "AddTable" method does not seem to exist

Is the documentation is up to date, or is something missing?
Thank you

Plugin Helper not found

I have just installed the plugin in my local environment and succesful created the first downloads to excel. After tranfering it to the production server, it is not finding the helper class on the path where it is indead.
I have followed the short discription found here.
Changes made in
bootstrap.php
routes.php
appcontroller.php
as your advices.
Could you give an additional hint please?

Import & Edit

I want to be able to import an excel file to edit multiple records. That's possible?

Import Dates

Hi again!

This time I have a problem when trying to import dates from excel.

I have this type of fields in excel with dates '2016-05-12' ready to enter the database. But, the import does not validate the field!

give this error:

'[errors]' => [
'birth_date' => [
'date' => 'The provided value is invalid'
],
'entry_date' => [
'date' => 'The provided value is invalid'
]
],
'[invalid]' => [
'birth_date' => (float) 42714,
'entry_date' => (float) 42623
],

My fields are of type 'Date' for cakephp to validate. What type of field should I use in this case?
Thanks!

Cewi/Excel Deprecation

I have used the plugin in my cakephp app and I have put in my DigitalOcean server. So my server is running with PHP 7.2.19 and I couldn't find a solution why it affecting to run cake.
The error I get,
"Deprecation warning: require.Cewi/Excel is invalid, it should not contain uppercase characters. Please use cewi/excel instead. Make sure you fix this as Composer 2.0 will error. Do not run Composer as root/super user! See https://getcomposer.orgroot for details."
Every time I try to update composer, this warning comes and tells Cewi/Excel plugin is deprecated.

Can you help me with this problem?

PHPExcelHelper could not be found.

I have this error with your plugin.

Error: PHPExcelHelper could not be found.

⟩ Cake\View\HelperRegistry->_throwMissingClassError
CORE/src/Core/ObjectRegistry.php, line 91
⟩ Cake\Core\ObjectRegistry->load
CORE/src/View/HelperRegistry.php, line 67
⟩ Cake\View\HelperRegistry->__isset
CORE/src/View/View.php, line 903
⟩ Cake\View\View->__get
ROOT/vendor/Cewi/Excel/src/View/Helper/ExcelHelper.php, line 196
⟩ Cewi\Excel\View\Helper\ExcelHelper->addSheet
ROOT/vendor/Cewi/Excel/src/View/Helper/ExcelHelper.php, line 89
⟩ Cewi\Excel\View\Helper\ExcelHelper->addWorksheet
APP/Template/Pages/home.ctp, line 228
⟩ include
CORE/src/View/View.php, line 1012
⟩ Cake\View\View->_evaluate
CORE/src/View/View.php, line 971
⟩ Cake\View\View->_render
CORE/src/View/View.php, line 595
⟩ Cake\View\View->render
CORE/src/Controller/Controller.php, line 617
⟩ Cake\Controller\Controller->render
APP/Controller/PagesController.php, line 58
/var/www/public/vendor/Cewi/Excel/src/View/Helper/ExcelHelper.php toggle arguments
     * @return void
     */
    public function addSheet($title = '')
    {
        $this->_**View->PHPExcel**->createSheet();
        $this->_View->currentSheetIndex++;
        $this->_View->PHPExcel->setActiveSheetIndex($this->_View->currentSheetIndex);
        $this->_View->PHPExcel->getActiveSheet()->setTitle($title);
        $this->_View->PHPExcel->getProperties()->setTitle($title);

thanks

not working with routes

I have test your plugin, it's not working when i add routes to my CakePHP 3.4.
I have added the Router::extensions('xlsx') inside Config/routes.php, also inside Router::scope('/',.....)
but it does not know what controller what action to go, it just add .xlsx to the root URL ( like so: http://localhost/myappname.xlsx ) but without routes it's working.

Export Data- Giving Format to Excel column

Hi guys,
i have this issue: when i export a varchar from a sql query, example: name = '000782541245', in the column it put '782541245' and i need the 3 zeros in the begin.

There is a way to giving format text for the excel column.
Do i make myself understand?

Composer Require

I have php 7 and cakephp 3.5 when I go to install by composer I get this error:

[InvalidArgumentException]
Could not find a matching version of package Cewi/Excel. Check the package spelling, your version constraint and th
at the package is available in a stability which matches your minimum-stability (stable).

Does the plugin serve with these requirements?

Creating worksheets with Date objects

Any ideas for how to work around Date objects from CakePHP queries?

Error: Cannot use object of type Cake\I18n\Date as array
File /var/www/html/app/vendor/phpoffice/phpexcel/Classes/PHPExcel/Cell/DefaultValueBinder.php
Line: 90

Sample data:

App\Model\Entity\Account Object
(
[id] => 2
[deal_id] => 56
[contact_id] => 5273
[cb_contact_id] => 5302
[deal_type] => F
[app_type] => I
[status] => Active
[location_id] => 2
[stock_no] => CHE60856
[contract_date] => Cake\I18n\Date Object
(
[time] => 2016-03-22T00:00:00+00:00
[timezone] => UTC
[fixedNowTime] =>
)
)

Import Excel

Hi!
I'm trying to import excel with the steps of README. This is what I did:

In my Entity Controller:

class ProductsController extends AppController
{
public $helpers = ['Cewi/Excel.Excel'];

public function initialize()
{
parent::initialize();
$this->loadComponent('Cewi/Excel.Import');
}
public function importProducts()
{
$table = TableRegistry::get('Products');
$data = $this->Import->prepareEntityData(TMP . $this->request->data['content']['tmp_name']);
$products = $table->newEntities($data);
foreach ($products as $product) {
$table->save($product, ['checkExisting' => false]);
}
}

In my view import_products.ctp

Form->create($product, ['type'=>'file']) ?> Form->input('content',['type'=>'file']); ?> Form->button(__('Import')) ?> Form->end() ?>

But I get these errors:

file_get_contents failed to open stream: No such file or directory [ROOT\vendor\phpoffice\phpexcel\Classes\PHPExcel\Shared\OLERead.php, line 85]
fopen failed to open stream: No such file or directory [ROOT\vendor\phpoffice\phpexcel\Classes\PHPExcel\Reader\Abstract.php, line 203]

I don't know what lacked. What was wrong with my code?

Thanks for your help!

Export current results

No way of exporting current results, each time you click on export link, you pass through the action then retrieving data, then export to excel, but what if any one wants to export data after doing a search or filtering data then he/she wants to export that results? he/she can't because he will need to pass to the action some additional data to the query.

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.