Adding Simple Excel Support

In this example I will expand on my Advent article from last year on AJAX grids by adding a button to download the book list as an Excel spreadsheet.

The complete tarball for this example is here.

We'll use this module to create the Excel spreadsheets.

The Button

First we need a suitable Excel icon. Find one and put it into your root/static/images directory. I used this one.

Insert standard disclaimer about not using other people's art without permission.

Add the style for the button in the <style> section of root/src/ajax.tt, like so:

    .flexigrid div.fbutton .excel
    {
    background: url([% c.uri_for('/static/images/excel-icon-small.gif') %]) no-repeat center left;
    }

Add the button in the buttons section of the flexigrid:

    {name: 'Excel', bclass: 'excel', onpress : export_to_excel},

Now we'll write the JavaScript, as specified in the synopsis.

    function export_to_excel(button, grid) {
        $('<iframe '                                                  
         +'src="/api/books?content-type=application%2Fvnd.ms-excel">')
        .hide().appendTo('body');
    }

This initiates the file download.

The Serializer

The serializer is much like any other serializer you would write. It goes into the API controller.

At the top, put:

    use POSIX ();

    __PACKAGE__->config->{map}{'application/vnd.ms-excel'} = 'SimpleExcel';

Then the action:

    sub books : Local ActionClass('REST') {}

    sub books_GET {
        my ($self, $c) = @_;

        my $rs = $c->model('DB::Book')->search({}, {
            order_by => ['title']
        });

        my @rows = map {
            [ $_->id, $_->title, $_->rating, $_->author_list ]
        } $rs->all;

        my $entity = {
            header => ['ID', 'Title', 'Rating', 'Authors'],
            rows => \@rows,
            filename => 'books-'.POSIX::strftime('%m-%d-%Y', localtime)
        };

        $self->status_ok(
            $c,
            entity => $entity
        );
    }

Try it out

Start the server with script/myapp_server.pl.

In your browser, open http://localhost:3000/ajax. You will see the books grid; click on the Excel icon and you should get a file-download prompt for the Excel file. Open it with Excel or OpenOffice.

TODO

We need an Excel deserializer, so that users can edit the downloaded Excel sheets and upload them back. It would also be nice if the ID column were highlighted and locked against editing.

If you have any interest in these issues, please email me at the address below, especially if you are able to do any work on them. Patches most certainly welcome as well.

AUTHOR

Caelum: Rafael Kitover <rkitover@cpan.org>