summaryrefslogtreecommitdiffstats
path: root/lib/Spreadsheet/ParseXLSX.pm
blob: 0ffbc438ed140e4e6a1be791dcddb36f2425c0e4 (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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
package Spreadsheet::ParseXLSX;
use strict;
use warnings;
use 5.008;
# ABSTRACT: parse XLSX files

use Archive::Zip;
use Graphics::ColorUtils 'rgb2hls', 'hls2rgb';
use Scalar::Util 'openhandle';
use Spreadsheet::ParseExcel 0.61;
use XML::Twig;

use Spreadsheet::ParseXLSX::Decryptor;

=head1 SYNOPSIS

  use Spreadsheet::ParseXLSX;

  my $parser = Spreadsheet::ParseXLSX->new;
  my $workbook = $parser->parse("file.xlsx");
  # see Spreadsheet::ParseExcel for further documentation

=head1 DESCRIPTION

This module is an adaptor for L<Spreadsheet::ParseExcel> that reads XLSX files.
For documentation about the various data that you can retrieve from these
classes, please see L<Spreadsheet::ParseExcel>,
L<Spreadsheet::ParseExcel::Workbook>, L<Spreadsheet::ParseExcel::Worksheet>,
and L<Spreadsheet::ParseExcel::Cell>.

=cut

=method new(%opts)

Returns a new parser instance. Takes a hash of parameters:

=over 4

=item Password

Password to use for decrypting encrypted files.

=back

=cut

sub new {
    my $class = shift;
    my (%args) = @_;

    my $self = bless {}, $class;
    $self->{Password} = $args{Password} if defined $args{Password};

    return $self;
}

=method parse($file, $formatter)

Parses an XLSX file. Parsing errors throw an exception. C<$file> can be either
a filename or an open filehandle. Returns a
L<Spreadsheet::ParseExcel::Workbook> instance containing the parsed data.
The C<$formatter> argument is an optional formatter class as described in L<Spreadsheet::ParseExcel>.

=cut

sub parse {
    my $self = shift;
    my ($file, $formatter) = @_;

    my $zip = Archive::Zip->new;
    my $workbook = Spreadsheet::ParseExcel::Workbook->new;

    if ($self->_check_signature($file)) {
        my $decrypted_file = Spreadsheet::ParseXLSX::Decryptor->open(
            $file,
            $self->{Password}
        );
        $file = $decrypted_file if $decrypted_file;
    }

    if (openhandle($file)) {
        bless $file, 'IO::File' if ref($file) eq 'GLOB'; # sigh
        my $fh = ref($file) eq 'File::Temp'
            ? IO::File->new("<&=" . fileno($file))
            : $file;
        $zip->readFromFileHandle($fh) == Archive::Zip::AZ_OK
            or die "Can't open filehandle as a zip file";
        $workbook->{File} = undef;
        $workbook->{__tempfile} = $file;
    }
    elsif (ref($file) eq 'SCALAR') {
        open my $fh, '+<', $file
            or die "Can't create filehandle from memory data";
        $zip->readFromFileHandle($fh) == Archive::Zip::AZ_OK
            or die "Can't open scalar ref as a zip file";
        $workbook->{File} = undef;
    }
    elsif (!ref($file)) {
        $zip->read($file) == Archive::Zip::AZ_OK
            or die "Can't open file '$file' as a zip file";
        $workbook->{File} = $file;
    }
    else {
        die "Argument to 'new' must be a filename, open filehandle, or scalar ref";
    }

    return $self->_parse_workbook($zip, $workbook, $formatter);
}

sub _check_signature {
    my $self = shift;
    my ($file) = @_;

    my $signature = '';
    if (openhandle($file)) {
        bless $file, 'IO::File' if ref($file) eq 'GLOB'; # sigh
        $file->read($signature, 2);
        $file->seek(-2, IO::File::SEEK_CUR);
    }
    elsif (ref($file) eq 'SCALAR') {
        $signature = substr($$file, 0, 2);
    }
    elsif (!ref($file)) {
        my $fh = IO::File->new($file, 'r');
        $fh->read($signature, 2);
        $fh->close;
    }

    return $signature eq "\xd0\xcf";
}

sub _parse_workbook {
    my $self = shift;
    my ($zip, $workbook, $formatter) = @_;

    my $files = $self->_extract_files($zip);

    my ($version)    = $files->{workbook}->find_nodes('//s:fileVersion');
    my ($properties) = $files->{workbook}->find_nodes('//s:workbookPr');

    if ($version) {
        $workbook->{Version} = $version->att('appName')
                             . ($version->att('lowestEdited')
                                 ? ('-' . $version->att('lowestEdited'))
                                 : (""));
    }

    $workbook->{Flg1904} = $self->_xml_boolean($properties->att('date1904'))
        if $properties;

    $workbook->{FmtClass} = $formatter || Spreadsheet::ParseExcel::FmtDefault->new;

    my $themes = $self->_parse_themes((values %{ $files->{themes} })[0]); # XXX

    $workbook->{Color} = $themes->{Color};

    my $styles = $self->_parse_styles($workbook, $files->{styles});

    $workbook->{Format}    = $styles->{Format};
    $workbook->{FormatStr} = $styles->{FormatStr};
    $workbook->{Font}      = $styles->{Font};

    if ($files->{strings}) {
        my %string_parse_data = $self->_parse_shared_strings(
            $files->{strings},
            $themes->{Color}
        );
        $workbook->{PkgStr} = $string_parse_data{PkgStr};
        $workbook->{Rich}   = $string_parse_data{Rich};
    }

    # $workbook->{StandardWidth} = ...;

    # $workbook->{Author} = ...;

    # $workbook->{PrintArea} = ...;
    # $workbook->{PrintTitle} = ...;

    my @sheets = map {
        my $idx = $_->att('rels:id');
        if ($files->{sheets}{$idx}) {
          my $sheet = Spreadsheet::ParseExcel::Worksheet->new(
              Name     => $_->att('name'),
              _Book    => $workbook,
              _SheetNo => $idx,
          );
          $sheet->{SheetHidden} = 1 if defined $_->att('state') and $_->att('state') eq 'hidden';
          $self->_parse_sheet($sheet, $files->{sheets}{$idx});
          ($sheet)
        } else {
          ()
        }
    } $files->{workbook}->find_nodes('//s:sheets/s:sheet');

    $workbook->{Worksheet}  = \@sheets;
    $workbook->{SheetCount} = scalar(@sheets);

    my ($node) = $files->{workbook}->find_nodes('//s:workbookView');
    my $selected = $node ? $node->att('activeTab') : undef;
    $workbook->{SelectedSheet} = defined($selected) ? 0+$selected : 0;

    return $workbook;
}

sub _parse_sheet {
    my $self = shift;
    my ($sheet, $sheet_file) = @_;

    $sheet->{MinRow} = 0;
    $sheet->{MinCol} = 0;
    $sheet->{MaxRow} = -1;
    $sheet->{MaxCol} = -1;
    $sheet->{Selection} = [ 0, 0 ];

    my %merged_cells;

    my @column_formats;
    my @column_widths;
    my @columns_hidden;
    my @row_heights;
    my @rows_hidden;

    my $default_row_height   = 15;
    my $default_column_width = 10;

    my %cells;

    my $sheet_xml = $self->_new_twig(
        twig_roots => {
            #XXX need a fallback here, the dimension tag is optional
            's:dimension' => sub {
                my ($twig, $dimension) = @_;

                my ($rmin, $cmin, $rmax, $cmax) = $self->_dimensions(
                    $dimension->att('ref')
                );

                $sheet->{MinRow} = $rmin;
                $sheet->{MinCol} = $cmin;
                $sheet->{MaxRow} = $rmax ? $rmax : -1;
                $sheet->{MaxCol} = $cmax ? $cmax : -1;

                $twig->purge;
            },

            's:headerFooter' => sub {
                my ($twig, $hf) = @_;

                my ($helem, $felem) = map {
                    $hf->first_child("s:$_")
                } qw(oddHeader oddFooter);
                $sheet->{Header} = $helem->text
                    if $helem;
                $sheet->{Footer} = $felem->text
                    if $felem;

                $twig->purge;
            },

            's:pageMargins' => sub {
                my ($twig, $margin) = @_;
                map {
                    my $key = "\u${_}Margin";
                    $sheet->{$key} = defined $margin->att($_)
                                    ? $margin->att($_) : 0
                } qw(left right top bottom header footer);

                $twig->purge;
            },

            's:pageSetup' => sub {
                my ($twig, $setup) = @_;
                $sheet->{Scale} = defined $setup->att('scale')
                                ? $setup->att('scale')
                                : 100;
                $sheet->{Landscape} = ($setup->att('orientation') || '') ne 'landscape';
                $sheet->{PaperSize} = defined $setup->att('paperSize')
                                    ? $setup->att('paperSize')
                                    : 1;
                $sheet->{PageStart} = $setup->att('firstPageNumber');
                $sheet->{UsePage} = $self->_xml_boolean($setup->att('useFirstPageNumber'));
                $sheet->{HorizontalDPI} = $setup->att('horizontalDpi');
                $sheet->{VerticalDPI} = $setup->att('verticalDpi');

                $twig->purge;
            },

            's:mergeCells/s:mergeCell' => sub {
                my ( $twig, $merge_area ) = @_;

                if (my $ref = $merge_area->att('ref')) {
                    my ($topleft, $bottomright) = $ref =~ /([^:]+):([^:]+)/;

                    my ($toprow, $leftcol)     = $self->_cell_to_row_col($topleft);
                    my ($bottomrow, $rightcol) = $self->_cell_to_row_col($bottomright);

                    push @{ $sheet->{MergedArea} }, [
                        $toprow, $leftcol,
                        $bottomrow, $rightcol,
                    ];
                    for my $row ($toprow .. $bottomrow) {
                        for my $col ($leftcol .. $rightcol) {
                            $merged_cells{"$row;$col"} = 1;
                        }
                    }
                }

                $twig->purge;
            },

            's:sheetFormatPr' => sub {
                my ( $twig, $format ) = @_;

                $default_row_height   = $format->att('defaultRowHeight')
                  unless defined $default_row_height;
                $default_column_width = $format->att('baseColWidth')
                  unless defined $default_column_width;

                $twig->purge;
            },

            's:col' => sub {
                my ( $twig, $col ) = @_;

                for my $colnum ($col->att('min')..$col->att('max')) {
                    $column_widths[$colnum - 1] = $col->att('width');
                    $column_formats[$colnum - 1] = $col->att('style');
                    $columns_hidden[$colnum - 1] = $self->_xml_boolean($col->att('hidden'));
                }

                $twig->purge;
            },

            's:row' => sub {
                my ( $twig, $row ) = @_;

                $row_heights[ $row->att('r') - 1 ] = $row->att('ht');
                $rows_hidden[ $row->att('r') - 1 ] = $self->_xml_boolean($row->att('hidden'));

                $twig->purge;
            },

            's:selection' => sub {
                my ( $twig, $selection ) = @_;

                if (my $cell = $selection->att('activeCell')) {
                    $sheet->{Selection} = [ $self->_cell_to_row_col($cell) ];
                }
                elsif (my $range = $selection->att('sqref')) {
                    my ($topleft, $bottomright) = $range =~ /([^:]+):([^:]+)/;
                    $sheet->{Selection} = [
                        $self->_cell_to_row_col($topleft),
                        $self->_cell_to_row_col($bottomright),
                    ];
                }

                $twig->purge;
            },

            's:sheetPr/s:tabColor' => sub {
                my ( $twig, $tab_color ) = @_;

                $sheet->{TabColor} = $self->_color($sheet->{_Book}{Color}, $tab_color);

                $twig->purge;
            },

            's:sheetData/s:row' => sub {
                my ( $twig, $row_elt ) = @_;

                for my $cell ( $row_elt->children('s:c') ){
                    my ($row, $col) = $self->_cell_to_row_col($cell->att('r'));
                    $sheet->{MaxRow} = $row
                        if $sheet->{MaxRow} < $row;
                    $sheet->{MaxCol} = $col
                        if $sheet->{MaxCol} < $col;
                    my $type = $cell->att('t') || 'n';
                    my $val_xml;
                    if ($type ne 'inlineStr') {
                        $val_xml = $cell->first_child('s:v');
                    }
                    elsif (defined $cell->first_child('s:is')) {
                        $val_xml = ($cell->find_nodes('.//s:t'))[0];
                    }
                    my $val = $val_xml ? $val_xml->text : undef;

                    my $long_type;
                    my $Rich;
                    if (!defined($val)) {
                        $long_type = 'Text';
                        $val = '';
                    }
                    elsif ($type eq 's') {
                        $long_type = 'Text';
                        $Rich = $sheet->{_Book}{Rich}->{$val};
                        $val  = $sheet->{_Book}{PkgStr}[$val];
                    }
                    elsif ($type eq 'n') {
                        $long_type = 'Numeric';
                        $val = defined($val) ? 0+$val : undef;
                    }
                    elsif ($type eq 'd') {
                        $long_type = 'Date';
                    }
                    elsif ($type eq 'b') {
                        $long_type = 'Text';
                        $val = $val ? "TRUE" : "FALSE";
                    }
                    elsif ($type eq 'e') {
                        $long_type = 'Text';
                    }
                    elsif ($type eq 'str' || $type eq 'inlineStr') {
                        $long_type = 'Text';
                    }
                    else {
                        die "unimplemented type $type"; # XXX
                    }

                    my $format_idx = $cell->att('s') || 0;
                    my $format = $sheet->{_Book}{Format}[$format_idx];
                    die "unknown format $format_idx" unless $format;

                    # see the list of built-in formats below in _parse_styles
                    # XXX probably should figure this out from the actual format string,
                    # but that's not entirely trivial
                    if (grep { $format->{FmtIdx} == $_ } 14..22, 45..47) {
                        $long_type = 'Date';
                    }

                    my $formula = $cell->first_child('s:f');
                    my $cell = Spreadsheet::ParseExcel::Cell->new(
                        Val      => $val,
                        Type     => $long_type,
                        Merged   => undef, # fix up later
                        Format   => $format,
                        FormatNo => $format_idx,
                        ($formula
                            ? (Formula => $formula->text)
                            : ()),
                        Rich     => $Rich,
                    );
                    $cell->{_Value} = $sheet->{_Book}{FmtClass}->ValFmt(
                        $cell, $sheet->{_Book}
                    );
                    $cells{"$row;$col"} = $cell;
                    $sheet->{Cells}[$row][$col] = $cell;
                }

                $twig->purge;
            },
        }
    );

    $sheet_xml->parse( $sheet_file );

    for my $key (keys %merged_cells) {
        $cells{$key}{Merged} = 1 if $cells{$key};
    }

    if ( ! $sheet->{Cells} ){
        $sheet->{MaxRow} = $sheet->{MaxCol} = -1;
    }

    $sheet->{DefRowHeight} = 0+$default_row_height;
    $sheet->{DefColWidth} = 0+$default_column_width;
    $sheet->{RowHeight} = [
        map { defined $_ ? 0+$_ : 0+$default_row_height } @row_heights
    ];
    $sheet->{RowHidden} = \@rows_hidden;
    $sheet->{ColWidth} = [
        map { defined $_ ? 0+$_ : 0+$default_column_width } @column_widths
    ];
    $sheet->{ColFmtNo} = \@column_formats;
    $sheet->{ColHidden} = \@columns_hidden;

}

sub _get_text_and_rich_font_by_cell {
    my $self = shift;
    my ($si, $theme_colors) = @_;

    # XXX
    my %default_font_opts = (
        Height         => 12,
        Color          => '#000000',
        Name           => '',
        Bold           => 0,
        Italic         => 0,
        Underline      => 0,
        UnderlineStyle => 0,
        Strikeout      => 0,
        Super          => 0,
    );

    my $string_text = '';
    my @rich_font_by_cell;
    my @nodes_r = $si->find_nodes('.//s:r');
    if (@nodes_r > 0) {
        for my $chunk (map { $_->children } @nodes_r) {
            my $string_length = length($string_text);
            if ($chunk->name eq 's:t') {
                if (!@rich_font_by_cell) {
                    push @rich_font_by_cell, [
                        $string_length,
                        Spreadsheet::ParseExcel::Font->new(%default_font_opts)
                    ];
                }
                $string_text .= $chunk->text;
            }
            elsif ($chunk->name eq 's:rPr') {
                my %format_text = %default_font_opts;
                for my $node_format ($chunk->children) {
                    if ($node_format->name eq 's:sz') {
                        $format_text{Height} = $node_format->att('val');
                    }
                    elsif ($node_format->name eq 's:color') {
                        $format_text{Color} = $self->_color(
                            $theme_colors,
                            $node_format
                        );
                    }
                    elsif ($node_format->name eq 's:rFont') {
                        $format_text{Name} = $node_format->att('val');
                    }
                    elsif ($node_format->name eq 's:b') {
                        $format_text{Bold} = 1;
                    }
                    elsif ($node_format->name eq 's:i') {
                        $format_text{Italic} = 1;
                    }
                    elsif ($node_format->name eq 's:u') {
                        $format_text{Underline} = 1;
                        if (defined $node_format->att('val')) {
                            $format_text{UnderlineStyle} = 2;
                        } else {
                            $format_text{UnderlineStyle} = 1;
                        }
                    }
                    elsif ($node_format->name eq 's:strike') {
                        $format_text{Strikeout} = 1;
                    }
                    elsif ($node_format->name eq 's:vertAlign') {
                        if ($node_format->att('val') eq 'superscript') {
                            $format_text{Super} = 1;
                        }
                        elsif ($node_format->att('val') eq 'subscript') {
                            $format_text{Super} = 2;
                        }
                    }
                }
                push @rich_font_by_cell, [
                    $string_length,
                    Spreadsheet::ParseExcel::Font->new(%format_text)
                ];
            }
        }
    }
    else {
        $string_text = join '', map { $_->text } $si->find_nodes('.//s:t');
    }

    return (
        String => $string_text,
        Rich => \@rich_font_by_cell,
    );
}

sub _parse_shared_strings {
    my $self = shift;
    my ($strings, $theme_colors) = @_;

    my $PkgStr = [];

    my %richfonts;
    if ($strings) {
        my $xml = $self->_new_twig(
            twig_handlers => {
                's:si' => sub {
                    my ( $twig, $si ) = @_;

                    my %text_rich = $self->_get_text_and_rich_font_by_cell(
                        $si,
                        $theme_colors
                    );
                    $richfonts{scalar @$PkgStr} = $text_rich{Rich};
                    push @$PkgStr, $text_rich{String};
                    $twig->purge;
                },
            }
        );
        $xml->parse( $strings );
    }
    return (
        Rich   => \%richfonts,
        PkgStr => $PkgStr,
    );
}

sub _parse_themes {
    my $self = shift;
    my ($themes) = @_;

    return {} unless $themes;

    my @color = map {
        $_->name eq 'drawmain:sysClr' ? $_->att('lastClr') : $_->att('val')
    } $themes->find_nodes('//drawmain:clrScheme/*/*');

    # this shouldn't be necessary, but the documentation is wrong here
    # see http://stackoverflow.com/questions/2760976/theme-confusion-in-spreadsheetml
    ($color[0], $color[1]) = ($color[1], $color[0]);
    ($color[2], $color[3]) = ($color[3], $color[2]);

    return {
        Color => \@color,
    }
}

sub _parse_styles {
    my $self = shift;
    my ($workbook, $styles) = @_;

    # these defaults are from
    # http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/e27aaf16-b900-4654-8210-83c5774a179c
    my %default_format_str = (
        0  => 'GENERAL',
        1  => '0',
        2  => '0.00',
        3  => '#,##0',
        4  => '#,##0.00',
        5  => '$#,##0_);($#,##0)',
        6  => '$#,##0_);[Red]($#,##0)',
        7  => '$#,##0.00_);($#,##0.00)',
        8  => '$#,##0.00_);[Red]($#,##0.00)',
        9  => '0%',
        10 => '0.00%',
        11 => '0.00E+00',
        12 => '# ?/?',
        13 => '# ??/??',
        14 => 'm/d/yyyy',
        15 => 'd-mmm-yy',
        16 => 'd-mmm',
        17 => 'mmm-yy',
        18 => 'h:mm AM/PM',
        19 => 'h:mm:ss AM/PM',
        20 => 'h:mm',
        21 => 'h:mm:ss',
        22 => 'm/d/yyyy h:mm',
        37 => '#,##0_);(#,##0)',
        38 => '#,##0_);[Red](#,##0)',
        39 => '#,##0.00_);(#,##0.00)',
        40 => '#,##0.00_);[Red](#,##0.00)',
        45 => 'mm:ss',
        46 => '[h]:mm:ss',
        47 => 'mm:ss.0',
        48 => '##0.0E+0',
        49 => '@',
    );

    my %default_format_opts = (
        IgnoreFont         => 1,
        IgnoreFill         => 1,
        IgnoreBorder       => 1,
        IgnoreAlignment    => 1,
        IgnoreNumberFormat => 1,
        IgnoreProtection   => 1,
        FontNo             => 0,
        FmtIdx             => 0,
        Lock               => 1,
        Hidden             => 0,
        AlignH             => 0,
        Wrap               => 0,
        AlignV             => 2,
        Rotate             => 0,
        Indent             => 0,
        Shrink             => 0,
        BdrStyle           => [0, 0, 0, 0],
        BdrColor           => [undef, undef, undef, undef],
        BdrDiag            => [0, 0, undef],
        Fill               => [0, undef, undef],
    );

    if (!$styles) {
        # XXX i guess?
        my $font = Spreadsheet::ParseExcel::Font->new(
            Height         => 12,
            Color          => '#000000',
            Name           => '',
        );
        my $format = Spreadsheet::ParseExcel::Format->new(
            %default_format_opts,
            Font => $font,
        );

        return {
            FormatStr => \%default_format_str,
            Font      => [ $font ],
            Format    => [ $format ],
        };
    }

    my %halign = (
        center           => 2,
        centerContinuous => 6,
        distributed      => 7,
        fill             => 4,
        general          => 0,
        justify          => 5,
        left             => 1,
        right            => 3,
    );

    my %valign = (
        bottom      => 2,
        center      => 1,
        distributed => 4,
        justify     => 3,
        top         => 0,
    );

    my %border = (
        dashDot          => 9,
        dashDotDot       => 11,
        dashed           => 3,
        dotted           => 4,
        double           => 6,
        hair             => 7,
        medium           => 2,
        mediumDashDot    => 10,
        mediumDashDotDot => 12,
        mediumDashed     => 8,
        none             => 0,
        slantDashDot     => 13,
        thick            => 5,
        thin             => 1,
    );

    my %fill = (
        darkDown        => 7,
        darkGray        => 3,
        darkGrid        => 9,
        darkHorizontal  => 5,
        darkTrellis     => 10,
        darkUp          => 8,
        darkVertical    => 6,
        gray0625        => 18,
        gray125         => 17,
        lightDown       => 13,
        lightGray       => 4,
        lightGrid       => 15,
        lightHorizontal => 11,
        lightTrellis    => 16,
        lightUp         => 14,
        lightVertical   => 12,
        mediumGray      => 2,
        none            => 0,
        solid           => 1,
    );

    my @fills = map {
        my $pattern_type = $_->att('patternType');
        [
            ($pattern_type ? $fill{$pattern_type} : 0),
            $self->_color($workbook->{Color}, $_->first_child('s:fgColor'), 1),
            $self->_color($workbook->{Color}, $_->first_child('s:bgColor'), 1),
        ]
    } $styles->find_nodes('//s:fills/s:fill/s:patternFill');

    my @borders = map {
        my $border = $_;
        my ($ddiag, $udiag) = map {
            $self->_xml_boolean($border->att($_))
        } qw(diagonalDown diagonalUp);
        my %borderstyles = map {
            my $e = $border->first_child("s:$_");
            $_ => ($e ? $e->att('style') || 'none' : 'none')
        } qw(left right top bottom diagonal);
        my %bordercolors = map {
            my $e = $border->first_child("s:$_");
            $_ => ($e ? $e->first_child('s:color') : undef)
        } qw(left right top bottom diagonal);
        # XXX specs say "begin" and "end" rather than "left" and "right",
        # but... that's not what seems to be in the file itself (sigh)
        {
            colors => [
                map {
                    $self->_color($workbook->{Color}, $bordercolors{$_})
                } qw(left right top bottom)
            ],
            styles => [
                map {
                    $border{$borderstyles{$_}}
                } qw(left right top bottom)
            ],
            diagonal => [
                ( $ddiag &&  $udiag ? 3
               :  $ddiag && !$udiag ? 2
               : !$ddiag &&  $udiag ? 1
               :                      0),
                $border{$borderstyles{diagonal}},
                $self->_color($workbook->{Color}, $bordercolors{diagonal}),
            ],
        }
    } $styles->find_nodes('//s:borders/s:border');

    my %format_str = (
        %default_format_str,
        (map {
            $_->att('numFmtId') => $_->att('formatCode')
        } $styles->find_nodes('//s:numFmts/s:numFmt')),
    );

    my @font = map {
        my $vert = $_->first_child('s:vertAlign');
        my $under = $_->first_child('s:u');
        my $heightelem = $_->first_child('s:sz');
        # XXX i guess 12 is okay?
        my $height = 0+($heightelem ? $heightelem->att('val') : 12);
        my $nameelem = $_->first_child('s:name');
        my $name = $nameelem ? $nameelem->att('val') : '';
        Spreadsheet::ParseExcel::Font->new(
            Height         => $height,
            # Attr           => $iAttr,
            # XXX not sure if there's a better way to keep the indexing stuff
            # intact rather than just going straight to #xxxxxx
            # XXX also not sure what it means for the color tag to be missing,
            # just assuming black for now
            Color          => ($_->first_child('s:color')
                ? $self->_color(
                    $workbook->{Color},
                    $_->first_child('s:color')
                )
                : '#000000'
            ),
            Super          => ($vert
                ? ($vert->att('val') eq 'superscript' ? 1
                 : $vert->att('val') eq 'subscript'   ? 2
                 :                                      0)
                : 0
            ),
            # XXX not sure what the single accounting and double accounting
            # underline styles map to in xlsx. also need to map the new
            # underline styles
            UnderlineStyle => ($under
                # XXX sometimes style xml files can contain just <u/> with no
                # val attribute. i think this means single underline, but not
                # sure
                ? (!$under->att('val')            ? 1
                 : $under->att('val') eq 'single' ? 1
                 : $under->att('val') eq 'double' ? 2
                 :                                  0)
                : 0
            ),
            Name           => $name,

            Bold      => $_->has_child('s:b') ? 1 : 0,
            Italic    => $_->has_child('s:i') ? 1 : 0,
            Underline => $_->has_child('s:u') ? 1 : 0,
            Strikeout => $_->has_child('s:strike') ? 1 : 0,
        )
    } $styles->find_nodes('//s:fonts/s:font');

    my @format = map {
        my $xml_fmt = $_;
        my $alignment  = $xml_fmt->first_child('s:alignment');
        my $protection = $xml_fmt->first_child('s:protection');
        my %ignore = map {
            ("Ignore$_" => !$self->_xml_boolean($xml_fmt->att("apply$_")))
        } qw(Font Fill Border Alignment NumberFormat Protection);
        my %opts = (
            %default_format_opts,
            %ignore,
        );

        $opts{FmtIdx}   = 0+($xml_fmt->att('numFmtId')||0);
        $opts{FontNo}   = 0+($xml_fmt->att('fontId')||0);
        $opts{Font}     = $font[$opts{FontNo}];
        $opts{Fill}     = $fills[$xml_fmt->att('fillId')||0];
        $opts{BdrStyle} = $borders[$xml_fmt->att('borderId')||0]{styles};
        $opts{BdrColor} = $borders[$xml_fmt->att('borderId')||0]{colors};
        $opts{BdrDiag}  = $borders[$xml_fmt->att('borderId')||0]{diagonal};

        if ($alignment) {
            $opts{AlignH} = $halign{$alignment->att('horizontal') || 'general'};
            $opts{Wrap}   = $self->_xml_boolean($alignment->att('wrapText'));
            $opts{AlignV} = $valign{$alignment->att('vertical') || 'bottom'};
            $opts{Rotate} = $alignment->att('textRotation');
            $opts{Indent} = $alignment->att('indent');
            $opts{Shrink} = $self->_xml_boolean($alignment->att('shrinkToFit'));
            # JustLast => $iJustL,
        }

        if ($protection) {
            $opts{Lock} = defined $protection->att('locked')
                ? $self->_xml_boolean($protection->att('locked'))
                : 1;
            $opts{Hidden} = $self->_xml_boolean($protection->att('hidden'));
        }

        # Style    => $iStyle,
        # Key123   => $i123,
        # Merge   => $iMerge,
        # ReadDir => $iReadDir,
        Spreadsheet::ParseExcel::Format->new(%opts)
    } $styles->find_nodes('//s:cellXfs/s:xf');

    return {
        FormatStr => \%format_str,
        Font      => \@font,
        Format    => \@format,
    }
}

sub _extract_files {
    my $self = shift;
    my ($zip) = @_;

    my $type_base =
        'http://schemas.openxmlformats.org/officeDocument/2006/relationships';

    my $rels = $self->_parse_xml(
        $zip,
        $self->_rels_for(''),
    );
    my $wb_name = ($rels->find_nodes(
        qq<//packagerels:Relationship[\@Type="$type_base/officeDocument"]>
    ))[0]->att('Target');
    $wb_name =~ s{^/}{};
    my $wb_xml = $self->_parse_xml($zip, $wb_name);

    my $path_base = $self->_base_path_for($wb_name);
    my $wb_rels = $self->_parse_xml(
        $zip,
        $self->_rels_for($wb_name),
    );

    my $get_path = sub {
        my ($p) = @_;

        return $p =~ s{^/}{}
            ? $p
            : $path_base . $p;
    };

    my ($strings_xml) = map {
        $self->_zip_file_member($zip, $get_path->($_->att('Target')))
    } $wb_rels->find_nodes(qq<//packagerels:Relationship[\@Type="$type_base/sharedStrings"]>);

    my ($styles_xml) = map {
        $self->_parse_xml(
            $zip,
            $get_path->($_->att('Target'))
        )
    } $wb_rels->find_nodes(qq<//packagerels:Relationship[\@Type="$type_base/styles"]>);

    my %worksheet_xml = map {
        ($_->att('Id') => $self->_zip_file_member($zip, $get_path->($_->att('Target'))))
    } $wb_rels->find_nodes(qq<//packagerels:Relationship[\@Type="$type_base/worksheet"]>);

    my %themes_xml = map {
        $_->att('Id') => $self->_parse_xml($zip, $get_path->($_->att('Target')))
    } $wb_rels->find_nodes(qq<//packagerels:Relationship[\@Type="$type_base/theme"]>);

    return {
        workbook => $wb_xml,
        sheets   => \%worksheet_xml,
        themes   => \%themes_xml,
        ($styles_xml
            ? (styles  => $styles_xml)
            : ()),
        ($strings_xml
            ? (strings => $strings_xml)
            : ()),
    };
}

sub _parse_xml {
    my $self = shift;
    my ($zip, $subfile, $map_xmlns) = @_;

    my $xml = $self->_new_twig;
    $xml->parse($self->_zip_file_member($zip, $subfile));

    return $xml;
}

sub _zip_file_member {
    my $self = shift;
    my ($zip, $name) = @_;

    my @members = $zip->membersMatching(qr/^$name$/i);
    die "no subfile named $name" unless @members;

    return scalar $members[0]->contents;
}

sub _rels_for {
    my $self = shift;
    my ($file) = @_;

    my @path = split '/', $file;
    my $name = pop @path;
    $name = '' unless defined $name;
    push @path, '_rels';
    push @path, "$name.rels";

    return join '/', @path;
}

sub _base_path_for {
    my $self = shift;
    my ($file) = @_;

    my @path = split '/', $file;
    pop @path;

    return join('/', @path) . '/';
}

sub _dimensions {
    my $self = shift;
    my ($dim) = @_;

    my ($topleft, $bottomright) = split ':', $dim;
    $bottomright = $topleft unless defined $bottomright;

    my ($rmin, $cmin) = $self->_cell_to_row_col($topleft);
    my ($rmax, $cmax) = $self->_cell_to_row_col($bottomright);

    return ($rmin, $cmin, $rmax, $cmax);
}

sub _cell_to_row_col {
    my $self = shift;
    my ($cell) = @_;

    my ($col, $row) = $cell =~ /([A-Z]+)([0-9]+)/;

    my $ncol = 0;
    for my $char (split //, $col) {
        $ncol *= 26;
        $ncol += ord($char) - ord('A') + 1;
    }
    $ncol = $ncol - 1;

    my $nrow = $row - 1;

    return ($nrow, $ncol);
}

sub _xml_boolean {
    my $self = shift;
    my ($bool) = @_;
    return defined($bool) && ($bool eq 'true' || $bool eq '1');
}

sub _color {
    my $self = shift;
    my ($colors, $color_node, $fill) = @_;

    my $color;
    if ($color_node && !$self->_xml_boolean($color_node->att('auto'))) {
        if (defined $color_node->att('indexed')) {
            # see https://rt.cpan.org/Public/Bug/Display.html?id=93065
            if ($fill && $color_node->att('indexed') == 64) {
                return '#FFFFFF';
            }
            else {
                $color = '#' . Spreadsheet::ParseExcel->ColorIdxToRGB(
                    $color_node->att('indexed')
                );
            }
        }
        elsif (defined $color_node->att('rgb')) {
            $color = '#' . substr($color_node->att('rgb'), 2, 6);
        }
        elsif (defined $color_node->att('theme')) {
            my $theme = $colors->[$color_node->att('theme')];
            if (defined $theme) {
                $color = "#$theme";
            }
            else {
                return undef;
            }
        }

        $color = $self->_apply_tint($color, $color_node->att('tint'))
            if $color_node->att('tint');
    }

    return $color;
}

sub _apply_tint {
    my $self = shift;
    my ($color, $tint) = @_;

    my ($r, $g, $b) = map { oct("0x$_") } $color =~ /#(..)(..)(..)/;
    my ($h, $l, $s) = rgb2hls($r, $g, $b);

    if ($tint < 0) {
        $l = $l * (1.0 + $tint);
    }
    else {
        $l = $l * (1.0 - $tint) + (1.0 - 1.0 * (1.0 - $tint));
    }

    return scalar hls2rgb($h, $l, $s);
}

sub _new_twig {
    my $self = shift;
    my %opts = @_;

    return XML::Twig->new(
        map_xmlns => {
            'http://schemas.openxmlformats.org/spreadsheetml/2006/main' => 's',
            'http://schemas.openxmlformats.org/package/2006/relationships' => 'packagerels',
            'http://schemas.openxmlformats.org/officeDocument/2006/relationships' => 'rels',
            'http://schemas.openxmlformats.org/drawingml/2006/main' => 'drawmain',
        },
        keep_original_prefix => 1,
        %opts,
    );
}

=head1 INCOMPATIBILITIES

This module returns data using classes from L<Spreadsheet::ParseExcel>, so for
the most part, it should just be a drop-in replacement. That said, there are a
couple areas where the data returned is intentionally different:

=over 4

=item Colors

In Spreadsheet::ParseExcel, colors are represented by integers which index into
the color table, and you have to use
C<< Spreadsheet::ParseExcel->ColorIdxToRGB >> in order to get the actual value
out. In Spreadsheet::ParseXLSX, while the color table still exists, cells are
also allowed to specify their color directly rather than going through the
color table. In order to avoid confusion, I normalize all color values in
Spreadsheet::ParseXLSX to their string RGB format (C<"#0088ff">). This affects
the C<Fill>, C<BdrColor>, and C<BdrDiag> properties of formats, and the
C<Color> property of fonts. Note that the default color is represented by
C<undef> (the same thing that C<ColorIdxToRGB> would return).

=item Formulas

Spreadsheet::ParseExcel doesn't support formulas. Spreadsheet::ParseXLSX
provides basic formula support by returning the text of the formula as part of
the cell data. You can access it via C<< $cell->{Formula} >>. Note that the
restriction still holds that formula cell values aren't available unless they
were explicitly provided when the spreadsheet was written.

=back

=head1 BUGS

=over 4

=item Large spreadsheets may cause segfaults on perl 5.14 and earlier

This module internally uses XML::Twig, which makes it potentially subject to
L<Bug #71636 for XML-Twig: Segfault with medium-sized document|https://rt.cpan.org/Public/Bug/Display.html?id=71636>
on perl versions 5.14 and below (the underlying bug with perl weak references
was fixed in perl 5.15.5). The larger and more complex the spreadsheet, the
more likely to be affected, but the actual size at which it segfaults is
platform dependent. On a 64-bit perl with 7.6gb memory, it was seen on
spreadsheets about 300mb and above. You can work around this adding
C<XML::Twig::_set_weakrefs(0)> to your code before parsing the spreadsheet,
although this may have other consequences such as memory leaks.

=item Worksheets without the C<dimension> tag are not supported

=item Intra-cell formatting is discarded

=item Shared formulas are not supported

Shared formula support will require an actual formula parser and quite a bit of
custom logic, since the only thing stored in the document is the formula for
the base cell - updating the cell references in the formulas in the rest of the
cells is handled by the application. Values for these cells are still handled
properly.

=back

In addition, there are still a few areas which are not yet implemented (the
XLSX spec is quite large). If you run into any of those, bug reports are quite
welcome.

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

=head1 SEE ALSO

L<Spreadsheet::ParseExcel>: The equivalent, for XLS files.

L<Spreadsheet::XLSX>: An older, less robust and featureful implementation.

=head1 SUPPORT

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

    perldoc Spreadsheet::ParseXLSX

You can also look for information at:

=over 4

=item * MetaCPAN

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

=item * RT: CPAN's request tracker

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

=item * Github

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

=item * CPAN Ratings

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

=back

=head1 SPONSORS

Parts of this code were paid for by

=over 4

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

=back

=cut

1;