-
Notifications
You must be signed in to change notification settings - Fork 17
/
Read.pm
executable file
·2875 lines (2364 loc) · 87.8 KB
/
Read.pm
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
#!/usr/bin/perl
package Spreadsheet::Read;
=head1 NAME
Spreadsheet::Read - Read the data from a spreadsheet
=head1 SYNOPSIS
use Spreadsheet::Read;
my $book = ReadData ("test.csv", sep => ";");
my $book = ReadData ("test.sxc");
my $book = ReadData ("test.ods");
my $book = ReadData ("test.xls");
my $book = ReadData ("test.xlsx");
my $book = ReadData ("test.xlsm");
my $book = ReadData ("test.gnumeric");
my $book = ReadData ($fh, parser => "xls");
Spreadsheet::Read::add ($book, "sheet.csv");
my $sheet = $book->[1]; # first datasheet
my $cell = $book->[1]{A3}; # content of field A3 of sheet 1
my $cell = $book->[1]{cell}[1][3]; # same, unformatted
# OO API
my $book = Spreadsheet::Read->new ("file.csv");
my $sheet = $book->sheet (1);
my $cell = $sheet->cell ("A3");
my $cell = $sheet->cell (1, 3);
$book->add ("test.xls");
=cut
use 5.008001;
use strict;
use warnings;
our $VERSION = "0.92";
sub Version { $VERSION }
use Carp;
use Exporter;
our @ISA = qw( Exporter );
our @EXPORT = qw( ReadData cell2cr cr2cell );
our @EXPORT_OK = qw( parses rows cellrow row add );
use Encode qw( decode );
use File::Temp qw( );
use Data::Dumper;
my @parsers = (
[ csv => "Text::CSV_XS", "0.71" ],
[ csv => "Text::CSV_PP", "1.17" ],
[ csv => "Text::CSV", "1.17" ],
[ ods => "Spreadsheet::ParseODS", "0.26" ],
[ ods => "Spreadsheet::ReadSXC", "0.26" ],
[ sxc => "Spreadsheet::ParseODS", "0.26" ],
[ sxc => "Spreadsheet::ReadSXC", "0.26" ],
[ sxc => "Spreadsheet::ReadSXC__BAD", "0.26" ], # For testing
[ xls => "Spreadsheet::ParseExcel", "0.34" ],
[ xlsx => "Spreadsheet::ParseXLSX", "0.24" ],
[ xlsm => "Spreadsheet::ParseXLSX", "0.24" ],
[ xlsx => "Spreadsheet::XLSX", "0.13" ],
[ xlsx => "Excel::ValueReader::XLSX", "1.13" ],
# [ prl => "Spreadsheet::Perl", "" ],
[ sc => "Spreadsheet::Read", "0.01" ],
[ gnumeric => "Spreadsheet::ReadGnumeric", "0.2" ],
[ zzz1 => "Z10::Just::For::Testing", "1.23" ],
[ zzz2 => "Z20::Just::For::Testing", "" ],
[ zzz3 => "Z30::Just::For::Testing", "1.00" ],
# Helper modules
[ ios => "IO::Scalar", "" ],
[ dmp => "Data::Peek", "" ],
);
my %can = ( supports => { map { $_->[1] => $_->[2] } @parsers });
foreach my $p (@parsers) {
my $format = $p->[0];
$can{$format} and next;
$can{$format} = "";
my $preset = $ENV{"SPREADSHEET_READ_\U$format"} or next;
my $min_version = $can{supports}{$preset};
unless ($min_version) {
# Catch weirdness like $SPREADSHEET_READ_XLSX = "DBD::Oracle"
$can{$format} = "!$preset is not supported for the $format format";
next;
}
if (eval "local \$_; require $preset" and not $@) {
# forcing a parser should still check the version
my $ok;
my $has = $preset->VERSION;
$has =~ s/_[0-9]+$//; # Remove beta-part
if ($min_version =~ m/^v([0-9.]+)/) { # clumsy versions
my @min = split m/\./ => $1;
$has =~ s/^v//;
my @has = split m/\./ => $has;
$ok = (($has[0] * 1000 + $has[1]) * 1000 + $has[2]) >=
(($min[0] * 1000 + $min[1]) * 1000 + $min[2]);
}
else { # normal versions
$ok = $has >= $min_version;
}
$ok or $preset = "!$preset";
}
else {
$preset = "!$preset";
}
$can{$format} = $preset;
}
delete $can{supports};
foreach my $p (@parsers) {
my ($flag, $mod, $vsn) = @$p;
$can{$flag} and next;
eval "require $mod; \$vsn and ${mod}->VERSION (\$vsn); \$can{\$flag} = '$mod'" and next;
$p->[0] = "! Cannot use $mod version $vsn: $@";
$can{$flag} = $@ =~ m/need to install|can(?:not|'t) locate/i
? 0 # Not found
: ""; # Too old
}
$can{sc} = __PACKAGE__; # SquirrelCalc is built-in
# Define ->get_active_sheet if not defined (yet)
sub _def_gas {
for ([ 0.61, $Spreadsheet::ParseExcel::VERSION, *Spreadsheet::ParseExcel::Workbook::get_active_sheet ],
[ 0.25, $Spreadsheet::ParseODS::VERSION, *Spreadsheet::ParseODS::Workbook::get_active_sheet ],
[ 9.99, $Excel::ValueReader::XLSX::VERSION, *Excel::ValueReader::XLSX::get_active_sheet ],
) {
my ($mv, $v, $cb) = @$_;
defined $v && $v < $mv or next;
defined $cb && defined *{$cb}{CODE} and next;
*{$cb} = sub { undef };
}
} # _def_gas
my $debug = 0;
my %def_opts = (
rc => 1,
cells => 1,
attr => 0,
clip => undef, # $opt{cells};
strip => 0,
pivot => 0,
dtfmt => "yyyy-mm-dd", # Format 14
debug => 0,
passwd => undef,
parser => undef,
sep => undef,
quote => undef,
label => undef,
merge => 0,
);
my @def_attr = (
type => "text",
fgcolor => undef,
bgcolor => undef,
font => undef,
size => undef,
format => undef,
halign => "left",
valign => "top",
bold => 0,
italic => 0,
uline => 0,
wrap => 0,
merged => 0,
hidden => 0,
locked => 0,
enc => "utf-8", # $ENV{LC_ALL} // $ENV{LANG} // ...
formula => undef,
);
# Helper functions
sub _dump {
my ($label, $ref) = @_;
if ($can{dmp}) {
print STDERR Data::Peek::DDumper ({ $label => $ref });
}
else {
print STDERR Data::Dumper->Dump ([$ref], [$label]);
}
my @c = caller (1);
print STDERR "<<- $c[1]:$c[2]|$c[3]\n";
} # _dump
sub _parser {
my $type = shift or return "";
if ($type =~ m/::/ and my @p = grep { $_->[1] eq $type } @parsers) {
my $format = $p[0][0];
$ENV{"SPREADSHEET_READ_\U$format"} = $type;
eval "local \$_; require $type";
$@ and croak ("Forced backend $type for $format fails to load:\n$@");
$can{$format} = $type;
$type = $format;
}
$type = lc $type;
my $ods = $can{ods} ? "ods" : "sxc";
# Aliases and fullnames
$type eq "excel" and return "xls";
$type eq "excel2007" and return "xlsx";
$type eq "xlsm" and return "xlsx";
$type eq "oo" and return $ods;
# $type eq "sxc" and return $ods;
$type eq "openoffice" and return $ods;
$type eq "libreoffice" and return $ods;
$type eq "perl" and return "prl";
$type eq "scalc" and return "sc";
$type eq "squirrelcalc" and return "sc";
return exists $can{$type} ? $type : "";
} # _parser
sub new {
my $class = shift;
my $r = ReadData (@_);
unless ($r) {
@_ and return; # new with arguments failed to open resource
$r = [{
parsers => [],
error => undef,
sheets => 0,
sheet => { },
}];
}
bless $r => $class;
} # new
sub parsers {
ref $_[0] eq __PACKAGE__ and shift;
my @c;
for (sort { $a->[0] cmp $b->[0] || $a->[1] cmp $b->[1] }
grep { $_->[0] !~ m{^(?:dmp|ios|!.*)$} }
@parsers) {
my ($typ, $mod, $min) = @$_;
eval "local \$_; require $mod";
my $vsn = $@ ? "-" : eval { $mod->VERSION };
push @c => {
ext => $typ,
mod => $mod,
min => $min,
vsn => $vsn,
def => $can{$typ} eq $mod ? "*" : "",
};
}
@c;
} # parsers
# Spreadsheet::Read::parses ("csv") or die "Cannot parse CSV"
sub parses {
ref $_[0] eq __PACKAGE__ and shift;
my $type = shift or
return sort grep { !m/^(?:dmp|ios)/ && $can{$_} !~ m{^!} }
keys %can;
$type = _parser ($type) or return 0;
if ($can{$type} =~ m/^!\s*(.*)/) {
$@ = $1;
return 0;
}
return $can{$type} || 0;
} # parses
sub sheets {
my $ctrl = shift->[0];
wantarray or return $ctrl->{sheets};
my $s = $ctrl->{sheet} or return (); # No labels defined
sort { $s->{$a} <=> $s->{$b} } keys %$s;
} # sheets
# col2label (4) => "D"
sub col2label {
ref $_[0] eq __PACKAGE__ and shift;
my $c = shift;
defined $c && $c > 0 or return "";
my $cell = "";
while ($c) {
use integer;
substr $cell, 0, 0, chr (--$c % 26 + ord "A");
$c /= 26;
}
$cell;
} # col2label
# cr2cell (4, 18) => "D18"
# No prototype to allow 'cr2cell (@rowcol)'
sub cr2cell {
ref $_[0] eq __PACKAGE__ and shift;
my ($c, $r) = @_;
defined $c && defined $r && $c > 0 && $r > 0 or return "";
col2label ($c) . $r;
} # cr2cell
# cell2cr ("D18") => (4, 18)
sub cell2cr {
ref $_[0] eq __PACKAGE__ and shift;
my ($cc, $r) = (uc ($_[0]||"") =~ m/^([A-Z]+)([0-9]+)$/) or return (0, 0);
my $c = 0;
while ($cc =~ s/^([A-Z])//) {
$c = 26 * $c + 1 + ord ($1) - ord ("A");
}
($c, $r);
} # cell2cr
# my @row = cellrow ($book->[1], 1);
# my @row = $book->cellrow (1, 1);
sub cellrow {
my $sheet = ref $_[0] eq __PACKAGE__ ? (shift)->[shift] : shift or return;
ref $sheet eq "HASH" && exists $sheet->{cell} or return;
exists $sheet->{maxcol} && exists $sheet->{maxrow} or return;
my $row = shift or return;
$row > 0 && $row <= $sheet->{maxrow} or return;
my $s = $sheet->{cell};
map { $s->[$_][$row] } 1..$sheet->{maxcol};
} # cellrow
# my @row = row ($book->[1], 1);
# my @row = $book->row (1, 1);
sub row {
my $sheet = ref $_[0] eq __PACKAGE__ ? (shift)->[shift] : shift or return;
ref $sheet eq "HASH" && exists $sheet->{cell} or return;
exists $sheet->{maxcol} && exists $sheet->{maxrow} or return;
my $row = shift or return;
$row > 0 && $row <= $sheet->{maxrow} or return;
map { $sheet->{cr2cell ($_, $row)} } 1..$sheet->{maxcol};
} # row
# Convert {cell}'s [column][row] to a [row][column] list
# my @rows = rows ($book->[1]);
sub rows {
my $sheet = ref $_[0] eq __PACKAGE__ ? (shift)->[shift] : shift or return;
ref $sheet eq "HASH" && exists $sheet->{cell} or return;
exists $sheet->{maxcol} && exists $sheet->{maxrow} or return;
my $s = $sheet->{cell};
map {
my $r = $_;
[ map { $s->[$_][$r] } 1..$sheet->{maxcol} ];
} 1..$sheet->{maxrow};
} # rows
sub sheet {
my ($book, $sheet) = @_;
$book && $sheet or return;
my $class = "Spreadsheet::Read::Sheet";
$sheet =~ m/^[0-9]+$/ && $sheet >= 1 && $sheet <= $book->[0]{sheets} and
return bless $book->[$sheet] => $class;
exists $book->[0]{sheet}{$sheet} and
return bless $book->[$book->[0]{sheet}{$sheet}] => $class;
foreach my $idx (1 .. $book->[0]{sheets}) {
$book->[$idx]{label} eq $sheet and
return bless $book->[$idx] => $class;
}
return;
} # sheet
# If option "clip" is set, remove the trailing rows and
# columns in each sheet that contain no visible data
sub _clipsheets {
my ($opt, $ref) = @_;
unless ($ref->[0]{sheets}) {
$ref->{sheet} ||= {};
return $ref;
}
my ($rc, $cl) = ($opt->{rc}, $opt->{cells});
my ($oc, $os, $oa) = ($opt->{clip}, $opt->{strip}, $opt->{attr});
# Strip leading/trailing spaces
if ($os || $oc) {
foreach my $sheet (1 .. $ref->[0]{sheets}) {
$ref->[$sheet]{indx} = $sheet;
my $ss = $ref->[$sheet];
$ss->{maxrow} && $ss->{maxcol} or next;
my ($mc, $mr) = (0, 0);
foreach my $row (1 .. $ss->{maxrow}) {
foreach my $col (1 .. $ss->{maxcol}) {
if ($rc) {
defined $ss->{cell}[$col][$row] or next;
$os & 2 and $ss->{cell}[$col][$row] =~ s/\s+$//;
$os & 1 and $ss->{cell}[$col][$row] =~ s/^\s+//;
if (length $ss->{cell}[$col][$row]) {
$col > $mc and $mc = $col;
$row > $mr and $mr = $row;
}
}
if ($cl) {
my $cell = cr2cell ($col, $row);
defined $ss->{$cell} or next;
$os & 2 and $ss->{$cell} =~ s/\s+$//;
$os & 1 and $ss->{$cell} =~ s/^\s+//;
if (length $ss->{$cell}) {
$col > $mc and $mc = $col;
$row > $mr and $mr = $row;
}
}
}
}
$oc && ($mc < $ss->{maxcol} || $mr < $ss->{maxrow}) or next;
# Remove trailing empty columns
foreach my $col (($mc + 1) .. $ss->{maxcol}) {
$rc and undef $ss->{cell}[$col];
$oa and undef $ss->{attr}[$col];
$cl or next;
my $c = col2label ($col);
delete $ss->{"$c$_"} for 1 .. $ss->{maxrow};
}
# Remove trailing empty rows
foreach my $row (($mr + 1) .. $ss->{maxrow}) {
foreach my $col (1 .. $mc) {
$cl and delete $ss->{cr2cell ($col, $row)};
$rc and undef $ss->{cell} [$col][$row];
$oa and undef $ss->{attr} [$col][$row];
}
}
($ss->{maxrow}, $ss->{maxcol}) = ($mr, $mc);
}
}
if ($opt->{pivot}) {
foreach my $sheet (1 .. $ref->[0]{sheets}) {
my $ss = $ref->[$sheet];
$ss->{maxrow} || $ss->{maxcol} or next;
my $mx = $ss->{maxrow} > $ss->{maxcol} ? $ss->{maxrow} : $ss->{maxcol};
foreach my $row (2 .. $mx) {
foreach my $col (1 .. ($row - 1)) {
$opt->{rc} and
($ss->{cell}[$col][$row], $ss->{cell}[$row][$col]) =
($ss->{cell}[$row][$col], $ss->{cell}[$col][$row]);
$opt->{cells} and
($ss->{cr2cell ($col, $row)}, $ss->{cr2cell ($row, $col)}) =
($ss->{cr2cell ($row, $col)}, $ss->{cr2cell ($col, $row)});
}
}
($ss->{maxcol}, $ss->{maxrow}) = ($ss->{maxrow}, $ss->{maxcol});
}
}
$ref;
} # _clipsheets
# Convert a single color (index) to a color
sub _xls_color {
my $clr = shift;
defined $clr or return undef;
$clr eq "#000000" and return undef;
$clr =~ m/^#[0-9a-fA-F]+$/ and return lc $clr;
$clr == 0 || $clr == 32767 and return undef; # Default fg color
return "#" . lc Spreadsheet::ParseExcel->ColorIdxToRGB ($clr);
} # _xls_color
# Convert a fill [ $pattern, $front_color, $back_color ] to a single background
sub _xls_fill {
my ($p, $fg, $bg) = @_;
defined $p or return undef;
$p == 32767 and return undef; # Default fg color
$p == 0 && !defined $bg and return undef; # No fill bg color
$p == 1 and return _xls_color ($fg);
$bg < 8 || $bg > 63 and return undef; # see Workbook.pm#106
return _xls_color ($bg);
} # _xls_fill
sub _missing_parser {
my ($type, $suggest) = (shift, "");
foreach my $p (@parsers) {
$p->[0] eq lc $type or next;
$suggest = "\nPlease install $p->[1]";
}
"No parser for $type found$suggest\n";
} # _missing_parser
sub _txt_is_xml {
# Return true if $txt is gzipped or contains XML. If we are also passed
# $ns_uri_of_interest, $txt must contain it in the first 1000 or so
# characters (but we try to search quickly rather than precisely).
my ($txt, $ns_uri_of_interest) = @_;
ref $txt and return; # Can't tell (unless we assume the stream is seekable).
if ($txt =~ m/\A\037\213/) {
# Literal gzipped string (/usr/share/misc/magic). [this is a hack that
# works only because Gnumeric is the only format that uses gzip. --
# rgr, 13-Jan-2023]
return 1;
}
if ($txt =~ m/\A<\?xml/) {
$ns_uri_of_interest or return 1;
$ns_uri_of_interest =~ s/([^\w\d])/\\$1/g;
my $prefix = length ($txt) > 10000 ? substr $txt, 0, 1000 : $txt;
return $prefix =~ m/xmlns:\w+=.$ns_uri_of_interest/;
}
$txt =~ m/\n/ and return; # safeguard for older perl versions
open my $in, "<", $txt or return;
read $in, my $block, 1000 or return;
return _txt_is_xml ($block, $ns_uri_of_interest);
} # _txt_is_xml
sub ReadData {
my $txt = shift or return;
my %opt;
if (@_) {
if (ref $_[0] eq "HASH") { %opt = %{shift @_} }
elsif (@_ % 2 == 0) { %opt = @_ }
}
# Aliasses
exists $opt{transpose} && !exists $opt{pivot} and $opt{pivot} = delete $opt{transpose};
exists $opt{trim} && !exists $opt{strip} and $opt{strip} = delete $opt{trim};
exists $opt{rc} or $opt{rc} = $def_opts{rc};
exists $opt{cells} or $opt{cells} = $def_opts{cells};
exists $opt{attr} or $opt{attr} = $def_opts{attr};
exists $opt{clip} or $opt{clip} = $opt{cells};
exists $opt{strip} or $opt{strip} = $def_opts{strip};
exists $opt{dtfmt} or $opt{dtfmt} = $def_opts{dtfmt};
exists $opt{merge} or $opt{merge} = $def_opts{merge};
# $debug = $opt{debug} || 0;
$debug = defined $opt{debug} ? $opt{debug} : $def_opts{debug};
$debug > 4 and _dump (Options => \%opt);
my %parser_opts = map { $_ => $opt{$_} }
grep { !exists $def_opts{$_} }
keys %opt;
my $_parser = _parser ($opt{parser});
my $io_ref = ref ($txt) =~ m/GLOB|IO/ ? $txt : undef;
my $io_fil = $io_ref ? 0 : $txt =~ m/\0/ ? 0
: do { no warnings "newline"; -f $txt };
my $io_txt = $io_ref || $io_fil ? 0 : 1;
$io_fil && ! -s $txt and do { $@ = "$txt is empty"; return };
$io_ref && eof $txt and do { $@ = "Empty stream"; return };
if ($opt{parser} ? $_parser eq "csv" : ($io_fil && $txt =~ m/\.(csv)$/i)) {
$can{csv} or croak _missing_parser ("CSV");
my $label = defined $opt{label} ? $opt{label} : $io_fil ? $txt : "IO";
$debug and print STDERR "Opening CSV $label using $can{csv}-", $can{csv}->VERSION, "\n";
my @data = (
{ type => "csv",
parser => $can{csv},
version => $can{csv}->VERSION,
parsers => [ {
type => "csv",
parser => $can{csv},
version => $can{csv}->VERSION,
}],
error => undef,
quote => '"',
sepchar => ',',
sheets => 1,
sheet => { $label => 1 },
},
{ parser => 0,
label => $label,
maxrow => 0,
maxcol => 0,
cell => [],
attr => [],
merged => [],
active => 1,
hidden => 0,
},
);
my ($sep, $quo, $in) = (",", '"');
defined $opt{sep} and $sep = $opt{sep};
defined $opt{quote} and $quo = $opt{quote};
$debug > 8 and _dump (debug => {
data => \@data, txt => $txt, io_ref => $io_ref, io_fil => $io_fil });
if ($io_fil) {
unless (defined $opt{quote} && defined $opt{sep}) {
open $in, "<", $txt or return;
my $l1 = <$in>;
$quo = defined $opt{quote} ? $opt{quote} : '"';
$sep = # If explicitly set, use it
defined $opt{sep} ? $opt{sep} :
# otherwise start auto-detect with quoted strings
$l1 =~ m/["0-9];["0-9;]/ ? ";" :
$l1 =~ m/["0-9],["0-9,]/ ? "," :
$l1 =~ m/["0-9]\t["0-9,]/ ? "\t" :
$l1 =~ m/["0-9]\|["0-9,]/ ? "|" :
# If neither, then for unquoted strings
$l1 =~ m/\w;[\w;]/ ? ";" :
$l1 =~ m/\w,[\w,]/ ? "," :
$l1 =~ m/\w\t[\w,]/ ? "\t" :
$l1 =~ m/\w\|[\w,]/ ? "|" :
"," ;
close $in;
}
open $in, "<", $txt or return;
}
elsif ($io_ref) {
$in = $txt;
}
elsif (ref $txt eq "SCALAR") {
open $in, "<", $txt or croak "Cannot open input: $!";
}
elsif ($txt =~ m/[\r\n,;]/) {
open $in, "<", \$txt or croak "Cannot open input: $!";
}
else {
warn "Input type ", ref $txt,
" might not be supported. Please file a ticket\n";
$in = $txt; # Now pray ...
}
$debug > 1 and print STDERR "CSV sep_char '$sep', quote_char '$quo'\n";
if (!exists $parser_opts{strict_eol} and
my $ka = $data[0]{parser}->can ("known_attributes")) {
grep m/^strict_eol$/ => $ka->() and $parser_opts{strict_eol} = 1;
}
my $csv = $can{csv}->new ({
%parser_opts,
sep_char => ($data[0]{sepchar} = $sep),
quote_char => ($data[0]{quote} = $quo),
keep_meta_info => 1,
binary => 1,
auto_diag => 1,
}) or croak "Cannot create a csv ('$sep', '$quo') parser!";
while (my $row = $csv->getline ($in)) {
my @row = @$row or last;
my $r = ++$data[1]{maxrow};
@row > $data[1]{maxcol} and $data[1]{maxcol} = @row;
foreach my $c (0 .. $#row) {
my $val = $row[$c];
my $cell = cr2cell ($c + 1, $r);
$opt{rc} and $data[1]{cell}[$c + 1][$r] = $val;
$opt{cells} and $data[1]{$cell} = $val;
$opt{attr} and $data[1]{attr}[$c + 1][$r] = { @def_attr };
}
}
$parser_opts{strict_eol} and $data[1]{eolt} = $csv->eol_type;
$csv->eof () or $data[0]{error} = [ $csv->error_diag ];
close $in;
for (@{$data[1]{cell}}) {
defined or $_ = [];
}
return _clipsheets \%opt, [ @data ];
}
if ($io_txt) { # && $_parser !~ m/^xlsx?$/) {
if ( # /etc/magic: Microsoft Office Document
$txt =~ m{\A(\376\067\0\043
|\320\317\021\340\241\261\032\341
|\333\245-\0\0\0)}x
# /usr/share/misc/magic
|| $txt =~ m{\A.{2080}Microsoft Excel 5.0 Worksheet}
|| $txt =~ m{\A\x09\x04\x06\x00\x00\x00\x10\x00}
) {
$can{xls} or croak _missing_parser ("XLS");
my $tmpfile;
if ($can{ios}) { # Do not use a temp file if IO::Scalar is available
$tmpfile = \$txt;
}
else {
$tmpfile = File::Temp->new (SUFFIX => ".xls", UNLINK => 1);
binmode $tmpfile;
print $tmpfile $txt;
close $tmpfile;
}
open $io_ref, "<", $tmpfile or do { $@ = $!; return };
$io_txt = 0;
$_parser = _parser ($opt{parser} = "xls");
}
elsif ( # /usr/share/misc/magic
$txt =~ m{\APK\003\004.{4,30}(?:\[Content_Types\]\.xml|_rels/\.rels)}
) {
$can{xlsx} or croak _missing_parser ("XLSX");
my $tmpfile;
if ($can{ios}) { # Do not use a temp file if IO::Scalar is available
$tmpfile = \$txt;
}
else {
$tmpfile = File::Temp->new (SUFFIX => ".xlsx", UNLINK => 1);
binmode $tmpfile;
print $tmpfile $txt;
close $tmpfile;
}
open $io_ref, "<", $tmpfile or do { $@ = $!; return };
$io_txt = 0;
$_parser = _parser ($opt{parser} = "xlsx");
}
elsif ( # /usr/share/misc/magic
$txt =~ m{\APK\003\004.{9,30}\Qmimetypeapplication/vnd.oasis.opendocument.spreadsheet}
) {
$can{ods} or croak _missing_parser ("ODS");
my $tmpfile;
if ($can{ios}) { # Do not use a temp file if IO::Scalar is available
$tmpfile = \$txt;
}
else {
$tmpfile = File::Temp->new (SUFFIX => ".ods", UNLINK => 1);
binmode $tmpfile;
print $tmpfile $txt;
close $tmpfile;
}
open $io_ref, "<", $tmpfile or do { $@ = $!; return };
$io_txt = 0;
$_parser = _parser ($opt{parser} = "ods");
}
elsif (!$io_ref && $txt =~ m/\.xls[xm]?$/i) {
$@ = "Cannot open $txt as file";
return;
}
}
if ($opt{parser} ? $_parser =~ m/^(?:xlsx?)$/
: ($io_fil && $txt =~ m/\.(xls[xm]?)$/i &&
($_parser = _parser ($1)))) {
my $parse_type = $_parser =~ m/x$/i ? "XLSX" : "XLS";
my $parser = $can{lc $parse_type} or croak _missing_parser ($parse_type);
#$debug and print STDERR __FILE__, "#", __LINE__, " | $_parser | $parser | $parse_type\n";
$debug and print STDERR "Opening $parse_type ", $io_ref ? "<REF>" : $txt,
" using $parser-", $can{lc $parse_type}->VERSION, "\n";
$opt{passwd} and $parser_opts{Password} = $opt{passwd};
my $oBook = eval {
$io_ref
? $parse_type eq "XLSX"
? $can{xlsx} eq "Spreadsheet::XLSX"
? $parser->new ($io_ref) # Spreadsheet::XLXS ($io)
: $can{xlsx} eq "Excel::ValueReader::XLSX"
? $parser->new (xlsx => $io_ref, %parser_opts) # Excel::ValueReader::XLSX ($io / $content)
: $parser->new (%parser_opts)->parse ($io_ref) # Spreadsheet::ParseXLSX ($io)
: $parser->new (%parser_opts)->Parse ($io_ref) # Spreadsheet::ParseExcel ($io)
: $parse_type eq "XLSX"
? $can{xlsx} eq "Spreadsheet::XLSX"
? $parser->new ($txt) # Spreadsheet::XLXS ($file / $content)
: $can{xlsx} eq "Excel::ValueReader::XLSX"
? $parser->new (xlsx => $txt, %parser_opts) # Excel::ValueReader::XLSX ($file / $content)
: $parser->new (%parser_opts)->parse ($txt) # Spreadsheet::ParseXLSX ($file / $content)
: $parser->new (%parser_opts)->Parse ($txt); # Spreadsheet::ParseExcel ($file / $content)
};
unless ($oBook) {
# cleanup will fail on folders with spaces.
(my $msg = $@) =~ s/ at \S+ line \d+.*//s;
croak "$parse_type parser cannot parse data: $msg";
}
$debug > 8 and _dump (oBook => $oBook);
# WorkBook keys:
# aColor _CurSheet Format SheetCount
# ActiveSheet _CurSheet_ FormatStr _skip_chart
# Author File NotSetCell _string_contin
# BIFFVersion Flg1904 Object Version
# _buffer FmtClass PkgStr Worksheet
# CellHandler Font _previous_info
my @data = ( {
type => lc $parse_type,
parser => $can{lc $parse_type},
version => $can{lc $parse_type}->VERSION,
parsers => [{
type => lc $parse_type,
parser => $can{lc $parse_type},
version => $can{lc $parse_type}->VERSION,
}],
error => undef,
sheets => $oBook->{SheetCount} || 0,
sheet => {},
} );
# Overrule the default date format strings
my %def_fmt = (
0x0E => lc $opt{dtfmt}, # m-d-yy
0x0F => "d-mmm-yyyy", # d-mmm-yy
0x11 => "mmm-yyyy", # mmm-yy
0x16 => "yyyy-mm-dd hh:mm", # m-d-yy h:mm
);
$oBook->{FormatStr}{$_} = $def_fmt{$_} for keys %def_fmt;
my $oFmt = eval { $parse_type eq "XLSX"
? $can{xlsx} eq "Spreadsheet::XLSX"
? Spreadsheet::XLSX::Fmt2007->new
: Spreadsheet::ParseExcel::FmtDefault->new
: Spreadsheet::ParseExcel::FmtDefault->new
};
$debug > 20 and _dump ("oBook before conversion", $oBook);
if ($can{xlsx} eq "Excel::ValueReader::XLSX" and !exists $oBook->{SheetCount}) {
my @sheets = $oBook->sheet_names;
$data[0]{sheet} = { map { $sheets[$_] => $_ + 1 } 0 .. $#sheets };
$data[0]{sheets} = scalar @sheets;
foreach my $sheet_name (@sheets) {
my $grid = $oBook->values ($sheet_name);
my $sheet = {
label => $sheet_name,
minrow => 1,
mincol => 1,
indx => 1,
merged => [],
};
# Transpose to column vectors.
# The A1, B5 etc items could be added here as well.
my @c;
foreach my $r (0 .. $#$grid) {
my $row = $grid->[$r];
foreach my $c (0 .. $#$row) {
# add 1 for array base 1
my $val = $grid->[$r][$c];
my $cell = cr2cell ($c + 1, $r + 1);
$opt{rc} and $sheet->{cell}[$c + 1][$r + 1] = $val;
$opt{cells} and $sheet->{$cell} = $val;
$c[$c] = 1;
}
}
# First entry in @t is padding so number of items
# is the max index.
$sheet->{maxcol} = scalar @c;
# No padding of first entry in $grid so
# number of items is the array length.
$sheet->{maxrow} = @$grid;
push @data => $sheet;
}
#use DP;die DDumper { oBook => $oBook, oFmt => $oFmt, data => \@data, parser_type => $parse_type };
}
if ($parse_type eq "ODS" and !exists $oBook->{SheetCount}) {
my $styles = delete $oBook->{_styles};
my $sheets = delete $oBook->{_sheets};
if ($sheets && ref $sheets eq "ARRAY") {
$styles = ($styles || {})->{styles} || {};
$data[0]{sheets} = $oBook->{SheetCount} = scalar @{$sheets};
$oBook->{Worksheet} = [];
*S::R::Sheet::get_merged_areas = sub { [] };
my $x = 0;
foreach my $sh (@{$sheets}) {
push @{$oBook->{Worksheet}} => bless {
Name => $sh->{label},
Cells => [],
MinRow => $sh->{col_min},
MaxRow => $sh->{row_max},
MinCol => $sh->{col_min},
MaxCol => $sh->{row_max},
SheetHidden => $sh->{sheet_hidden} || 0,
RowHidden => $sh->{hidden_rows},
ColHidden => $sh->{hidden_cols},
_SheetNo => $x++,
} => "S::R::Sheet";
# header_cols
# header_rows
# print_areas
# sheet_hidden
# tab_color
*S::R::Cell::Value = sub { $_[0]{Raw} };
*S::R::Cell::is_merged = sub { 0 };
my $r = 0;
foreach my $row (@{$sh->{data}}) {
$#$row > $oBook->{Worksheet}[-1]{MaxCol} and
$oBook->{Worksheet}[-1]{MaxCol} = $#$row;
$oBook->{Worksheet}[-1]{Cells}[$r++] = [ map { bless {
Code => undef,
Format => $_->{format},
Formula => $_->{formula},
Hidden => undef,
Merged => undef,
# use || instead of // for now
# even though it is undesirable
Type => $_->{type} || "",
Val => $_->{value} || $_->{unformatted},
Raw => $_->{unformatted} || $_->{value},
_Style => $styles->{$_->{style} || ""}
|| $_->{style},
# hyperlink
} => "S::R::Cell" } @{$row} ];
}
--$r > $oBook->{Worksheet}[-1]{MaxRow} and
$oBook->{Worksheet}[-1]{MaxRow} = $r;
}
}
}
$debug and print STDERR "\t$data[0]{sheets} sheets\n";
_def_gas ();
my $active_sheet = $oBook->get_active_sheet
|| $oBook->{ActiveSheet}
|| $oBook->{SelectedSheet};
my $current_sheet = 0;
foreach my $oWkS (@{$oBook->{Worksheet}}) {
$debug > 8 and _dump ("oWkS", $oWkS);
$current_sheet++;
$opt{clip} and !defined $oWkS->{Cells} and next; # Skip empty sheets
my %sheet = (
parser => 0,
label => $oWkS->{Name},
maxrow => 0,
maxcol => 0,
cell => [],
attr => [],
merged => [],
active => 0,
hidden => $oWkS->{SheetHidden} || 0,
);
# $debug and $sheet{_parser} = $oWkS;
defined $sheet{label} or $sheet{label} = "-- unlabeled --";
exists $oWkS->{MinRow} and $sheet{minrow} = $oWkS->{MinRow} + 1;
exists $oWkS->{MaxRow} and $sheet{maxrow} = $oWkS->{MaxRow} + 1;
exists $oWkS->{MinCol} and $sheet{mincol} = $oWkS->{MinCol} + 1;
exists $oWkS->{MaxCol} and $sheet{maxcol} = $oWkS->{MaxCol} + 1;
$sheet{merged} = [
map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
map {[ $_, pack "NNNN", @$_ ]}
map {[ map { $_ + 1 } @{$_}[1,0,3,2] ]}
@{$oWkS->get_merged_areas || []}];
my $sheet_idx = 1 + @data;
$debug and print STDERR "\tSheet $sheet_idx '$sheet{label}' $sheet{maxrow} x $sheet{maxcol}\n";
if (defined $active_sheet) {
# _SheetNo is 0-based
my $sheet_no = defined $oWkS->{_SheetNo} ? $oWkS->{_SheetNo} : $current_sheet - 1;
$sheet_no eq $active_sheet and $sheet{active} = 1;
}
# Sheet keys:
# _Book FooterMargin MinCol RightMargin
# BottomMargin FooterMergin MinRow RightMergin
# BottomMergin HCenter Name RowHeight
# Cells Header NoColor RowHidden
# ColFmtNo HeaderMargin NoOrient Scale
# ColHidden HeaderMergin NoPls SheetHidden
# ColWidth Kind Notes _SheetNo
# Copis Landscape PageFit SheetType
# DefColWidth LeftMargin PageStart SheetVersion
# DefRowHeight LeftMergin PaperSize TopMargin
# Draft LeftToRight _Pos TopMergin
# FitHeight MaxCol PrintGrid UsePage
# FitWidth MaxRow PrintHeaders VCenter
# Footer MergedArea Res VRes
if (exists $oWkS->{MinRow}) {
my $hiddenRows = $oWkS->{RowHidden} || [];
my $hiddenCols = $oWkS->{ColHidden} || [];
if ($opt{clip}) {
my ($mr, $mc) = (-1, -1);
foreach my $r ($oWkS->{MinRow} .. $sheet{maxrow}) {
foreach my $c ($oWkS->{MinCol} .. $sheet{maxcol}) {
my $oWkC = $oWkS->{Cells}[$r][$c] or next;
defined (my $val = $oWkC->{Val}) or next;
$val eq "" and next;
$r > $mr and $mr = $r;
$c > $mc and $mc = $c;
}
}
($sheet{maxrow}, $sheet{maxcol}) = ($mr + 1, $mc + 1);
}
foreach my $r ($oWkS->{MinRow} .. $sheet{maxrow}) {
foreach my $c ($oWkS->{MinCol} .. $sheet{maxcol}) {
my $oWkC = $oWkS->{Cells}[$r][$c] or next;
#defined (my $val = $oWkC->{Val}) or next;
my $val = $oWkC->{Val};
if (defined $val and my $enc = $oWkC->{Code}) {
$enc eq "ucs2" and $val = decode ("utf-16be", $val);
}
my $cell = cr2cell ($c + 1, $r + 1);
$opt{rc} and $sheet{cell}[$c + 1][$r + 1] = $val; # Original
my $fmt;
my $FmT = $oWkC->{Format};
if ($FmT) {
unless (ref $FmT) {
$fmt = $FmT;
$FmT = {};
}
}
else {
$FmT = {};
}
foreach my $attr (qw( AlignH AlignV FmtIdx Hidden Lock
Wrap )) {
exists $FmT->{$attr} or $FmT->{$attr} = 0;
}
exists $FmT->{Fill} or $FmT->{Fill} = [ 0 ];
exists $FmT->{Font} or $FmT->{Font} = undef;
unless (defined $fmt) {
$fmt = $FmT->{FmtIdx}
? $oBook->{FormatStr}{$FmT->{FmtIdx}}
: undef;