Coder Social home page Coder Social logo

kartik-v / yii2-export Goto Github PK

View Code? Open in Web Editor NEW
165.0 15.0 126.0 611 KB

A library to export server/db data in various formats (e.g. excel, html, pdf, csv etc.)

Home Page: http://demos.krajee.com/export

License: Other

PHP 96.42% CSS 0.25% JavaScript 3.33%
php spreadsheet yii2 excel html pdf export grid

yii2-export's Introduction

Krajee Logo
yii2-export
Donate       kartikv

Stable Version Unstable Version License Total Downloads Monthly Downloads Daily Downloads

A library to export server/db data in various formats (e.g. excel, html, pdf, csv etc.) using the PhpSpreadsheet library. The widget allows you to configure the dataProvider, columns just like a yii\grid\GridView. However, it just displays the export actions in form of a ButtonDropdown menu, for embedding into any of your GridView or other components.

In addition, with release v1.2.0, the extension also displays a handy grid columns selector for controlling the columns for export. The features available with the column selector are:

  • shows a column picker dropdown list to allow selection of columns for export.
  • new container property allows you to group the export menu and column selector dropdowns.
  • new template property for manipulating the display of menu, column selector or additional buttons in button group.
  • allows configuration of column picker dropdown button through columnSelectorOptions
  • auto-generates column labels in the column selector. But you can override displayed column labels for each column key through columnSelector property settings.
  • allows preselected columns through selectedColumns (you must set the selected column keys)
  • allows columns to be disabled in column selector through disabledColumns (you must set the disabled column keys)
  • allows columns to be hidden in column selector through hiddenColumns (you must set the hidden column keys)
  • allows columns to be hidden from both export and column selector through noExportColumns (you must set the no export column keys)
  • toggle display of the column selector through showColumnSelector property
  • column selector is displayed only if asDropdown is set to true.

The extension offers configurable user interfaces for advanced cases using view templates.

  • exportColumnsView allows you to setup your own custom view file for rendering the column selector dropdown.
  • afterSaveView allows you to setup your own after save view file if you are configuring to save exported file on server.

Demo

You can see detailed documentation and demonstration on usage of the extension.

Release Changes

NOTE: Refer the CHANGE LOG for details on changes to various releases.

Installation

The preferred way to install this extension is through composer.

Note: Read this web tip /wiki on setting the minimum-stability settings for your application's composer.json.

Pre-requisites

Install the necessary pre-requisite (Krajee Dropdown Extension) based on your bootstrap version:

  • For Bootstrap v5.x install the extension kartik-v/yii2-bootstrap5-dropdown
  • For Bootstrap v4.x install the extension kartik-v/yii2-bootstrap4-dropdown
  • For Bootstrap v3.x install the extension kartik-v/yii2-dropdown-x

For example if you are using the Bootstrap v5.x add the following to the require section of your composer.json file:

"kartik-v/yii2-bootstrap5-dropdown": "@dev"

Install

Either run:

$ php composer.phar require kartik-v/yii2-export "@dev"

or add

"kartik-v/yii2-export": "@dev"

to the require section of your composer.json file.

Note: you must run composer update to have the latest stable dependencies like kartik-v/yii2-krajee-base

Pre-requisites

The yii2-export extension is dependent on yii2-grid extension module. In order to start using yii2-export, you need to ensure setup of the gridview module in your application modules configuration file. For example:

'modules' => [
    'gridview' => [
        'class' => 'kartik\grid\Module',
        // other module settings
    ]
]

Usage

ExportMenu

use kartik\export\ExportMenu;
$gridColumns = [
    ['class' => 'yii\grid\SerialColumn'],
    'id',
    'name',
    'color',
    'publish_date',
    'status',
    ['class' => 'yii\grid\ActionColumn'],
];

// Renders a export dropdown menu
echo ExportMenu::widget([
    'dataProvider' => $dataProvider,
    'columns' => $gridColumns,
    'clearBuffers' => true, //optional
]);

// You can choose to render your own GridView separately
echo \kartik\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns
]);

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

License

yii2-export is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

yii2-export's People

Contributors

aayaresko avatar acerix avatar aikon2 avatar ananthhh avatar arnaud-g1 avatar bmsrox avatar bscheshirwork avatar deividas1 avatar edofre avatar fallingdust avatar friek108 avatar fsateler avatar gorbachevpavel avatar harloprillar avatar ittaskeu avatar karneds avatar kartik-v avatar ksideks avatar lenasterg avatar mortezakarimi avatar muhammadcahya avatar richweber avatar rodion-k avatar romeromsk avatar scotthuangzl avatar sensetivity avatar stivehu avatar tibee avatar tonisormisson avatar tphan-tx 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

yii2-export's Issues

Data unfiltered after pjax

If I filter by something and tab to next column so that pjax update occurs, when I export the data is unfiltered. If I refresh the browser window before export then the export works filtered - which is what I would expect.

Missing versioned dependency on kartik-v/yii2-krajee-base

yii2-export (transitively) depends on kartik-v/yii2-krajee-base, but it requires a new enough version. Installing yii2-export will not cause composer to update yii2-krajee-base to a new enough version. Please add a versioned dependency so that this happens automatically.

Export Menu Button Not Expanding to Show Export Menu

Hi, i'm fairly new to Yii development but the menu isn't displaying when I click on the button - i think the code is OK but I can't figure ok what is wrong. The grid is showing fine just the button which doesn't work.

Thanks

Code:

ExportMenu::widget([
    'dataProvider' => $dataProvider,
    'columns' => $gridColumns,
    'fontAwesome' => true,
    'dropdownOptions' => [
        'label' => 'Export All',
        'class' => 'btn btn-default',           
    ]
]) . "<hr>\n" .

GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => $gridColumns,
        ]
);

How to embed Japanese font to pdf file?

I have trouble with Japanese charaters when export to PDF format. All Japanese character transform to rectangle character after downloaded.
Could you help me find a way to embed Japanese font to pdf file.

Thanks in advance.

How can I add text before header in report?

I want to add some text before column and data.
I need shift report to second row and add some text.
I can not to do it, because _beginRow is private property (I can not expand this class and create getter to this property).
Why have you created private properties (why not protected)?
Maybe can you add some property in widget, with text before data in report?

Does not render grid view

The current code, when not triggering the excel download, does the following:

 if (!$this->_triggerDownload) {
    $this->registerAssets();
    echo $this->renderExportMenu();
    return;
}

I believe a parent::run() call is missing.

Buffer emulation

Hello!
Nice extension! It's not new issue, but I would like to suggest you add a buffer emulation properties or callback on save. It is useful when output_buffering is disabled or has small size.
Example:

function SaveViaTempFile($exportMenu, $writer, $filePath)  {
    $writer->save($filePath);
    $exportMenu->setHttpHeaders();
    readfile($filePath);
    @unlink($filePath);
    $exportMenu->destroyPHPExcel();
    exit();
}

Adding new attribute inside option select2

=== sorry wrong place; closed;

i have script :

echo $form->field($model, 'data')->widget(Select2::classname(), [
'data' => [array_merge(["" => ""], $data)],
'options' => [
'placeholder' => 'Select Data Name',
'multiple' => false,
],
]);

and the result in html :

<select id="storymapdata-data" class="form-control kv-hide input-md" name="Storymapdata[data]">
<optgroup label="0">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</optgroup>
</select>

and my question, how to add attribute 'data-type' inside option?, i want to like this :

<option value="1" data-type="wms">Option 1</option>
<option value="2" data-type="geojson">Option 2</option>

Is it possible to explicitly set Excel cells types?

It throws the 'Class kartik\widgets\AssetBundle not found' exception. Could you please change the namespaces to 'use kartik\base\AssetBundle' for those who don't import the yii2-widgets module?

Also I have the following question. Currently in the generated Excel file all cells have the default Excel's 'general' format. In this case some big numbers are displayed in exponential form. Is it possible to somehow change those cells format to 'numeric' on exporting?

Problem with export

Hi,

When I have in my view this, the widget export the html code too (#div class="compra-index"#, etc..) and the excel don't open the file:

<div class="compra-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a('Criar adjudicação', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?php
        echo ExportMenu::widget([
        'dataProvider' => $dataProvider,
        'columns' => $gridColumns,
        'columnSelectorOptions'=>[
            'label' => 'Cols...',
        ],
        'fontAwesome' => true,
        'dropdownOptions' => [
            'label' => 'Exportar tudo',
            'class' => 'btn btn-default'
        ]
        ]) . "<hr>\n".
    GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => $gridColumns,

    ]);        
    ?>

</div>

Can I do this or is anything wrong with my code? Can I put the ExportMenu after a div?

My grid-export.cvs have this data:

<div class="compra-index">

    <h1>Adjudicações</h1>

    <p>
        <a class="btn btn-success" href="/compra/create">Criar adjudicação</a>    </p>

    "#","Ano","Prazo inicio","Prazo fim","Diversos","Valor",""
"1","2015_RC.com","2015-01-22","2015-02-07","sdbhdfg","222,00",""
"2","2015_Acordos Quadro","2015-03-02","2015-03-28","sdfgfgdfgfsdgdfg","356,00",""

yii2 export config

I try to use from kartik-v: yii2-export (with the module grid)
git: https://github.com/kartik-v/yii2-export (grid from kartik-v: http://demos.krajee.com/grid)
Did not get to do the export setting (put delimiter, create your own name for the file);

On site:
http://demos.krajee.com/grid
written default settings:
"The default exportConfig is setup as below".

For their changes I write settings in a property: [i]exportConfig[/i] in GridView.

No results are not present, the file is exported with the default settings. And the property itself "exportConfig" successfully parsed like widget GridView, by parseExportConfig.

Since I am suffering for about a day with this, I decided to tweak these settings, the "default", but it does not give (. Settings loaded unclear from where ((

[code]use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\export\ExportMenu;

$gridColumns = [
['class' => 'yii\grid\SerialColumn'],
'idproduct',
'name',
'mainImg',
['class' => 'yii\grid\ActionColumn'],
];

// Renders a export dropdown menu
echo ExportMenu::widget([
    'dataProvider' => $dataProvider,
    'columns' => $gridColumns
]);

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'exportConfig'=> [
        GridView::CSV=>[
            'label' => 'CSV',
            'icon' => '',
            'iconOptions' => '',
            'showHeader' => false,
            'showPageSummary' => false,
            'showFooter' => false,
            'showCaption' => false,
            'filename' => 'yii',
            'alertMsg' => 'created',
            'options' => ['title' => 'Semicolon -  Separated Values'],
            'mime' => 'application/csv',
            'config' => [
                'colDelimiter' => ";",
                'rowDelimiter' => "\r\n",
            ], 
        ],
    ],
]);  [/code]

Export UTF8

When I export to CSV File, utf-8 characters are showed as symbols

composer update error, phpexcel version should be ~1.8.0

phpexcel lastest version is 1.8.1, when i composer update, there is a error notice,
it said, phpexcel should be1.8.1.
so, we should modify composer.json like this:
"require": {
"kartik-v/yii2-grid": "*",
"phpoffice/phpexcel": "~1.8.0"
},
thank you.

THE ERROR NOTICE IS:
Problem 1
- hscstudio/yii2-heart dev-master requires phpoffice/phpexcel dev-master -> satisfiable by phpoffice/phpexcel[dev-master].
- hscstudio/yii2-heart dev-master requires phpoffice/phpexcel dev-master -> satisfiable by phpoffice/phpexcel[dev-master].
- Can only install one of: phpoffice/phpexcel[1.8.0, dev-master].
- Can only install one of: phpoffice/phpexcel[dev-master, 1.8.0].
- kartik-v/yii2-export dev-master requires phpoffice/phpexcel 1.8.0 -> satisfiable by phpoffice/phpexcel[1.8.0].
- Installation request for kartik-v/yii2-export dev-master -> satisfiable by kartik-v/yii2-export[dev-master].
- Installation request for hscstudio/yii2-heart dev-master -> satisfiable by hscstudio/yii2-heart[dev-master].

lastModifiedBy must not be set to datetime

You set lastModifiedBy in document properties as datetime, but this property must contain user name.
You can check this in properties when file is opened in MS Excel.

Export in Mac OS

Hi,

why in Mac Os all files exported have .html. To open a excel file a have xlsx.html and I have to delete . html to open the file.

thank you.

Export Menu Button Not Expanding

Hi,

The buttons not expanding the options. The grid work ok.

In my html source I have the options but when I click in the buttons (columns | export) nothing happens:

<div class="btn-group">

    <button id="w1" class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Export data in selected format" href="#" aria-expanded="false">

            <i class="glyphicon glyphicon-export"></i>

             Export All 

            <span class="caret"></span>
        </button>
        <ul id="w2" class="dropdown-menu">
            <li title="Linguagem de Marcação de Hipertexto"></li>
            <li title="Valores separados por vírgula"></li>
            <li title="Texto delimitado por tabulações"></li>
            <li title="Documento em formato PDF"></li>
            <li title="Microsoft Excel 95+ (xls)"></li>
            <li title="Microsoft Excel 2007+ (xlsx)"></li>
        </ul>
    </div>

</div>

My view:

<?php

use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\export\ExportMenu;
use yii\helpers\ArrayHelper;
use common\models\AcordonegociacaoAno;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Adjudicações';
$this->params['breadcrumbs'][] = $this->title;

// the grid columns setup (only two column entries are shown here
// you can add more column entries you need for your use case)
$gridColumns = [
    ['class' => 'yii\grid\SerialColumn'],
    'id',
    [
        'attribute'=>'acordonegociacao_ano_id',
        'label'=>'Ano',
        'vAlign'=>'middle',
        'width'=>'190px',
        'value'=>function ($model, $key, $index, $widget) {
            return Html::a($model->acordonegociacaoAno->nome, '#', []);
        },
        'format'=>'raw'
    ],
    'diversos',
    'contrato_inicio',
    'contrato_inicio',
    ['attribute'=>'valor','format'=>['decimal',2]],
    ['class' => 'yii\grid\ActionColumn']
];

?>
<div class="compra-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a('Criar adjudicação', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <?php
        echo ExportMenu::widget([
        'dataProvider' => $dataProvider,
        'columns' => $gridColumns,
        'fontAwesome' => true,
        'dropdownOptions' => [
        'label' => 'Export All',
        'class' => 'btn btn-default'
        ]
        ]) . "<hr>\n".

        GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => $gridColumns,
    ]);        
?>
</div>

Define export columns in runtime

I want to make a form with checkbox list to give user a possibility to chose columns for export. When submitting an export form I need to export only checked columns from POST array.
Is it possible to use your widget in my case?

Multiple export menus on one page

Is it possible to add multiple export menu on the same page with different data?

When I try this, the second export menu gives the data of the first, while I set another dataProvider.

Can't open .xlsx file after upgrading to 1.2.2

This used to work but after update I can't open generated .xlsx file:

echo ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
]);

Other formats works as expected.
Any ideas?
Thanks

[discussion] How to improve performance of slow yii2-export ?

Hey guys,

thanks for this wonderful script! I'm using to inside several projects and the creation of the files is extremely slow. I'd like to open a small discussion on how to improve the performance of this script (as I'm experiencing performance issues even on very powerful servers).

Example

Rendering just 100 lines of super-simple data (10 columns with simple strings) takes 5secs on a 8-core machine with 8 GB RAM (Rackspace instance). Rendering 1000 lines takes 30secs, crashing the request. I can reproduce this.

Question:

I would like to ask the creators of the project if ...

  1. this is a know problem (or just me) ?
  2. is there a simple quick way to improve the speed of this script ?

Thanks a lot & have a fine day

Kartik-v yii2-export gives different result when exporting from web and from localhost

I have developed my Yii2 application on xampp and then I published it online. My application exports a table from the database as excel file. When I export from my local host I get the form that I want:

export from local host

But when I export the same file from the web this is what I get:

export from web

I didn't change anything in my code. I wonder what could be the problem and how can I fix this.

PDF library should be optional

The extension unconditionally tries to load tcpdf, which may not be satisfied if one does not want pdf export.

Thus I suggest only loading the library when pdf export is required. I believe the following should do (untested, in my local copy I just removed the pdf parts):

if($this->_exportType == self::FORMAT_PDF) {
     if (!PHPExcel_Settings::setPdfRenderer(
            PHPExcel_Settings::PDF_RENDERER_TCPDF, $path
        )) {
        throw new InvalidConfigException("The pdf rendering library '{$path}' was not found or is not installed.");
     }
}

Thanks!

Not exporting after change to filter - possibly pjax related

First worth mentioning this only issue when pjax is true.

When I change a filter value and then click to export, nothing happens - no console error nor post.

When I refresh the browser exporting now works - and with the filter applied.

Great job by the way, I previously used your grid view but had written my own export using phpexcel - now I can get rid of that and just use yours :)

Of course there is the possibility that you can't replicate the issue and it turns out to be something else of mine conflicting but heres the important bits to try and replicate anyway. If you can't replicate then I will strip away everything to find out where it goes wrong.

$fullExportMenu = ExportMenu::widget([
    'dataProvider' => $dataProvider,
    'columns' => $gridColumns,
    'target' => ExportMenu::TARGET_SELF,
    'fontAwesome' => true,
    'showConfirmAlert' => false,
    'showColumnSelector' => false,
    'dropdownOptions' => [
        'label' => 'Export',
        'class' => 'btn btn-default',
    ],
]);

?>
<div class="index">
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => $gridColumns,
        'responsive' => true,
        'hover' => true,
        'bordered' => false,
        'floatHeader' => true,
                'pjax' => true,
        'panel' => [
            'heading'=>Html::tag('h3', Html::encode($this->title), ['class' => 'panel-title']),
            'type' => 'default',
            'before' => $before,
            'showFooter' => false,
            'layout' => $template,
        ],
        'toolbar' => [
            $fullExportMenu,
        ]
    ]); ?>

Error Class 'PHPExcel_Settings' not found

Hi Kartik V. I've used code from Usage and getting error Class 'PHPExcel_Settings' not found. Tried versions from
"kartik-v/yii2-export": "dev-master"
and
"kartik-v/yii2-export": "*"
Pls help

showPageSummary option in yii2-export

If I am using the default export feature of gridview, I am getting the page summary in the exported excel file, but then it exports in old excel format.
If I am using the export menu for export I am not getting the page summary, where I am getting the excel-2007 format, which I want.
Am I missing anything in the config?

yii\i18n\PhpMessageSource::loadMessages generates error

I see this error in log when using widget:

The message file for category 'kvexport' does not exist: .../vendor/kartik-v/yii2-export/messages/ru-RU/kvexport.php
Fallback file does not exist as well: .../vendor/kartik-v/yii2-export/messages/ru/kvexport.php

Can't understand why it doesn't fallback to kvexport.php which I've placed inside @app/messages/ru directory.

Change writer for text formats

PHPExcel is very memory-hungry and even for text formats (CSV, Text, HTML) it requires too much memory and time for generating a file. When I'm generating a 3.5 MB CSV file with 48000+ lines and 4 columns, it takes about 900 MB and 160 seconds.
I suggest to optionally change writer for text formats. For example, you can use https://github.com/thephpleague/csv or https://github.com/goodby/csv for writing CSV with more efficient way. It is not so hard to implement, I think. Also another text formats can be writen with such library (just by changing delimiter and enclosure and adding some tags to the begining and ending of HTML file).
What do you think about this?

Missing kartik-v/yii2-grid dependency

ExportMenu extends kartik\grid\GridView, but its composer.json does not have a kartik-v/yii2-grid dependency.

Please add it so it can work after install

Thanks!

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.