Code Monkey home page Code Monkey logo

laravel-datatables-export's Introduction

Laravel DataTables Export Plugin

Laravel 11 Latest Stable Version Continuous Integration Static Analysis Total Downloads License

This package is a plugin of Laravel DataTables for handling server-side exporting using Queue, OpenSpout and Livewire.

Requirements

Documentations

Laravel Version Compatibility

Laravel Package
8.x 0.x
9.x 1.x
10.x 10.x
11.x 11.x

Quick Installation

composer require yajra/laravel-datatables-export:^11.0

The package also requires batch job:

php artisan queue:batches-table
php artisan migrate

Service Provider (Optional since Laravel 5.5+)

Yajra\DataTables\ExportServiceProvider::class

Configuration and Assets (Optional)

$ php artisan vendor:publish --tag=datatables-export --force

Usage

  1. Add the export-button livewire component on your view file that uses dataTable class.
<livewire:export-button :table-id="$dataTable->getTableId()"/>
  1. On your DataTable class, use WithExportQueue
use Yajra\DataTables\WithExportQueue;

class PermissionsDataTable extends DataTable
{
    use WithExportQueue;
    
    ...
}
  1. Run your queue worker. Ex: php artisan queue:work

Purging exported files

On app\Console\Kernel.php, register the purge command

$schedule->command('datatables:purge-export')->weekly();

Export Filename

You can set the export filename by setting the property.

<livewire:export-button :table-id="$dataTable->getTableId()" filename="my-table.xlsx"/>
<livewire:export-button :table-id="$dataTable->getTableId()" filename="my-table.csv"/>

<livewire:export-button :table-id="$dataTable->getTableId()" :filename="$filename"/>

Export Button Name

You can set the export button name by setting the buttonName property.

<!-- Examples demonstrating how to customize the button name for different scenarios -->
<livewire:export-button :table-id="$dataTable->getTableId()" type="xlsx" buttonName="Export Excel"/>
<livewire:export-button :table-id="$dataTable->getTableId()" type="csv"  buttonName="Export CSV"/>

Export Type

You can set the export type by setting the property to csv or xlsx. Default value is xlsx.

<livewire:export-button :table-id="$dataTable->getTableId()" type="xlsx"/>
<livewire:export-button :table-id="$dataTable->getTableId()" type="csv"/>

Set Excel Sheet Name

Option 1: You can set the Excel sheet name by setting the property.

<livewire:export-button :table-id="$dataTable->getTableId()" sheet-name="Monthly Report"/>

Option 2: You can also set the Excel sheet name by overwriting the method.

protected function sheetName() : string
{
    return "Yearly Report";
}

Formatting Columns

You can format the column by setting it via Column definition on you DataTable service class.

Column::make('mobile')->exportFormat('00000000000'),

The format above will treat mobile numbers as text with leading zeroes.

Numeric Fields Formatting

The package will auto-detect numeric fields and can be used with custom formats.

Column::make('total')->exportFormat('0.00'),
Column::make('count')->exportFormat('#,##0'),
Column::make('average')->exportFormat('#,##0.00'),

Date Fields Formatting

The package will auto-detect date fields when used with a valid format or is a DateTime instance.

Column::make('report_date')->exportFormat('mm/dd/yyyy'),
Column::make('created_at'),
Column::make('updated_at')->exportFormat(NumberFormat::FORMAT_DATE_DATETIME),

Valid Date Formats

Valid date formats can be adjusted on datatables-export.php config file.

    'date_formats' => [
        'mm/dd/yyyy',
        NumberFormat::FORMAT_DATE_DATETIME,
        NumberFormat::FORMAT_DATE_YYYYMMDD,
        NumberFormat::FORMAT_DATE_XLSX22,
        NumberFormat::FORMAT_DATE_DDMMYYYY,
        NumberFormat::FORMAT_DATE_DMMINUS,
        NumberFormat::FORMAT_DATE_DMYMINUS,
        NumberFormat::FORMAT_DATE_DMYSLASH,
        NumberFormat::FORMAT_DATE_MYMINUS,
        NumberFormat::FORMAT_DATE_TIME1,
        NumberFormat::FORMAT_DATE_TIME2,
        NumberFormat::FORMAT_DATE_TIME3,
        NumberFormat::FORMAT_DATE_TIME4,
        NumberFormat::FORMAT_DATE_TIME5,
        NumberFormat::FORMAT_DATE_TIME6,
        NumberFormat::FORMAT_DATE_TIME7,
        NumberFormat::FORMAT_DATE_XLSX14,
        NumberFormat::FORMAT_DATE_XLSX15,
        NumberFormat::FORMAT_DATE_XLSX16,
        NumberFormat::FORMAT_DATE_XLSX17,
        NumberFormat::FORMAT_DATE_YYYYMMDD2,
        NumberFormat::FORMAT_DATE_YYYYMMDDSLASH,
    ]

Force Numeric Field As Text Format

Option to force auto-detected numeric value as text format.

Column::make('id')->exportFormat('@'),
Column::make('id')->exportFormat(NumberFormat::FORMAT_GENERAL),
Column::make('id')->exportFormat(NumberFormat::FORMAT_TEXT),

Auto Download

Option to automatically download the exported file.

<livewire:export-button :table-id="$dataTable->getTableId()" filename="my-table.xlsx" auto-download="true"/>

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-datatables-export's People

Contributors

alexpm51 avatar darmawanefendi avatar hpacleb avatar jaydons avatar jeanne007 avatar jidago avatar jsarmiento-obi avatar lot-man avatar nicacode avatar patricktorres27 avatar shairayo avatar throwexceptions avatar uchajk avatar vivekwaah avatar yajra 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

Watchers

 avatar  avatar  avatar  avatar  avatar

laravel-datatables-export's Issues

Use with multiple tables?

Summary of problem or feature request

First thank you for this plugin, once I get through a few edge cases I think it will do exactly what I need. How would one use this plugin with 2 tables loaded following the example at https://datatables.yajrabox.com/services/two-datatables

Code snippet of problem

Unsure of how to go about it

System details

  • Chrome Version 105.0.5195.125 (Official Build) (x86_64)
  • Operating System MacOS 12.6
  • PHP Version 8.1.1
  • Laravel Version 9.31.0
  • Laravel-DataTables Version 10.1.3
  • Laravel-DataTable-Export Version 0.14.0

Call to a member function finished() on null

Call to a member function finished() on null

If the URL has already query params, then it is getting error
Call to a member function finished() on null

On debugging found that the batchJobId is coming as the html content of the page.

Code snippet of problem

$.get(baseUrl + '?' + params.toString() + '&' + $.param(oTable.ajax.params())).then(function(exportId) {
    $wire.export(exportId)
}).catch(function(error) {
    $wire.exportFinished = true;
    $wire.exporting = false;
    $wire.exportFailed = true;
});

System details

  • Operating System - Ubuntu 22.04
  • PHP Version - 8.2
  • Laravel Version - ^10.10
  • Laravel-DataTables Version - ^10.1

Export has duplicates

Export yields unexpected results. We see multiple duplicates in the exported excel file.
The problem stems from this line:

$query = $dataTable->getFilteredQuery()->lazy($chunkSize);

Notice that if the filtered query is not ordered by id (or any unique column), the order of the rows might differ between the calls.
I would suggest using lazyById, but then we would have to pass the name of the column we want to use for lazyById.

Class "PhpOffice\PhpSpreadsheet\Style\NumberFormat" not found

Installation problem.
when i run composer require yajra/laravel-datatables-export -W command in cmd it's return Class "PhpOffice\PhpSpreadsheet\Style\NumberFormat" not found


   Error

  Class "PhpOffice\PhpSpreadsheet\Style\NumberFormat" not found

  at vendor\yajra\laravel-datatables-export\src\config\datatables-export.php:61
     57▕     |
     58▕     */
     59▕     'date_formats' => [
     60▕         'mm/dd/yyyy',
  ➜  61▕         NumberFormat::FORMAT_DATE_DATETIME,
     62▕         NumberFormat::FORMAT_DATE_YYYYMMDD,
     63▕         NumberFormat::FORMAT_DATE_XLSX22,
     64▕         NumberFormat::FORMAT_DATE_DDMMYYYY,
     65▕         NumberFormat::FORMAT_DATE_DMMINUS,

  1   vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138

  2   vendor\yajra\laravel-datatables-export\src\ExportServiceProvider.php:51
      Illuminate\Support\ServiceProvider::mergeConfigFrom("projectRoot\vendor\yajra\laravel-datatables-export\src/config/datatables-export.php", "datatables-export")       

Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
  • Xampp Server
  • Php: 8.2.*
  • Laravel Version: 10.*
  • Laravel-DataTables Version: 10.0

window._buildUrl is not a function

Summary of problem or feature request

When implementing the laravel-datatables-export button I'm presented with an error when clicking on the export button that states window._buildUrl is not a function. I have all the javascripts implemented along with the https://github.com/yajra/laravel-datatables-buttons/blob/master/src/resources/assets/buttons.server-side.js being in the vendor folder.

Code snippet of problem

Following along with the Usage guide. Nothing really complex as the buttons.server-side.js contains the _buildUrl function but its not scoped to window.

System details

  • Chrome Version 105.0.5195.125 (Official Build) (x86_64)
  • Operating System MacOS 12.6
  • PHP Version 8.1.1
  • Laravel Version 9.31.0
  • Laravel-DataTables Version 10.1.3
  • Laravel-DataTables-Export Version 0.14.0

Error to install laravel-datatables-export with laravel 11

Summary of problem or feature request

i am trying to install laravel-datatables. but cannot install this package.

Code snippet of problem

Your requirements could not be resolved to an installable set of packages.

Problem 1
- yajra/laravel-datatables-export[v10.1.0, ..., v10.1.1] require yajra/laravel-datatables ^10.0 -> satisfiable by yajra/laravel-datatables[v10.0.0, v10.1.0].
- yajra/laravel-datatables-export[v11.0.0, ..., v11.1.0] require pestphp/pest ^2.34 -> satisfiable by pestphp/pest[v2.34.0, ..., v2.34.7].
- yajra/laravel-datatables-export v10.0.0 requires livewire/livewire ^2.11.2 -> satisfiable by livewire/livewire[v2.11.2, ..., v2.12.6].
- yajra/laravel-datatables-export[v0.1.0, ..., v0.6.1] require yajra/laravel-datatables-buttons 4.* -> found yajra/laravel-datatables-buttons[v4.0.0, ..., v4.13.3] but it conflicts with your root composer.json require (^11.0).
- yajra/laravel-datatables-export[v0.7.0, ..., v0.14.1, v1.0.0, ..., v1.2.0] require yajra/laravel-datatables-buttons 4.|9. -> found yajra/laravel-datatables-buttons[v4.0.0, ..., v4.13.3, v9.0.0, ..., v9.1.4] but it conflicts with your root composer.json require (^11.0).
- yajra/laravel-datatables v10.0.0 requires yajra/laravel-datatables-oracle ^10 -> found yajra/laravel-datatables-oracle[v10.0.0, ..., v10.11.4] but it conflicts with your root composer.json require (^11.1).
- yajra/laravel-datatables v10.1.0 requires yajra/laravel-datatables-buttons ^10 -> found yajra/laravel-datatables-buttons[v10.0.0, ..., v10.0.9] but it conflicts with your root composer.json require (^11.0).
- pestphp/pest[v2.33.6, ..., v2.34.0] require phpunit/phpunit ^10.5.10 -> found phpunit/phpunit[10.5.10, ..., 10.5.20] but it conflicts with your root composer.json require (^11.0.1).
- pestphp/pest v2.34.1 requires phpunit/phpunit ^10.5.11 -> found phpunit/phpunit[10.5.11, ..., 10.5.20] but it conflicts with your root composer.json require (^11.0.1).
- pestphp/pest v2.34.2 requires phpunit/phpunit ^10.5.12 -> found phpunit/phpunit[10.5.12, ..., 10.5.20] but it conflicts with your root composer.json require (^11.0.1).
- pestphp/pest[v2.34.3, ..., v2.34.4] require phpunit/phpunit ^10.5.13 -> found phpunit/phpunit[10.5.13, ..., 10.5.20] but it conflicts with your root composer.json require (^11.0.1).
- pestphp/pest v2.34.5 requires phpunit/phpunit ^10.5.15 -> found phpunit/phpunit[10.5.15, ..., 10.5.20] but it conflicts with your root composer.json require (^11.0.1).
- pestphp/pest v2.34.6 requires phpunit/phpunit ^10.5.16 -> found phpunit/phpunit[10.5.16, ..., 10.5.20] but it conflicts with your root composer.json require (^11.0.1).
- pestphp/pest v2.34.7 requires phpunit/phpunit ^10.5.17 -> found phpunit/phpunit[10.5.17, 10.5.18, 10.5.19, 10.5.20] but it conflicts with your root composer.json require (^11.0.1).
- livewire/livewire[v2.11.0, ..., v2.12.6] require symfony/http-kernel ^5.0|^6.0 -> found symfony/http-kernel[v5.0.0, ..., v5.4.39, v6.0.0, ..., v6.4.7] but the package is fixed to v7.0.7 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
- Root composer.json requires yajra/laravel-datatables-export * -> satisfiable by yajra/laravel-datatables-export[v0.1.0, ..., v0.14.1, v1.0.0, v1.0.1, v1.1.0, v1.2.0, v10.0.0, v10.1.0, v10.1.1, v11.0.0,
v11.0.1, v11.1.0].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require yajra/laravel-datatables-export:*" to figure out if any version is installable, or "composer require yajra/laravel-datatables-export:^2.1" if you know which you need.

  • Operating System : windows 10
  • PHP Version : 8.2.4
  • Laravel Version : 11.0.7
  • Laravel-DataTables Version :
    "yajra/laravel-datatables-buttons": "^11.0",
    "yajra/laravel-datatables-html": "^11.2",
    "yajra/laravel-datatables-oracle": "^11.1"

Component not found phpunit

Component not found phpunit.

[2023-01-10 16:25:54] testing.ERROR: Unable to find component: [export-button] {"userId":1,"exception":"[object] (Livewire\\Exceptions\\ComponentNotFoundException(code: 0): Unable to find component: [export-button] at /Users/ucha/www/project/vendor/livewire/livewire/src/LivewireManager.php:75) [stacktrace]

I believe the problem is caused by
if (! $this->app->runningInConsole()) { Livewire::component('export-button', ExportButtonComponent::class); } in https://github.com/yajra/laravel-datatables-export/blob/master/src/ExportServiceProvider.php

I guess my question is, why only register the component when not running in console?
And if there is a good reason behind it, how would I go about registering the component when running a test?

[Feature Request] Make storage path configurable

I stumbled upon this repo and realized this is exactly what I've been looking for as a lot of my data is very large 20k+ records. One issue I noticed is there is no way to configure the storage location as it's hard coded. If you could make that configurable that would make this plugin work perfectly!

Add command to periodically delete exported files

TODO:

  • Add command to delete / purge old export files
  • Add config on how old are the files to be deleted

Example:

php artisan datatables:purge-export

Command can be attached to scheduler to automatically purge old files.

exportFormat doesn't work for .csv files

Summary of problem or feature request

exportFormat doesn't work for CSV files.

Code snippet of problem

Blade file

<livewire:export-button :table-id="$dataTable->getTableId()" filename="export.csv" />

Datatable file

Column::make('date')->exportFormat('mm/dd/yyyy'),

Dumping the raw date column using Model::first()->date

2022-02-04 00:00:00

In the export file, the date shows

44596

After checking the source code of the package, the value from the export is equal to

Date::dateTimeToExcel(Carbon::parse(strval(Model::first()->date));

--

System details

  • Operating System : macOS Big Sur Version 11.5.2
  • PHP Version : v8.1.8
  • Laravel Version : v9.21.3
  • Laravel-DataTables Version : v9.0.0

--

It seems like the package Openspout doesn't support styling for CSV files as seen here.

    /**
     * @return CSVWriter
     */
    private static function createCSVWriter()
    {
        $optionsManager = new CSVOptionsManager();
        $globalFunctionsHelper = new GlobalFunctionsHelper();

        $helperFactory = new HelperFactory();

        return new CSVWriter($optionsManager, $globalFunctionsHelper, $helperFactory);
    }

    /**
     * @return XLSXWriter
     */
    private static function createXLSXWriter()
    {
        $styleBuilder = new StyleBuilder();
        $optionsManager = new XLSXOptionsManager($styleBuilder);
        $globalFunctionsHelper = new GlobalFunctionsHelper();

        $helperFactory = new XLSXHelperFactory();
        $managerFactory = new XLSXManagerFactory(new InternalEntityFactory(), $helperFactory);

        return new XLSXWriter($optionsManager, $globalFunctionsHelper, $helperFactory, $managerFactory);
    }

My first thought for a fix for dates was to change the value directly only for csv exports.

$cellValue = $value ? Carbon::parse(strval($value))->format('m/d/Y') : '';

or convert the excel value back to php datetime and then using ->format('m/d/Y')

However there are a few issues for this, carbon format strings are also different from excel formats.

Carbon Format Excel Format Result
->format('m/d/Y') ->exportFormat('mm/dd/yyyy') 02/04/2022

For full comparison :
Carbon Full Date Format List
Excel Full Date Format List

Any thoughts?

[Feature Request] Add option to set sheet name

It would be nice to have a property to set the sheet name.

Proposed Approach

If sheet-name is not set, we can get the default value (Sheet1) via config .

<livewire:export-button :table-id="$dataTable->getTableId()" filename="my-table.xlsx" sheet-name="Summary Report" />

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.