summaryrefslogtreecommitdiffstats
path: root/lib/Spreadsheet/Template.pm
blob: ebbf73b63dba33652997ce976ac08099266c9b0f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package Spreadsheet::Template;
use Moose;
# ABSTRACT: generate spreadsheets from a template

use Class::Load 'load_class';
use JSON;

=head1 SYNOPSIS

  use Spreadsheet::Template;

  my $template = Spreadsheet::Template->new;
  my $in = do { local $/; <> };
  my $out = $template->render($in);
  open my $fh, '>', 'out.xlsx';
  binmode $fh;
  $fh->print($out);
  $fh->close;

=head1 DESCRIPTION

This module is used to render spreadsheets from JSON files which describe the
desired content and formatting. These JSON files can be preprocessed with a
template engine such as L<Text::Xslate> in order to customize the spreadsheet
contents before generation, in a similar way to how HTML pages can be rendered
with templates.

The typical workflow for using this module is to create a sample spreadsheet in
Excel with the desired layout and formatting, and use
L<Spreadsheet::Template::Generator> (or the included C<spreadsheet_to_template>
script) to generate a base template. That base template can then be edited
to add in template declarations, and then this module can be used to generate
new spreadsheets based on the template.

=head1 DATA FORMAT

The intermediate data format that should be produced after the template has
been preprocessed is a JSON file, with a structure that looks like this:

  {
     "selection" : 0,
     "worksheets" : [
        {
           "column_widths" : [ 10, 10, 10 ],
           "name"          : "Sheet1",
           "row_heights"   : [ 18, 18, 18 ],
           "selection"     : [ 0, 0 ],
           "autofilter"    : [
               [ [0, 0], [0, 2] ]
           ],
           "cells"         : [
              [
                 {
                    "contents" : "This is cell A1",
                    "format"   : {
                       "color" : "#000000",
                       "size" : 14,
                       "text_wrap" : true,
                       "valign" : "vcenter"
                    },
                    "type"     : "string"
                 },
                 {
                    "contents" : "3.25",
                    "format"   : {
                       "color" : "#000000",
                       "num_format" : "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)",
                       "size" : 14
                    },
                    "type"     : "number"
                 }
              ],
              [
                 {
                    "contents" : "2013-03-20T00:00:00",
                    "format"   : {
                       "color" : "#000000",
                       "align" : "center",
                       "num_format" : "d-mmm",
                       "size" : 14,
                       "border_color" : [
                          "#000000",
                          "#000000",
                          "#000000",
                          "#000000"
                       ],
                       "border" : [
                          "thin",
                          "thin",
                          "thin",
                          "thin"
                       ]
                    },
                    "type"     : "date_time"
                 },
                 {
                    "contents" : "3.25",
                    "formula"  : "SUM(B1:B1)",
                    "format"   : {
                       "bg_color" : "#d8d8d8",
                       "bold" : true,
                       "color" : "#000000",
                       "num_format" : "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)",
                       "pattern" : "solid",
                       "size" : 14
                    },
                    "type"     : "string"
                 }
              ]
           ],
           "merge" : [
              {
                  "range"    : [ [1, 0], [1, 2] ],
                  "contents" : "Merged Contents",
                  "format"   : {
                      "color" : "#000000"
                  },
                  "type"     : "string"
              }
           ]
        }
     ]
  }

=head2 workbook

The entire JSON document describes a workbook to be produced. The document
should be a JSON object with these keys:

=over 4

=item selection

The (zero-based) index of the worksheet to be initially selected when the
spreadsheet is opened.

=item worksheets

An array of worksheet objects.

=back

=head2 worksheet

Each element of the C<worksheets> array in the workbook object should be a JSON
object with these keys:

=over 4

=item name

The name of the worksheet.

=item column_widths

An array of numbers corresponding to the widths of the columns in the
spreadsheet.

=item row_heights

An array of numbers corresponding to the heights of the rows in the
spreadsheet.

=item selection

An array of two numbers corresponding to the (zero-based) row and column of the
cell that should be selected when the worksheet is first displayed.

=item autofilter

Enables autofilter behavior for each range of cells listed. Cell ranges are
specified by an array of two arrays of two numbers, corresponding to the row
and column of the top left and bottom right cell of the autofiltered range.

=item cells

An array of arrays of cell objects. Each innermost array represents a row,
containing all of the cell data for that row.

=item merge

An array of merge objects. Merge objects are identical to cell objects, except
that they contain an additional C<range> key, which has a value of an array of
two arrays of two numbers, corresponding to the row and column of the top left
and bottom right cell of the range to be merged.

=back

=head2 cell

Each element of the two-dimensional C<cells> array in a worksheet object should
be a JSON object with these keys:

=over 4

=item contents

The unformatted contents of the cell. For cells with a C<type> of C<string>,
this should be a string, for cells with a C<type> of C<number>, this should be
a number, and for cells with a C<type> of C<date_time>, this should be a string
containing the ISO8601 representation of the date and time.

=item format

The format object describing how the cell's contents should be formatted.

=item type

The type of the data in the cell. Can be either C<string>, C<number>, or
C<date_time>.

=item formula

The formula used to calculate the cell contents. This field is optional. If you
want the generated spreadsheet to be able to be read by programs other than
full spreadsheet applications (such as by L<Spreadsheet::Template::Generator>,
then you should ensure that you include an accurate value for C<contents> as
well, since most simple spreadsheet parsers don't include a full formula
calculation engine.

=back

=head2 format

Each cell object contains a C<format> key whose value should be a JSON object
with these (all optional) keys:

=over 4

=item size

The font size for the cell contents.

=item color

The font color for the cell contents.

=item bold

True if the cell contents are bold.

=item italic

True if the cell contents are italic.

=item pattern

The background pattern for the cell. Can have any of these values (with
C<none> being the default if nothing is specified):

  none
  solid
  medium_gray
  dark_gray
  light_gray
  dark_horizontal
  dark_vertical
  dark_down
  dark_up
  dark_grid
  dark_trellis
  light_horizontal
  light_vertical
  light_down
  light_up
  light_grid
  light_trellis
  gray_125
  gray_0625

=item bg_color

The background color for the cell. Only has meaning if a C<pattern> other than
C<none> is chosen.

=item fg_color

The foreground color for the cell. Only has meaning if a C<pattern> other than
C<none> or C<solid> is chosen.

=item border

The border style for the cell. This should be an array with four elements,
corresponding to the left, right, top, and bottom borders. Each element can
have any of these values (with C<none> being the default if nothing is
specified):

  none
  thin
  medium
  dashed
  dotted
  thick
  double
  hair
  medium_dashed
  dash_dot
  medium_dash_dot
  dash_dot_dot
  medium_dash_dot_dot
  slant_dash_dot

=item border_color

The border color for the cell. This should be an array with four elements,
corresponding to the left, right, top, and bottom borders.

=item align

The horizontal alignment for the cell contents. Can have any of these values,
with C<none> being the default:

  none
  left
  center
  right
  fill
  justify
  center_across

=item valign

The vertical alignment for the cell contents. Can have any of these values,
with C<bottom> being the default:

  top
  vcenter
  bottom
  vjustify

=item text_wrap

True if the contents of the cell should be text-wrapped.

=item num_format

The numeric format for the cell. Only meaningful if the cell's type is
C<number> or C<date_time>. This is the string representation of the format as
understood by Excel itself.

=back

=cut

=attr processor_class

Name of the L<Spreadsheet::Template::Processor> class to use to preprocess the
template. Defaults to L<Spreadsheet::Template::Processor::Xslate>.

=cut

has processor_class => (
    is      => 'ro',
    isa     => 'Str',
    default => 'Spreadsheet::Template::Processor::Xslate',
);

=attr processor_options

Arguments to pass to the C<processor_class> constructor.

=cut

has processor_options => (
    is      => 'ro',
    isa     => 'HashRef',
    default => sub { {} },
);

=attr writer_class

Name of the L<Spreadsheet::Template::Writer> class to use to preprocess the
template. Defaults to L<Spreadsheet::Template::Writer::XLSX>.

=cut

has writer_class => (
    is      => 'ro',
    isa     => 'Str',
    default => 'Spreadsheet::Template::Writer::XLSX',
);

=attr writer_options

Arguments to pass to the C<writer_class> constructor.

=cut

has writer_options => (
    is      => 'ro',
    isa     => 'HashRef',
    default => sub { {} },
);

has _processor => (
    is      => 'ro',
    does    => 'Spreadsheet::Template::Processor',
    lazy    => 1,
    default => sub {
        my $self = shift;
        my $class = $self->processor_class;
        load_class($class);
        return $class->new($self->processor_options);
    },
);

=attr json

Instance of a JSON class that will handle decoding. Defaults to an instance of L<JSON>.
Passing in a JSON obj with ->relaxed(1) set will allow for trailing commas in your templates.

=cut

has json => (
    is => 'ro',
    default => sub {
        return JSON->new;
    }
);

sub _writer {
    my $self = shift;
    my $class = $self->writer_class;
    load_class($class);
    return $class->new($self->writer_options);
}

=method render($template, $vars)

Calls C<process> on the L<Spreadsheet::Template::Processor> instance with
C<$template> and C<$vars> as arguments, decodes the result as JSON, and returns
the result of passing that data to the C<write> method of the
L<Spreadsheet::Template::Writer> instance.

=cut

sub render {
    my $self = shift;
    my ($template, $vars) = @_;
    my $contents = $self->_processor->process($template, $vars);
    # not decode_json, since we expect that we are already being handed a
    # character string (decode_json also decodes utf8)
    my $data = $self->json->decode($contents);
    return $self->_writer->write($data);
}

__PACKAGE__->meta->make_immutable;
no Moose;

=head1 BUGS

=over 4

=item *

Default values aren't handled properly - spreadsheets can set defaults for
things like font sizes, but this isn't actually handled, so cells that are
supposed to use the default may get an incorrect value.

=back

Please report any bugs to GitHub Issues at
L<https://github.com/doy/spreadsheet-template/issues>.

=head1 SEE ALSO

L<Excel::Template>

=head1 SUPPORT

You can find this documentation for this module with the perldoc command.

    perldoc Spreadsheet::Template

You can also look for information at:

=over 4

=item * MetaCPAN

L<https://metacpan.org/release/Spreadsheet-Template>

=item * Github

L<https://github.com/doy/spreadsheet-template>

=item * RT: CPAN's request tracker

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Spreadsheet-Template>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/Spreadsheet-Template>

=back

=head1 SPONSORS

Parts of this code were paid for by

=over 4

=item Socialflow L<http://socialflow.com>

=back

=cut

1;