XLSX.pm

filter: Statementstmt 92.5% 25 / 27 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.4% 34 / 36 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« build.pl ↑ Summary
1 package Excel::Template::XLSX;
2
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use base 'Excel::Writer::XLSX';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Excel::Writer::XLSX::Utility;
Subroutine BEGIN: called CC=1 SCAR=0.0
7
8 1 ▶use version; our $VERSION = version->declare("v1.1.0");
Subroutine BEGIN: called CC=1 SCAR=0.0
9
10 1 ▶use Archive::Zip;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Graphics::ColorUtils 'rgb2hls', 'hls2rgb';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Scalar::Util 'openhandle';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
14
15 1; # Return True from module
16
17 ###############################################################################
18 sub __podhead {
19
20 =for pod
21
22 =head1 NAME
23
24 Excel-Template-XLSX - Create Excel .xlsx files starting from (one or more) template(s).
25
26 =head1 SYNOPSIS
27
28 use Excel::Template::XLSX;
29 my ($self, $workbook) = Excel::Template::XLSX->new('perl.xlsx', 'template1.xlsx', 'template2.xlsx', ...);
30 $self->parse_template();
31
32 # Add a worksheet, ... and anything else you would do with Excel::Writer::XLSX
33 $worksheet = $workbook->add_worksheet();
34
35 # Although Excel::Writer::XLSX says the workbook will automatically get
36 # closed during global destruction. This wrapper around Excel::Writer::XLSX may
37 # mess this up, and it is better to specifically close your workbook when you are done.
38 $workbook->close();
39
40 =head1 DESCRIPTION
41
42 This module is a companion to
43 L<Excel::Writer::XLSX|https://metacpan.org/release/Excel-Writer-XLSX>(EWX), or
44 if you prefer, a wrapper to that module. It uses EWX as a base class. It opens
45 an existing spreadsheet file (.xlsx format), and also creates a new EWX object.
46 As it parses the template file(s), it calls EWX methods to re-create the template
47 contents in the EWX object.
48
49 When parsing is complete, the workbook object is left open for the calling perl
50 script to add additional content.
51
52 The purpose of this module is to separate the roles of content/presentation vs
53 programming in an Excel document, in much the same way that HTML templating
54 engines work. A user who is knowledgeable in Excel can create an Excel file for
55 use as a template, without requiring the skill set of Perl or
56 Excel::Writer::XLSX. Conversely, the Perl programmer who is creating dynamic
57 content does not need design skills to layout the presentation in the template.
58
59 =head1 WHAT IT CAN DO
60
61 Cell Values (strings, numbers, dates, ... )
62 Cell Formulas
63 Cell Hyperlinks
64
65 Cell Formatting (borders, shading, fonts, font sizes, colors)
66
67 Column Widths
68 Row Widths
69
70 Headers and Footers
71
72 Simple template variables (via callback) See L</"template_callback">
73
74 =head1 WHAT IT CAN NOT DO
75
76 Excel::Template::Excel can not modify Excel files in place! It is not
77 intended to. Since the parser directly adds content to the EWX workbook object
78 as the contents are parsed, both the template, and the output file must
79 be open at the same time.
80
81 It may be possible to open the output file to a file handle, and
82 after parsing of the template is complete, write the contents of file
83 over the template. The author has not tried this.
84
85 It is not the design of this module to faithfully re-create the entire
86 contents of the template file in the EWX output. If you are using this
87 module to rewrite Excel files, you are on your own.
88
89 These items are completely dropped from the output file:
90
91 Images in the Sheet
92 Images in Headers/Footers
93 Charts
94 Shapes
95 Themes (gradients, fonts, fills, styles)
96 macros
97 modules (vba code)
98
99 And probably other things. See the tests (t directory of the distribution)
100 for examples of what does work.
101
102 =head1 SUBROUTINES AND METHODS
103
104 =head2 __podhead
105
106 Dummy subroutine to allow me to hide this pod documentation when using code
107 folding in the editor.
108
109 =cut
110
111 }
112 ###############################################################################
113 sub new {
114
115 =head2 new
116
117 Creates a new Excel::Template::XLSX object, and also creates a new
118 Excel::Writer::XLSX object. A workbook object is created for the output file.
119
120 Returns the Template object, and the workbook object. Workbook object is also
121 available as $self->{EWX}; If the caller is only expecting a single
122 return value, then just the $self object is returned.
123
124 =cut
125
126 my ( $class, $output_file, @template_files ) = @_;
127 my $self = {
128 FORMATS => [],
129 HYPERLINKS => {},
130 NEED_PROPS => 1,
131 PRINT_AREA => {},
132 PRINT_TITLES => {},
133 MERGED_RANGES => {},
134 SHARED_STRINGS => [],
135 THEMES => [],
136 ZIP => [],
137
138 template_callback => undef,
139 };
140
141 # Create a new Excel workbook
142 $self->{EWX} = Excel::Writer::XLSX->new($output_file);
143 if ( defined $self->{EWX} ) {
144 $self->{DEFAULT_FORMAT} = $self->{EWX}->add_format();
145 bless $self, $class;
146 }
147 else {
148 die
149 "Can't create new Excel::Writer::XLSX object using file ($output_file) $!";
150 }
151
152 foreach my $template_file (@template_files) {
153 my $zip = Archive::Zip->new;
154 if ( openhandle($template_file) ) {
155 bless $template_file, 'IO::File'
156 if ref($template_file) eq 'GLOB'; # sigh
157 my $status = $zip->readFromFileHandle($template_file);
158 unless ( $status == Archive::Zip::AZ_OK ) {
159 warn "Can't open filehandle as a zip file, skipping";
160 $zip = undef;
161 }
162 }
163 elsif ( !ref($template_file) ) {
164 my $status = $zip->read($template_file);
165 unless ( $status == Archive::Zip::AZ_OK ) {
166 $template_file //= '(undef)';
167 warn "Can't open file '$template_file' as a zip file, skipping";
168 $zip = undef;
169 }
170 }
171 else {
172 warn
173 "Argument to 'new' must be a filename or open filehandle. skipping $template_file";
174 $zip = undef;
175 }
176
177 # Create a list of template files to add to the workbook
178 push @{ $self->{ZIP} }, $zip;
179 }
180 if (wantarray) {
181 return ( $self, $self->{EWX} );
182 }
183 else {
184 return $self;
185 }
186 }
187 ###############################################################################
188 sub parse_template {
189
190 =head2 parse_template
191
192 Parses common elements of the Spreadsheet, such as themes, styles, and strings.
193 These are stored in the main object ($self).
194
195 Finds each sheet in the workbook, and initiates parsing of each sheet.
196
197 Properties for the created workbook are set from the first template that has
198 properties. Properties in subsequent workbooks are ignored.
199
200 =cut
201
202 my $self = shift;
203
204 my $remap = {
205 title => 'title',
206 subject => 'subject',
207 creator => 'author',
208 keywords => 'keywords',
209 description => 'comments',
210
211 manager => 'manager',
212 company => 'company',
213 category => 'category',
214 status => 'status',
215 };
216
217 for my $z ( 0 .. $#{ $self->{ZIP} } ) {
218 my $zip = $self->{ZIP}[$z] // next;
219 $self->{PRINT_TITLES} = {};
220 $self->{SHARED_STRINGS} = [];
221 $self->{FORMATS} = [];
222
223 my $files = $self->_extract_files($zip);
224
225 my $callback = $self->{template_callback};
226 my $call = ref($callback) eq 'CODE';
227 if ( $self->{NEED_PROPS} ) {
228 if ( my @core_nodes
229 = $files->{core}->find_nodes('//cp:coreProperties') )
230 {
231 my $core = shift @core_nodes;
232 my %hash = map {
233 my $prop = $core->first_child( "dc:" . $_ )
234 // $core->first_child( "cp:" . $_ );
235 my %pair = ();
236 if ($prop) {
237 my $text = $prop->text();
238 $call and $self->$callback( \$text );
239 %pair = ( $remap->{$_}, $text );
240 }
241 %pair;
242 } keys %$remap;
243 $self->{EWX}->set_properties(%hash);
244 $self->{NEED_PROPS} = 0;
245 }
246 }
247
248 $self->{THEMES}
249 = $self->_parse_themes( ( values %{ $files->{themes} } )[0] );
250
251 $self->_parse_styles( $files->{styles} );
252 $self->_parse_shared_strings( $files->{strings} );
253
254 # Defined Names (includes print area, print titles)
255 map {
256 my $name = $_->att('name') // '';
257 my $address = $_->text();
258
259 # Print Titles (may contain none, one, or both. Delimited by comma if both supplied)
260 # e.g. Title_Page!$A:$A
261 if ( $name eq '_xlnm.Print_Titles' ) {
262 my @title = split( ',', $address );
263 foreach (@title) {
264 my ( $sheet_name, $range ) = split('!');
265 push @{ $self->{PRINT_TITLES}{$sheet_name} }, $range;
266 }
267
268 # Print Area (Save it until sheets are processed)
269 }
270 elsif ( $name eq '_xlnm.Print_Area' ) {
271 my @title = split( ',', $address );
272 my ( $sheet_name, $range ) = split( '!', $address );
273 $self->{PRINT_AREA}{$sheet_name} = $range;
274 }
275 else {
276 $self->{EWX}->define_name( $name, $address );
277 }
278 } $files->{workbook}->find_nodes('//definedNames/definedName');
279
280 # Sheets: Add a worksheet for each sheet in workbook
281 # Rename sheet if template(s) already has a sheet by that name
282 map {
283 my $name = $_->att('name');
284 my $test = $name;
285 for ( my $i = 1; ; $i++ ) {
286 last unless $self->{EWX}->get_worksheet_by_name($test);
287 $test = $name . "($i)";
288 }
289 my $sheet = $self->{EWX}->add_worksheet($test);
290
291 my $range = $self->{PRINT_AREA}{$name};
292 $sheet->print_area($range) if $range;
293
294 foreach my $range ( @{ $self->{PRINT_TITLES}{$name} } ) {
295
296 if ($range =~ m/[A-Za-z]/) { # Column Range like $A:$A
297 $sheet->repeat_columns( $range )
298 } else {
299 # Row Range like $1:$1
300 $range =~ s/\$//g;
301 my ($first, $last) = split('\:', $range);
302 $sheet->repeat_rows( --$first, --$last );
303 }
304 }
305
306 # Parse the contents of the sheet
307 my $idx = $_->att('r:id');
308 $self->_parse_sheet( $sheet, $files->{sheets}{$idx} );
309 } $files->{workbook}->find_nodes('//sheets/sheet');
310 $self->{ZIP}[$z] = undef;
311 }
312 }
313 ###############################################################################
314 sub template_callback {
315
316 =head2 template_callback
317
318 Place holder method for a callback routine to modify the content of the template
319 before being written to the output spreadsheet.
320
321 This callback is activated for all shared string (both plain and rich text
322 strings), and also for header/footer text.
323
324 The callback is supplied with the two parameters: The object name (since this is
325 a method), and the text to be processed. This is passed as a reference to single
326 scalar.
327
328 This method is called numerous times during processing (e.g. once for each
329 unique string in the spreadsheet, so the user is advised to keep it efficient.
330
331 This callback approach does not force any particular templating system on the
332 user. They are free to use whatever system they choose.
333
334 Note that templating can only do simple scalars. Complex templating (if-then-
335 else, loops, etc) do not make sense in that the callback is supplied with the
336 contents of a single cell. Having said that, remember that the full power of
337 Excel::Writer::XLSX is available to the user to modify the template after it is
338 processed.
339
340 # A snippet of code to replace [% template %] in the
341 # template spreadsheet with 'Output'
342
343 my ($self, $wbk) = Excel::Template::XLSX->new($output_xlsx, $template_xlsx);
344
345 use Template::Tiny;
346 my $template = Template::Tiny->new( TRIM => 1 );
347 $self->{template_callback} = sub {
348 my ($self, $textref) = @_;
349 $template->process($textref, { template => 'Output' }, $textref );
350 };
351
352 $self->parse_template();
353
354 =cut
355
356 my $self = shift;
357 my ($text) = @_;
358 }
359 ###############################################################################
360 sub _apply_tint {
361
362 =head2 _apply_tint
363
364 Applies tinting to a color object, if the tint attribute is encountered in
365 parsing.
366
367 =cut
368
369 my $self = shift;
370 my ( $color, $tint ) = @_;
371
372 my ( $r, $g, $b ) = map { oct("0x$_") } $color =~ /#(..)(..)(..)/;
373 my ( $h, $l, $s ) = rgb2hls( $r, $g, $b );
374
375 if ( $tint < 0 ) {
376 $l = $l * ( 1.0 + $tint );
377 }
378 else {
379 $l = $l * ( 1.0 - $tint ) + ( 1.0 - 1.0 * ( 1.0 - $tint ) );
380 }
381
382 return scalar hls2rgb( $h, $l, $s );
383 }
384 ###############################################################################
385 sub _base_path_for {
386
387 =head2 _base_path_for
388
389 Manipulates the path to a member in the zip file, to find the associated
390 rels file.
391
392 =cut
393
394 my $self = shift;
395 my ($file) = @_;
396
397 my @path = split '/', $file;
398 pop @path;
399
400 return join( '/', @path ) . '/';
401 }
402 ###############################################################################
403 sub _cell_to_row_col {
404
405 =head2 _cell_to_row_col
406
407 Converts an A1 style cell reference to a row and column index.
408
409 =cut
410
411 my $self = shift;
412 my $cell = shift;
413
414 my ( $col, $row ) = $cell =~ /([A-Z]+)([0-9]+)/;
415
416 my $ncol = 0;
417 for my $char ( split //, $col ) {
418 $ncol *= 26;
419 $ncol += ord($char) - ord('A') + 1;
420 }
421 $ncol = $ncol - 1;
422 my $nrow = $row - 1;
423 return ( $nrow, $ncol );
424 }
425 ###############################################################################
426 sub _color {
427
428 =head2 _color
429
430 Parses color element (rgb, index, theme, and tint)
431
432 =cut
433
434 my $self = shift;
435 my ( $color_node, $fill ) = @_;
436
437 my $themes = $self->{THEMES};
438 my $color;
439 if ( $color_node && !$color_node->att('auto') ) {
440 my $rgb = $color_node->att('rgb');
441 my $theme = $color_node->att('theme');
442 my $index = $color_node->att('indexed');
443 my $tint = $color_node->att('tint');
444
445 # see https://rt.cpan.org/Public/Bug/Display.html?id=93065 (still needed for XLSX??)
446 # defined $index and $color = ($fill && $index == 64) ? '#FFFFFF' : $index;
447 $rgb and $color = '#' . substr( $rgb, 2, 6 );
448 defined $theme and $color = '#' . $themes->{Color}[$theme];
449 $tint and $color = $self->_apply_tint( $color, $tint );
450 }
451 return $color;
452 }
453 ###############################################################################
454 sub _extract_files {
455
456 =head2 _extract_files
457
458 Called by parse_template to fetch the xml strings from the zip file. XML
459 strings are parsed, except for worksheets. Individual worksheets are
460 parsed separately.
461
462 =cut
463
464 my $self = shift;
465 my ($zip) = @_;
466
467 my $type_base
468 = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
469
470 my $rels = $self->_parse_xml( $zip, $self->_rels_for('') );
471
472 my $node = qq<//Relationship[\@Type="$type_base/officeDocument"]>;
473 my $wb_name = ( $rels->find_nodes($node) )[0]->att('Target');
474 my $wb_xml = $self->_parse_xml( $zip, $wb_name );
475
476 my $path_base = $self->_base_path_for($wb_name);
477 my $wb_rels = $self->_parse_xml( $zip, $self->_rels_for($wb_name) );
478
479 my $string_xpath = qq<//Relationship[\@Type="$type_base/sharedStrings"]>;
480 my ($strings_xml) = map {
481 $zip->memberNamed( $path_base . $_->att('Target') )->contents
482 } $wb_rels->find_nodes($string_xpath);
483
484 my $style_xpath = qq<//Relationship[\@Type="$type_base/styles"]>;
485 my $style_target
486 = ( $wb_rels->find_nodes($style_xpath) )[0]->att('Target');
487 my $styles_xml = $self->_parse_xml( $zip, $path_base . $style_target );
488
489 my %sheet_rels;
490 my $wks_xpath = qq<//Relationship[\@Type="$type_base/worksheet"]>;
491 my %worksheet_xml = map {
492
493 my $sheet_file = $path_base . $_->att('Target');
494 my $rels_file = $self->_rels_for($sheet_file);
495 my $sheet_rels = '';
496 if ( $zip->memberNamed($rels_file) ) {
497 $sheet_rels = $self->_parse_xml( $zip, $rels_file );
498 }
499
500 if ( my $contents = $zip->memberNamed($sheet_file)->contents ) {
501 ( $_->att('Id') => { 'xml' => $contents, 'rels' => $sheet_rels } );
502 }
503
504 } $wb_rels->find_nodes($wks_xpath);
505
506 my %themes_xml = map {
507 $_->att('Id') =>
508 $self->_parse_xml( $zip, $path_base . $_->att('Target') )
509 } $wb_rels->find_nodes(qq<//Relationship[\@Type="$type_base/theme"]>);
510
511 my $core_base
512 = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata';
513 my $core_full = qq<//Relationship[\@Type="$core_base/core-properties"]>;
514 my $core_name = ( $rels->find_nodes($core_full) )[0]->att('Target');
515 my $core_xml = $self->_parse_xml( $zip, $core_name );
516
517 return {
518 workbook => $wb_xml,
519 styles => $styles_xml,
520 sheets => \%worksheet_xml,
521 themes => \%themes_xml,
522 core => $core_xml,
523 ( $strings_xml ? ( strings => $strings_xml ) : () ),
524 };
525 }
526 ###############################################################################
527 sub _parse_alignment {
528
529 =head2 _parse_alignment
530
531 Parses horizontal and vertical cell alignments in a sheet.
532
533 =cut
534
535 my $self = shift;
536 my ($node) = @_;
537
538 my %align_map = (
539 horizontal => 'align',
540 vertical => 'valign',
541 textRotation => 'rotation',
542 indent => 'indent',
543 wrapText => 'text_wrap',
544 shrinkToFit => 'shrink',
545 );
546 my %align = ();
547 if ( my $alignment = $node->first_child('alignment') ) {
548 map {
549 my $v = $alignment->att($_);
550 if ( defined $v ) {
551 $v = 'vcenter' if ( $_ eq 'vertical' ) and ( $v eq 'center' );
552 $align{ $align_map{$_} } = $v;
553 }
554 } keys %align_map;
555 }
556 return %align;
557 }
558 ###############################################################################
559 sub _parse_borders {
560
561 =head2 _parse_borders
562
563 Parses cell border and diagonal border styles. Called from _parse_styles.
564 Returns an array of border styles, each one as a hash.
565
566 =cut
567
568 my $self = shift;
569 my ($styles) = @_;
570
571 my $borders = [];
572 my %border_map = (
573 dashDot => 9,
574 dashDotDot => 11,
575 dashed => 3,
576 dotted => 4,
577 double => 6,
578 hair => 7,
579 medium => 2,
580 mediumDashDot => 10,
581 mediumDashDotDot => 12,
582 mediumDashed => 8,
583 none => 0,
584 slantDashDot => 13,
585 thick => 5,
586 thin => 1,
587 );
588 push @$borders, map {
589 my $border = $_;
590
591 # XXX specs say "begin" and "end" rather than "left" and "right",
592 # but... that's not what seems to be in the file itself (sigh)
593
594 my %colors = ();
595 map {
596 my $color
597 = $self->_color(
598 $border->first_child($_)->first_child('color') );
599 $colors{ $_ . '_color' } = $color if $color;
600 } qw(left right top bottom);
601
602 my %types = ();
603 map {
604 my $style = $border->first_child($_)->att('style');
605 $types{$_} = $border_map{$style} if $style;
606 } qw(left right top bottom);
607
608 my %diag = ();
609 my $down = $border->att('diagonalDown') // 0;
610 my $up = $border->att('diagonalUp') // 0;
611 $diag{'diag_type'} = 2 * $down + $up if $down + $up;
612 my $dborder = $border->first_child('diagonal')->att('style');
613 $diag{'diag_border'} = $border_map{$dborder} if $dborder;
614 my $dcolor = $border->first_child('diagonal')->first_child('color');
615 $diag{'diag_color'} = $self->_color($dcolor) if $dcolor;
616
617 my $border_ref = { %colors, %types, %diag };
618 # use Mojo::Util qw(dumper);
619 # warn dumper ($border_ref);
620 # $border_ref;
621
622 } $styles->find_nodes('//borders/border');
623 return $borders;
624 }
625 ###############################################################################
626 sub _parse_fills {
627
628 =head2 _parse_fills
629
630 Parses styles for cell fills (pattern, foreground and background colors.
631 horizontal and horizontal and vertical cell alignments in a sheet.
632
633 Gradients are parsed, but since EWX does not support gradients, a
634 pattern is substituted.
635
636 =cut
637
638 my $self = shift;
639 my ($styles) = @_;
640 my %fill_map = (
641 darkDown => 7,
642 darkGray => 3,
643 darkGrid => 9,
644 darkHorizontal => 5,
645 darkTrellis => 10,
646 darkUp => 8,
647 darkVertical => 6,
648 gray0625 => 18,
649 gray125 => 17,
650 lightDown => 13,
651 lightGray => 4,
652 lightGrid => 15,
653 lightHorizontal => 11,
654 lightTrellis => 16,
655 lightUp => 14,
656 lightVertical => 12,
657 mediumGray => 2,
658 none => 0,
659 solid => 1,
660 );
661
662 # Pattern Fills / # Gradient Fills
663 # EWX does not support Gradient fills (yet??)
664 # so, substitute a pattern fill to keep indices aligned
665 my $fills = [];
666 push @$fills, map {
667 my ( $fill, @color );
668 my $pat = $_->first_child('patternFill');
669 if ($pat) {
670 for (qw[fg bg]) {
671 my $fgbg = $self->_color( $pat->first_child("${_}Color"), 1 );
672 push @color, ( "${_}_color", $fgbg ) if $fgbg;
673 }
674 $fill = { pattern => $fill_map{ $pat->att('patternType') }, @color };
675 }
676 my $gradient = $_->first_child('gradientFill');
677 if ($gradient) {
678 my @stop_colors = $gradient->find_nodes('stop/color');
679 my $fg = $self->_color( $stop_colors[0], 1 );
680 my $bg = $self->_color( $stop_colors[1], 1 );
681 my %hfg = ( 'fg_color' => ( $fg // 'white' ) );
682 my %hbg = ( 'bg_color' => ( $bg // 'black' ) );
683
684 ### ?? Create a lightGrid pattern in place of a gradient for now
685 $fill = { pattern => $fill_map{'lightGrid'}, %hfg, %hbg };
686 }
687 $fill;
688 } $styles->find_nodes('//fills/fill');
689 $fills;
690 }
691 ###############################################################################
692 sub _parse_fonts {
693
694 =head2 _parse_fonts
695
696 Parses font information (font name, size, super/sub scripts, alignment
697 colors, underline, bold, italic, and strikeout attributes).
698
699 =cut
700
701 my $self = shift;
702 my ( $styles, $xpath ) = @_;
703 $xpath //= '//fonts/font';
704
705 my $fonts = [];
706 @$fonts = map {
707
708 my $u = $_->first_child('u');
709 my $vert = $_->first_child('vertAlign');
710 my $font;
711
712 my $size = $_->first_child('sz')->att('val');
713 $font->{'size'} = $size if $size;
714
715 # XXX if color tag is missing is it black?? '#000000'
716 my $color = $_->first_child('color');
717 $font->{'color'} = $self->_color($color) if $color;
718
719 my $script_map = {
720 'superscript' => 1,
721 'subscript' => 2,
722 };
723
724 if ( defined $vert ) {
725 my $script = $vert->att('val');
726 $font->{'font_script'} = $script_map->{$script} if $script;
727 }
728
729 my $u_map = {
730 'single' => 1,
731 'double' => 2,
732 'singleAccounting' => 33,
733 'doubleAccounting' => 34,
734 };
735 if ( defined $u ) {
736
737 # XXX sometimes style xml files can contain just <u/> with no
738 # val attribute. i think this means single underline, but not sure
739 my $underline = $u->att('val') // 'single';
740 $font->{'underline'} = $u_map->{$underline} if $underline;
741 }
742
743 my $font_name = $_->first_child('name');
744 $font->{'font'} = $font_name->att('val') if $font_name;
745
746 # Alternate for rich strings (embedded font)
747 my $rFont = $_->first_child('rFont');
748 $font->{'font'} = $rFont->att('val') if $rFont;
749
750 my $bold = $_->first_child('b');
751 $font->{'bold'} = 1 if $bold;
752
753 my $italic = $_->first_child('i');
754 $font->{'italic'} = 1 if $italic;
755
756 my $strike = $_->first_child('strike');
757 $font->{'font_strikeout'} = 1 if $strike;
758
759 $font;
760 } $styles->find_nodes($xpath);
761 return $fonts;
762 }
763 ###############################################################################
764 sub _parse_numbers {
765
766 =head2 _parse_numbers
767
768 Parses styles for cell number formats (financial, decimal, exponential, date-time, ...)
769
770 =cut
771
772 my $self = shift;
773 my ($styles) = @_;
774 my $number_format = { 0 => {} };
775 map {
776 my $id = $_->att('numFmtId') // 0;
777
778 # defaults are from
779 #http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/e27aaf16-b900-4654-8210-83c5774a179c
780 # Defaults do not need to be re-created.
781 my $code = $_->att('formatCode') // $id;
782 $number_format->{$id} = { num_format => $code } if $id;
783 } $styles->find_nodes('//numFmts/numFmt');
784 return $number_format;
785 }
786 ###############################################################################
787 sub _parse_protection {
788
789 =head2 _parse_protection
790
791 Parses locked and hidden attributes for a cell. These are only
792 useful if the worksheet is locked.
793
794 This module does not lock the workbook or the worksheet.
795
796 =cut
797
798 my $self = shift;
799 my ($node) = @_;
800 my @protection = qw(locked hidden);
801 my %prot = ();
802 if ( my $protection = $_->first_child('protection') ) {
803 map {
804 my $v = $protection->att($_);
805 $prot{$_} = $v if defined $v;
806 } @protection;
807 }
808 return %prot;
809 }
810 ###############################################################################
811 sub _parse_shared_strings {
812
813 =head2 _parse_shared_strings
814
815 Parses the shared strings file. Excel does not directly store
816 string values with the cell, but stores an index into the shared
817 strings table instead, to save memory, if a string value is
818 referenced more than once. Shared strings also contain
819 formatting if multiple formats are applied within a cell (See
820 write_rich_string in EWX.
821
822 =cut
823
824 my $self = shift;
825 my ($strings) = @_;
826
827 return unless $strings;
828 my $xml = XML::Twig->new(
829 twig_handlers => {
830 'si' => sub {
831 my ( $twig, $si ) = @_;
832
833 my $callback = $self->{template_callback};
834 my $call = ref($callback) eq 'CODE';
835
836 # plain text strings
837 my $t = $si->first_child('t');
838 if ($t) {
839 my $text = $t->text();
840 $call and $self->$callback( \$text );
841 push @{ $self->{SHARED_STRINGS} }, $text;
842 }
843
844 # rich text strings; String item (si) with multiple
845 # text elements, with optional formatting
846 my $rich = [];
847 for my $r ( $si->find_nodes('r') ) {
848 my $text = $r->first_child('t')->text();
849 $call and $self->$callback( \$text );
850 my $rPr = $r->first_child('rPr');
851
852 if ($rPr) {
853 my $xml = $r->first_child('rPr')->outer_xml();
854 my $twig = XML::Twig->parse($xml);
855 my $fonts = $self->_parse_fonts( $twig, '//rPr' );
856 my $format = $self->{EWX}->add_format( %{ $fonts->[0] } );
857 push @$rich, $format, $text;
858 }
859 else {
860 push @$rich, $text;
861 }
862 }
863 push( @{ $self->{SHARED_STRINGS} }, $rich ) if scalar(@$rich);
864 $twig->purge;
865 }
866 }
867 ); # } twig_handlers ) new
868 $xml->parse($strings);
869 }
870 ###############################################################################
871 sub _parse_sheet {
872
873 =head2 _parse_sheet
874
875 Parses an individual worksheet. This is done in two passes.
876 See _parse_sheet_pass1 and _parse_sheet_pass2 for what elements are
877 parsed. This is necessary because the parse order of XML::Twig callbacks
878 are in the wrong order for some sheet information (header/footer information,
879 hyperlinks, and merged cells).
880
881 =cut
882
883 my $self = shift;
884 my ( $sheet, $sheet_file ) = @_;
885
886 # Hyperlinks are local to each sheet
887 $self->{HYPERLINKS} = {};
888 my $pass1
889 = XML::Twig->new( twig_roots => $self->_parse_sheet_pass1($sheet) );
890 $pass1->parse( $sheet_file->{xml} );
891
892 # Half time show - track down the URLs for hyperlinks found in pass 1
893 while ( my ( $a1, $rid ) = each %{ $self->{HYPERLINKS} } ) {
894 my $xpath = qq<//Relationship[\@Id="$rid"]>;
895 my $url = ( $sheet_file->{rels}->find_nodes($xpath) )[0];
896 if ($url) {
897 my $target = $url->att('Target');
898 my $mode = lc( $url->att('TargetMode') );
899 $self->{HYPERLINKS}{$a1} = "$target";
900 }
901 }
902
903 # 2nd pass: cell/row building is dependent on having parsed the merge definitions
904 # beforehand. Also header/footer margins must be parsed before setting header/footer
905 my $pass2
906 = XML::Twig->new( twig_roots => $self->_parse_sheet_pass2($sheet) );
907 $pass2->parse( $sheet_file->{xml} );
908 }
909 ###############################################################################
910 sub _parse_sheet_pass1 {
911
912 =head2 _parse_sheet_pass1
913
914 Parses some elements in a worksheet ( pageMargins, headerFooter,
915 hyperlinks, pageSetup, Merged Cells, Sheet Formatting Row and Column
916 heights, Sheet selection, and Tab Color)
917
918 =cut
919
920 my $self = shift;
921 my ($sheet) = @_;
922
923 my $default_row_height = 15;
924 my $default_column_width = 10;
925 my %hf_margin;
926
927 return {
928 'pageMargins' => sub {
929 my ( $twig, $margin ) = @_;
930 map {
931 my $method = "set_margin_" . $_;
932 $sheet->$method( $margin->att($_) // 0 );
933 } qw( left right top bottom );
934
935 # Capture header/footer margin, for use with headerFooter callback
936 $hf_margin{Header} = $margin->att('header');
937 $hf_margin{Footer} = $margin->att('footer');
938 $twig->purge;
939 },
940
941 # Headers/Footers
942 'headerFooter' => sub {
943 my ( $twig, $hf ) = @_;
944
945 my $callback = $self->{template_callback};
946 my $call = ref($callback) eq 'CODE';
947 for (qw[Header Footer]) {
948 my $child = $hf->first_child( 'odd' . $_ );
949 my $text = $child ? $child->text() : '';
950 $call and $self->$callback( \$text );
951 my $method = 'set_' . lc($_);
952 $sheet->$method( $text, $hf_margin{$_} );
953 }
954
955 $twig->purge;
956 },
957
958 # Hyperlinks
959 'hyperlinks/hyperlink ' => sub {
960 my ( $twig, $link ) = @_;
961 my $a1 = $link->att('ref');
962 $self->{HYPERLINKS}{$a1} = $link->att('r:id');
963 $twig->purge;
964 },
965
966 # Paper/page setup
967 'pageSetup' => sub {
968 my ( $twig, $setup ) = @_;
969 my %lookup = (
970 orientation => => 'set_portrait',
971 firstPageNumber => 'set_start_page',
972 scale => 'set_print_scale',
973 paperSize => 'set_paper'
974
975 # horizontalDpi ??
976 # verticalDpi
977 );
978
979 my @page
980 = qw(scale orientation horizontalDpi verticalDpi paperSize firstPageNumber scale);
981 foreach (@page) {
982
983 # Ignore if we do not have a EWX method for this attribute
984 my $method = $lookup{$_} // next;
985
986 # Ignore if no value defined for this attribute
987 next unless my $set = $setup->att($_);
988
989 # Special case; no generic method to set portrait/landscape
990 $method = 'set_landscape' if $set eq 'landscape';
991 $sheet->$method($set);
992 }
993
994 $twig->purge;
995 },
996
997 # Merged cells (Create the ranges: content will be added later)
998 'mergeCells/mergeCell' => sub {
999 my ( $twig, $merge_area ) = @_;
1000
1001 if ( my $ref = $merge_area->att('ref') ) {
1002 my ( $topleft, $bottomright ) = $ref =~ /([^:]+):([^:]+)/;
1003 # my ( $tr, $lc ) = $self->_cell_to_row_col($topleft);
1004 # my ( $br, $rc ) = $self->_cell_to_row_col($bottomright);
1005
1006 # Merged Ranges/Areas: save the address for pass 2.
1007 # cells within the merged range will be processed with
1008 # merge_range_type(), instead of write()
1009 $self->{MERGED_RANGES}{$sheet->{_index}}{$topleft} = $ref;
1010 }
1011 $twig->purge;
1012 },
1013
1014 # Default row height
1015 'sheetFormatPr' => sub {
1016 my ( $twig, $format ) = @_;
1017 $default_row_height //= $format->att('defaultRowHeight');
1018 $default_column_width //= $format->att('baseColWidth');
1019 $sheet->set_default_row($default_row_height);
1020 $twig->purge;
1021 },
1022
1023 'col' => sub {
1024 my ( $twig, $col ) = @_;
1025
1026 for my $ci ( $col->att('min') .. $col->att('max') ) {
1027 #set_column($first,$last,$width,$fmt,$hide,$level,$collapsed )
1028 $sheet->set_column( $ci - 1, $ci - 1, $col->att('width') );
1029 #?? just sets width, not $col->att('style')
1030 }
1031 $twig->purge;
1032 },
1033
1034 'row' => sub {
1035 my ( $twig, $row ) = @_;
1036
1037 # ?? just sets row height. No formatting yet
1038 # set_row( $row, $height, $format, $hidden, $level, $collapsed )
1039 $sheet->set_row( $row->att('r') - 1, $row->att('ht') );
1040 $twig->purge;
1041 },
1042
1043 'sheetView/selection' => sub {
1044 my ( $twig, $selection ) = @_;
1045 my $range = $selection->att('sqref')
1046 // $selection->att('activeCell') // 'A1';
1047 $sheet->set_selection($range);
1048 $twig->purge;
1049 },
1050
1051 'sheetPr/tabColor' => sub {
1052 my ( $twig, $tab_color ) = @_;
1053 $sheet->set_tab_color( $tab_color->att('rgb') );
1054 $twig->purge;
1055 }
1056
1057 } # return hashref
1058 }
1059 ###############################################################################
1060 sub _parse_sheet_pass2 {
1061
1062 =head2 _parse_sheet_pass2
1063
1064 Parses cell contents (first by row, then by column). Cells can contain
1065 inline strings, string references, direct string values, formulas,
1066 and hyperlinks. Each cell may also contain formatting information.
1067 The format is in an index to formatting for borders, shading, alignment,
1068 font, and number formats.
1069
1070 =cut
1071
1072 my $self = shift;
1073 my ($sheet) = @_;
1074
1075 return {
1076 'sheetData/row' => sub {
1077 my ( $twig, $row_elt ) = @_;
1078 my $sheet_idx = $sheet->{_index};
1079 for my $cell ( $row_elt->children('c') ) {
1080
1081 my $string_index = 0;
1082 my $a1 = $cell->att('r'); # Cell Address
1083 my $t = $cell->att('t') || 'n'; # Cell Type
1084 my $s = $cell->att('s'); # Cell Format Index
1085 my $val_xml
1086 = $t eq 'inlineStr'
1087 ? $cell->first_child('is')->first_child('t')
1088 : $cell->first_child('v');
1089 my $val = $val_xml ? $val_xml->text() : undef;
1090
1091
1092 my $format_idx = $s // 0;
1093 my $format = $self->{FORMATS}[$format_idx];
1094
1095 # Formatted cell, no contents
1096 if ( !defined($val) ) {
1097 $sheet->write_blank($a1, $format);
1098 next;
1099 }
1100
1101 if ( $t eq 's' ) {
1102 $string_index = $val;
1103 $val = $self->{SHARED_STRINGS}[$val];
1104
1105 my $is_array = ref($val) eq 'ARRAY';
1106 my @aval = $is_array ? @$val : ($val);
1107 if ( my $ref = $self->{MERGED_RANGES}{$sheet_idx}{$a1} ) {
1108 my $type = $is_array ? 'rich_string' : 'string';
1109 $sheet->merge_range_type($type, $ref, @aval, $format );
1110 next;
1111 }
1112
1113 # Special case for multiple formats in a cell
1114 # see _parse_shared_strings for rPr nodes
1115 if ( $is_array ) {
1116 $sheet->write_rich_string( $a1, @aval );
1117 next;
1118 }
1119 if ( my $url = $self->{HYPERLINKS}{$a1} ) {
1120 $sheet->write_url( $a1, $url, $format, $val );
1121 next;
1122 }
1123 $sheet->write_string( $a1, $val, $format );
1124 next;
1125 }
1126
1127 # In-line string (not seen in practice)
1128 elsif ( $t eq 'str' ) {
1129 $val = '=' . $cell->first_child('f')->text();
1130 }
1131
1132 # Formulas
1133 elsif ( $t eq 'n' ) {
1134 if ( my $form_child = $cell->first_child('f') ) {
1135 my $is_array = $form_child->att('t');
1136 my $ref = $form_child->att('ref');
1137 my $formula = $form_child->text() // q[="No Formula Found"];
1138 if ($is_array and $ref) {
1139 $sheet->write_array_formula( $ref, "=${formula}", $format, $val );
1140 }
1141 else {
1142 #if ( my $ref = $self->{MERGED_RANGES}{$a1} ) {
1143 if ( my $ref = $self->{MERGED_RANGES}{$sheet_idx}{$a1} ) {
1144 $sheet->merge_range_type('formula', $ref, "=${formula}", $format, $val);
1145 } else {
1146 $sheet->write_formula( $a1, "=${formula}", $format, $val );
1147 }
1148 }
1149 next;
1150 }
1151
1152 }
1153 elsif ( $t eq 'b' ) {
1154 $val = $val ? "TRUE" : "FALSE";
1155 }
1156 elsif ( $t eq 'e' ) {
1157 }
1158 elsif ( $t eq 'str' || $t eq 'inlineStr' ) {
1159 }
1160 else {
1161 warn "unimplemented type $t found in cell $a1"; # XXX
1162 }
1163
1164 $sheet->write( $a1, $val, $format );
1165 }
1166
1167 $twig->purge;
1168 }
1169 };
1170 }
1171 ###############################################################################
1172 sub _parse_styles {
1173
1174 =head2 _parse_styles
1175
1176 Parses style information.
1177 Parses number formats directly. Calls subroutines to parse
1178 fonts, fills, and borders, alignment, and protection.
1179
1180 Finally, parses Cell Xfs elements to Combine fonts, borders, number formats,
1181 alignment, patterns, into a single format specification.
1182
1183 Calls EWX add_formats to create a format, and stores the format information
1184 in a FORMAT array within the object.
1185
1186 =cut
1187
1188 my $self = shift;
1189 my ($styles) = @_;
1190
1191 # Number Formats
1192 my $numfmt = $self->_parse_numbers($styles);
1193
1194 # Fonts / Fills / Borders
1195 my $fonts = $self->_parse_fonts( $styles, '//fonts/font' );
1196 my $fills = $self->_parse_fills($styles);
1197 my $borders = $self->_parse_borders($styles);
1198
1199 # Cell Xfs
1200 # Combine fonts, borders, number formats, alignment, patterns, into a single format spec
1201 map {
1202 # Also has applyAlignment property, which we do not examine
1203 # same for ApplyFont, ApplyBorder ApplyProtection
1204
1205 my %halign = $self->_parse_alignment($_);
1206 my %hprot = $self->_parse_protection($_);
1207 my %hfont = %{ $fonts->[ $_->att('fontId') // 0 ] };
1208
1209 my $numFmtId = $_->att('numFmtId') // 0;
1210 # Use custom format, or built-in if custom not found
1211 my $ref = $numfmt->{$numFmtId} // { num_format => $numFmtId };
1212 my %hnumfmt = %$ref;
1213
1214 my %hbord = %{ $borders->[ $_->att('borderId') // 0 ] };
1215 my %hfill = %{ $fills->[ $_->att('fillId') // 0 ] };
1216
1217 my $fmt
1218 = $self->{EWX}
1219 ->add_format( %hfont, %hnumfmt, %hbord, %halign, %hprot, %hfill );
1220 push @{ $self->{FORMATS} }, $fmt;
1221 } $styles->find_nodes('//cellXfs/xf');
1222 }
1223 ###############################################################################
1224 sub _parse_themes {
1225
1226 =head2 _parse_themes
1227
1228 Parses theme information. Some color settings are referenced by an
1229 index to the theme.
1230
1231 =cut
1232
1233 my $self = shift;
1234 my ($themes) = @_;
1235
1236 return {} unless $themes;
1237
1238 my @color
1239 = map { $_->name eq 'a:sysClr' ? $_->att('lastClr') : $_->att('val') }
1240 $themes->find_nodes('//a:clrScheme/*/*');
1241
1242 # this shouldn't be necessary, but the documentation is wrong here
1243 # see http://stackoverflow.com/questions/2760976/theme-confusion-in-spreadsheetml
1244 ( $color[0], $color[1] ) = ( $color[1], $color[0] );
1245 ( $color[2], $color[3] ) = ( $color[3], $color[2] );
1246
1247 return { Color => \@color };
1248 }
1249 ###############################################################################
1250 sub _parse_xml {
1251
1252 =head2 _parse_xml
1253
1254 Low level subroutine to parse an entire member of a zip file. Used
1255 for small files, such as xxx.xml.rels, where the entire file is parsed.
1256
1257 For larger files, XML::Twig::twig_handlers are used.
1258
1259 =cut
1260
1261 my $self = shift;
1262 my ( $zip, $subfile ) = @_;
1263
1264 my $member = $zip->memberNamed($subfile);
1265 die "no subfile named $subfile" unless $member;
1266
1267 my $xml = XML::Twig->new;
1268 $xml->parse( scalar $member->contents );
1269 return $xml;
1270 }
1271 ###############################################################################
1272 sub _rels_for {
1273
1274 =head2 _rels_for
1275
1276 Returns the .rels file name for a sibling workbook or worksheet.
1277
1278 =cut
1279
1280 my $self = shift;
1281 my ($file) = @_;
1282
1283 my @path = split '/', $file;
1284 my $name = pop @path;
1285 $name = '' unless defined $name;
1286 push @path, '_rels';
1287 push @path, "$name.rels";
1288
1289 return join '/', @path;
1290 }
1291 ###############################################################################
1292 sub zzpodtail {
1293
1294 =for pod
1295
1296 =head2 zzpodtail
1297
1298 Dummy subroutine to allow me to hide pod documentation when using code
1299 folding in the editor.
1300
1301 =head1 INSTALLATION
1302
1303 Install with CPAN
1304
1305 cpan Excel::Template::XLSX
1306
1307 or, use the standard Unix style installation.
1308
1309 Unzip and untar the module as follows:
1310
1311 tar -zxvf Excel::Template::XLSX-nnn.tar.gz
1312
1313 The module can be installed using the standard Perl procedure:
1314
1315 perl Makefile.PL
1316 make
1317 make test
1318 make install # As sudo/root
1319
1320 =head1 BUGS
1321
1322 =over 4
1323
1324 =item Large spreadsheets may cause segfaults on perl 5.14 and earlier
1325
1326 This module internally uses XML::Twig, which makes it potentially subject to
1327 L<Bug #71636 for XML-Twig: Segfault with medium-sized document|https://rt.cpan.org/Public/Bug/Display.html?id=71636>
1328 on perl versions 5.14 and below (the underlying bug with perl weak references
1329 was fixed in perl 5.15.5). The larger and more complex the spreadsheet, the
1330 more likely to be affected, but the actual size at which it segfaults is
1331 platform dependent. On a 64-bit perl with 7.6gb memory, it was seen on
1332 spreadsheets about 300mb and above. You can work around this adding
1333 C<XML::Twig::_set_weakrefs(0)> to your code before parsing the spreadsheet,
1334 although this may have other consequences such as memory leaks.
1335
1336 Please report any bugs to GitHub Issues at
1337 L<https://github.com/davidsclarke/Excel-Template-XLSX/issues>.
1338
1339 =back
1340
1341 =head1 SUPPORT
1342
1343 You can find this documentation for this module with the perldoc command.
1344
1345 perldoc Excel::Template::XLSX
1346
1347 You can also look for information at:
1348
1349 =over 4
1350
1351 =item * MetaCPAN
1352
1353 L<https://metacpan.org/release/Excel-Template-XLSX>
1354
1355 =item * RT: CPAN's request tracker
1356
1357 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Excel-Template-XLSX>
1358
1359 =item * Github
1360
1361 L<https://github.com/davidsclarke/Excel-Template-XLSX>
1362
1363 =item * CPAN Ratings
1364
1365 L<http://cpanratings.perl.org/d/Excel-Template-XLSX>
1366
1367 =back
1368
1369 =head1 DEBUGGING TIPS
1370
1371 Using the Perl debugger gets complicated because of XML::Twig. The objects
1372 created by XML::Twig are HUGE. Also, stepping through the code often results
1373 in exceeding a stack depth of >100. The author found it helpful to take
1374 advantage of the simplify() method in XML::Twig when using the debugger 'x'
1375 command to examine variables.
1376
1377 x $node->simplify()
1378
1379 Also, it is helpful to use the 'c' command to jump over XML::Twig subroutine calls and callbacks.
1380
1381 =head1 BUGS
1382
1383 Please report any bugs or feature requests to the author.
1384
1385 =head1 TO DO
1386
1387 Worksheet Activation
1388 Table Formatting/Styles
1389 Calculation Mode
1390
1391 =head1 REPOSITORY
1392
1393 The Excel::Template::XLSX source code is hosted on github:
1394 L<http://github.com/davidsclarke/Excel-Template-xlsx>.
1395
1396 =head1 SEE ALSO
1397
1398 Excel::Writer::XLSX
1399
1400 This module does not provide much documentation on the capabilites of methods
1401 for creating Excel content. The documentation provided with EWX is excellent,
1402 and also has numerous examples included.
1403
1404 Spreadsheet::ParseXLSX
1405
1406 Although this module does not use Spreadsheet::ParseXLSX, the parsing and
1407 comments regarding issues involved with parsing spreadsheets came from this module.
1408
1409 XML::Twig and Archive::Zip
1410
1411 Excel .xlsx files are zippped .xml files. These two modules are used to
1412 unzip the .xlsx file, extract the members, and parse the relative portions
1413 of the .xml files inside.
1414
1415 =head1 ACKNOWLEDGEMENTS
1416
1417 This module leverages the methods in L<Excel::Writer::XLSX|https://metacpan.org/release/Excel-Writer-XLSX>, maintained by L<John McNamara|https://metacpan.org/author/JMCNAMARA>
1418 to recreate the template.
1419
1420 The parser was developed using L<Spreadsheet::ParseXLSX|https://metacpan.org/release/Spreadsheet-ParseXLSX> as a starting point, maintained by L<Jesse Luehrs|https://metacpan.org/author/DOY>.
1421 This parser calls methods in EWX directly when a token is resolved rather than building
1422 up an object representing the parsed content.
1423
1424 =head1 LICENSE AND COPYRIGHT
1425
1426 Either the Perl Artistic Licence L<http://dev.perl.org/licenses/artistic.html>
1427 or the GPL L<http://www.opensource.org/licenses/gpl-license.php>.
1428
1429 AUTHOR
1430
1431 David Clarke dclarke@cpan.org
1432
1433 =cut
1434
1435 }
1436
« build.pl ↑ Summary