blib/lib/Excel/Table.pm

filter: Statementstmt 90.4% 19 / 21 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.8% 26 / 28 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Excel::Table;
2  
3 =head1 NAME
4  
5 Excel::Table - Table processing class for Excel worksheets.
6  
7 =head1 AUTHOR
8  
9 Copyright (C) 2012-2020 Tom McMeekin E<lt>tmcmeeki@cpan.orgE<gt>
10  
11 =head1 SYNOPSIS
12  
13 use Excel::Table;
14  
15 my $xs = Excel::Table->new('dir' => '/cygdrive/c/Users/self/Desktop');
16  
17 for ($xs->list_workbooks) {
18 print "workbook [$_]\n";
19 }
20  
21 $xs->open('mybook.xls');
22  
23 my $wb1 = $xs->open_re('foo*bar*');
24  
25 for my $worksheet ($wb1->worksheets) {
26 print "worksheet: " . $worksheet->get_name() . "\n";
27 }
28  
29 $xs->null("this is a null value");
30 $xs->force_null(1);
31  
32 $xs->rowid(0);
33  
34 $xs->trim(0);
35  
36 my @data = $xs->extract('Sheet1');
37  
38 for (@data) {
39 printf "rowid [%s] title [%s] max_width [%d] value [%s]\n",
40 $_->[0],
41 $xs->titles->[0],
42 $xs->widths->[0],
43 $data{$_}->[0];
44 }
45  
46 @data = $xs->extract_hash('Sheet1');
47  
48 @data = $xs->select("column1,column2,column3", 'Sheet1');
49  
50 @data = $xs->select_hash("column1,column2,column3", 'Sheet1');
51  
52 printf "columns %d rows %d title_row %d\n",
53 $xs->columns, $xs->rows, $xs->title_row;
54  
55 printf "regexp [%s] pathname [%s] sheet_name [%s]\n",
56 $xs->regexp, $xs->pathname, $xs->sheet_name;
57  
58 printf "colid2title(0) = [%s]\n", $xs->colid2title(0);
59  
60 printf "title2colid('Foo') = %d\n", $xs->title2colid('Foo');
61  
62 =head1 DESCRIPTION
63  
64 "Excel::Table" retrieves worksheets as if they are structured
65 tables in array-format or optionally in hash-format.
66  
67 =over 4
68  
69 =item 1a. OBJ->dir(EXPR)
70  
71 Override the directory location in which to look for workbooks.
72 Defaults to "." (i.e. the current working directory).
73 This location is critical to the B<list_workbooks>, B<open>,
74 and B<open_re> methods.
75  
76 =item 1b. OBJ->list_workbooks
77  
78 Returns an array of workbook files in the directory defined by the
79 B<dir> property.
80  
81 =item 2a. OBJ->open(EXPR)
82  
83 Parses the filename specified by EXPR. The B<dir> property
84 will designate the search path.
85 Once opened, via this method (or B<open_re>) the
86 workbook is available for use by the B<extract> method.
87  
88 =item 2b. OBJ->open_re(EXPR)
89  
90 This will search for a file which has a filename matching the regexp EXPR.
91 A warning will be issued if multiple matches are found, only the first will
92 be opened.
93  
94 =item 3. OBJ->regexp
95  
96 Returns the regexp used to search for the workbook on the filesystem.
97  
98 =item 4. OBJ->pathname
99  
100 Returns the pathname of the opened workbook.
101  
102 =item 5a. OBJ->extract(EXPR,[TITLE_ROW])
103  
104 This will extract all data from the worksheet named EXPR. Data is extracted
105 into an array and returned. Format of data is per below:
106  
107 [ value1, value2, value3, ... ],
108 [ value1, value2, value3, ... ],
109 [ value1, value2, value3, ... ],
110 ...
111  
112 The object OBJ will be populated with various properties to assist you to
113 access the data in the array, including column titles and widths.
114  
115 A worksheet object is temporarily created in order to populate the array.
116 Once a worksheet is extracted, the associated worksheet object is destroyed.
117 This routine can be called again on any worksheet in the workbook.
118  
119 If the TITLE_ROW argument is specified, then the B<title_row> property will
120 also be updated prior to extraction.
121  
122 =item 5b. OBJ->extract_hash(EXPR,[TITLE_ROW])
123  
124 Per the B<extract> method, but returns an array of hashes, with the hash
125 keys corresponding to the titles.
126  
127 =item 5c. OBJ->select(CLAUSE,EXPR,[TITLE_ROW])
128  
129 Similar to the B<extract> method, this will extract all rows from the worksheet EXPR, constraining the columns to those specified by the B<clause> argument,
130 which is a comma-separated string, e.g. "column1,column2,column3".
131  
132 As with the B<extract> method, the B<titles> and B<widths> properties will
133 be revised.
134  
135 =item 5d. OBJ->select_hash(CLAUSE,EXPR,[TITLE_ROW])
136  
137 Per the B<select> method, but returns an array of hashes.
138  
139 =item 6. OBJ->columns or OBJ->rows
140  
141 Returns the number of columns or rows available in the sheet extracted via the
142 B<extract> method.
143  
144 =item 7a. OBJ->force_null
145  
146 Flag which determines if whitespace fields should be
147 replaced by specific text (see OBJ->null).
148  
149 =item 7b. OBJ->null
150  
151 String to replace whitespace fields with. Defaults to "(null)".
152  
153 =item 8. OBJ->rowid
154  
155 Flag which determines whether a pseudo-column "rowid" is included in each
156 tuple. The value will take the form "999999999" Defaults to FALSE.
157  
158 =item 9. OBJ->sheet_name
159  
160 Returns the sheet_name against which data was extracted via B<extract>.
161  
162 =item 10. OBJ->trim
163  
164 Flag which determines if trailing whitespace fields should be trimmed.
165  
166 =item 11a. OBJ->title_row
167  
168 Returns the title row of the worksheet (defaults to zero), following extract.
169  
170 =item 11b. OBJ->titles
171  
172 Returns an array of title fields, the title row number having been defined
173 as OBJ->title_row.
174  
175 =item 11c. OBJ->colid2title(colid)
176  
177 Converts the column number (colid) to a string column title (i.e.
178 the offset within the title_row array).
179 If no match, then returns undef.
180  
181 =item 11d. OBJ->title2colid(REGEXP)
182  
183 Returns the column number of the title identified by REGEXP.
184 If no match, then returns undef.
185  
186 =item 12. OBJ->widths
187  
188 Returns an array of maximum lengths of any (non-title) data in each column.
189  
190 =back
191  
192 =cut
193  
194 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
195  
196 # --- includes ---
197 9 ▶use Carp qw(cluck confess); # only use stack backtrace within class
Subroutine BEGIN: called CC=1 SCAR=0.0
198 9 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
199 9 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
200 9 ▶use Log::Log4perl qw/ get_logger /;
Subroutine BEGIN: called CC=1 SCAR=0.0
201 9 ▶use Spreadsheet::ParseExcel 0.57;
Subroutine BEGIN: called CC=1 SCAR=0.0
202 0 ▶use Spreadsheet::ParseXLSX 0.27; # rt.cpan.org #133420
Subroutine BEGIN: called CC=1 SCAR=2.6
203  
204  
205 # --- package constants ---
206 use constant S_RID => "rowid";
207 use constant S_NULL => "(null)";
208 use constant EXT_EXCEL => qw/
209 \.xls \.xla \.xlb \.xlc \.xld \.xlk \.xll \.xlm \.xlt
210 \.xlv \.xlw \.xls \.xlt
211 /; # known extensions for EXCEL file
212  
213 # need the Spreadsheet::ParseXLSX module for the following:
214 use constant EXT_EXCEL_2007 => qw/
215 \.xlsx \.xlsm \.xlsb \.xltm \.xlam
216 /; # known extensions for EXCEL 2007 file
217  
218  
219 # --- package globals ---
220 our $AUTOLOAD;
221 our $VERSION = "1.023"; # update this on new release
222  
223  
224 # --- package locals ---
225 my $n_Objects = 0; # counter of objects created.
226  
227 my %attribute = (
228 _n_objects => \$n_Objects,
229 _xl_vers => undef,
230 columns => undef,
231 dir => ".",
232 _log => get_logger("Excel::Table"),
233 null => S_NULL,
234 pathname => undef,
235 regexp => undef,
236 force_null => 0,
237 rows => undef,
238 rowid => 0,
239 sheet_name => undef,
240 title_row => 0, # if title row is zero, first data row is 1
241 titles => undef,
242 trim => 0,
243 widths => undef,
244 workbook => undef,
245 );
246  
247  
248 #INIT { };
249  
250  
251 sub AUTOLOAD {
252 my $self = shift;
253 my $type = ref($self) or croak("self is not an object");
254  
255 my $name = $AUTOLOAD;
256 $name =~ s/.*://; # strip fully−qualified portion
257  
258 unless (exists $self->{_permitted}->{$name} ) {
259 confess "no attribute [$name] in class [$type]";
260 }
261  
262 if (@_) {
263 return $self->{$name} = shift;
264 } else {
265 return $self->{$name};
266 }
267 }
268  
269  
270 sub new {
271 my ($class) = shift;
272 #my $self = $class->SUPER::new(@_);
273 my $self = { _permitted => \%attribute, %attribute };
274  
275 ++ ${ $self->{_n_objects} };
276  
277 bless ($self, $class);
278  
279 my %args = @_; # start processing any parameters passed
280 my ($method,$value); # start processing any parameters passed
281 while (($method, $value) = each %args) {
282  
283 confess "SYNTAX new(method => value, ...) value not specified"
284 unless (defined $value);
285  
286 $self->_log->debug("method [self->$method($value)]");
287  
288 $self->$method($value);
289 }
290
291 return $self;
292 }
293  
294  
295 sub _determine_xl_vers {
296 my ($self,$pn)=@_;
297 $self->_log->logcroak("SYNTAX: _determine_xl_vers(path)")
298 unless defined ($pn);
299 # return version string or undef for given pathname
300 my $extension;
301 my @extensions;
302 my $retval = undef;
303  
304 $self->_log->debug("pn [$pn]");
305  
306 @extensions = EXT_EXCEL;
307 (undef,undef,$extension) = fileparse($pn,@extensions);
308 #$self->_log->debug(sprintf " extension [%s] \@extensions [%s]", $extension, Dumper(\@extensions));
309  
310 $retval = 'xl2003' if ($extension ne "");
311  
312 @extensions = EXT_EXCEL_2007;
313 (undef,undef,$extension) = fileparse($pn,@extensions);
314  
315 $retval = 'xl2007' if ($extension ne "");
316  
317 if (defined $retval) {
318 $self->_log->debug("pn [$pn] returning [$retval]");
319 }
320  
321 return $retval;
322 }
323  
324  
325 sub list_workbooks {
326 my $self = shift;
327  
328 my $dn = $self->dir;
329 my ($dh,$fn);
330 my @workbooks;
331  
332 $self->_log->debug("dn [$dn]");
333  
334 opendir($dh, $dn) || $self->_log->logcroak("opendir($dn)");
335  
336 while ($fn = readdir($dh)) {
337 my $pn = File::Spec->catfile($dn, $fn);
338  
339 # need to remember just the filename here, not the path because
340 # open will use the self->dir property to make the path
341 push @workbooks, $fn
342 if (defined($self->_determine_xl_vers($pn)));
343 }
344  
345 closedir $dh;
346  
347 $self->_log->debug(sprintf '@workbooks [%s]', Dumper(\@workbooks));
348  
349 return @workbooks;
350 }
351  
352  
353 sub open {
354 my ($self,$fn)=@_;
355 $self->_log->logcroak("SYNTAX: open(file)") unless defined ($fn);
356 my $pn = File::Spec->catfile($self->dir, $fn);
357  
358 # to look for the file in the cwd, is not good behaviour,
359 # so dir must be explicit, thus the default to "."
360  
361 if (-f $pn) {
362 $self->pathname($pn);
363 } else {
364 $self->_log->logcroak("no such path [$pn]");
365 }
366  
367 $self->_log->debug("parsing [$pn]");
368  
369 $self->{'_xl_vers'} = $self->_determine_xl_vers($pn);
370  
371 my $parser;
372  
373 if ($self->_xl_vers eq 'xl2007') {
374 $parser = Spreadsheet::ParseXLSX->new;
375 $self->workbook($parser->parse($pn));
376  
377 } else {
378 $parser = Spreadsheet::ParseExcel->new();
379 $self->workbook($parser->Parse($pn));
380  
381 $self->_log->logcroak("Parse() failed, error: " . $self->workbook->error())
382 unless defined $self->workbook;
383 }
384 $self->_log->logcroak("parsing failed for [$pn]")
385 unless defined $self->workbook;
386  
387  
388 return $self->workbook;
389 }
390  
391  
392 sub open_re {
393 my $self = shift;
394 if (@_) { $self->regexp(shift); } else { $self->_log->logcroak("SYNTAX: open_re(regexp)"); }
395 my $re = $self->regexp;
396 my $matches = 0;
397 my $wb = undef;
398  
399 $self->_log->debug(sprintf "regexp [%s]", $self->regexp);
400 for ( $self->list_workbooks ) {
401 $self->_log->debug(" file [$_]");
402 if ($_ =~ /$re/) {
403 $self->_log->debug(" FOUND [$_]");
404 $wb = $_ unless ($matches++); # remember first occurence
405 }
406 }
407  
408 unless (defined $wb) {
409 $self->_log->logcarp("could not find file matching [$re]");
410 return undef;
411 }
412  
413 $self->_log->logwarn("non-unique match on [$re]")
414 if ($matches > 1);
415  
416 return $self->open($wb);
417 }
418  
419  
420 sub _prepend_rowid {
421 my ($self, $ra_columns, $id)=@_;
422  
423 my $rowid = ($id == $self->title_row) ? S_RID : sprintf "%09d", $id;
424  
425 push @$ra_columns, $rowid;
426  
427 return $rowid;
428 }
429  
430  
431 sub extract {
432 my $self = shift;
433 if (@_) { $self->sheet_name(shift); }
434 if (@_) { $self->title_row(shift); }
435  
436 $self->_log->logcroak("SYNTAX: extract(sheet_name,title_row)")
437 unless (defined $self->sheet_name && defined $self->title_row);
438  
439 $self->_log->debug(sprintf "opening [%s]", $self->sheet_name);
440  
441 my $ws = $self->workbook->worksheet($self->sheet_name);
442  
443 my ($minr, $maxr) = $ws->row_range();
444 my ($minc, $maxc) = $ws->col_range();
445  
446 $self->rows($maxr);
447 $self->columns($maxc + 1);
448  
449 $self->title_row($minr) # fix minimum row
450 if ($self->title_row < $minr);
451  
452 $self->_log->debug(sprintf "sheet_name [%s] minr [%d] maxr [%d] minc [%d] maxc [%d]",
453 $self->sheet_name, $minr, $maxr, $minc, $maxc);
454  
455 my ($subr,$subc,$value);
456 my @data;
457 my (@columns,@widths);
458  
459 for ($subr = $self->title_row; $subr <= $maxr; $subr++) {
460  
461 $self->_prepend_rowid(\@columns, $subr)
462 if ($self->rowid);
463  
464 for ($subc = $minc; $subc <= $maxc; $subc++) {
465  
466 my $cell = $ws->get_cell($subr, $subc);
467  
468 if (defined $cell) {
469 $value = ($self->trim) ? $self->_trim_whitespace($cell->value) : $cell->value;
470 } else {
471 $value = undef;
472 }
473  
474 $value = $self->_resolve_null($value, $self->null)
475 if ($self->force_null);
476  
477 push @columns, $value;
478 }
479  
480 # adjust widths, including rowid column
481 $subc = 0;
482 for $value (@columns) {
483  
484 # calculate width, ignoring title_row
485  
486 if ($subr == $self->title_row) {
487 $widths[$subc] = 0;
488 } else {
489 $widths[$subc] = length($value)
490 if (defined($value) &&
491 length($value) > $widths[$subc]);
492 }
493  
494 $subc++;
495 }
496  
497 $self->_log->debug(sprintf '@columns [%s]', Dumper(\@columns));
498 $self->_log->debug(sprintf '@widths [%s]', Dumper(\@widths));
499
500 if ($subr == $self->title_row) {
501 $self->titles([ @columns ]);
502 } else {
503 push @data, [ @columns ];
504 }
505 @columns = ();
506 }
507 $self->widths([ @widths ]);
508  
509 @widths = $ws = ();
510  
511 return @data;
512 }
513  
514  
515 sub colid2title {
516 my ($self,$colid)=@_;
517  
518 $self->_log->logcroak("SYNTAX: colid2title2(colid)")
519 unless (defined $colid);
520  
521 $self->_log->debug("colid [$colid]");
522  
523 return undef
524 if ($colid < 0);
525  
526 return undef
527 unless ($colid < scalar @{ $self->titles });
528  
529 return $self->titles->[$colid];
530 }
531  
532  
533 sub title2colid {
534 my ($self,$title)=@_;
535  
536 $self->_log->logcroak("SYNTAX: title2colid(title)")
537 unless (defined $title);
538  
539 $self->_log->debug("title [$title] ");
540  
541 my $tmax = scalar @{ $self->titles };
542  
543 for (my $tsub = 0; $tsub < $tmax; $tsub++) {
544 if ($self->titles->[$tsub] =~ /$title/) {
545 $self->_log->debug("match at colid $tsub");
546 return $tsub;
547 }
548 }
549 $self->_log->debug("NO MATCH");
550  
551 return undef;
552 }
553  
554  
555 sub _trim_whitespace {
556 my ($self,$s_value)=@_;
557  
558 if (defined $s_value) {
559 $self->_log->debug("s_value [$s_value]");
560  
561 $s_value =~ s/^[[:cntrl:][:space:]]+//; # trim leading
562 $s_value =~ s/[[:cntrl:][:space:]]+$//; # trim trailing
563  
564 $self->_log->debug("after s_value [$s_value]");
565 }
566  
567 return $s_value;
568 }
569  
570  
571 sub _resolve_null {
572 my ($self, $s_value, $s_null)=@_;
573  
574 $self->_log->debug(sprintf "s_value [%s] s_null [%s]",
575 (defined $s_value) ? $s_value : "not defined",
576 (defined $s_null) ? $s_null : "not defined",
577 );
578  
579 if (defined $s_value) {
580 $s_value = $s_null
581 if ($s_value eq "");
582 } else {
583 $s_value = $s_null;
584 }
585  
586 return $s_value;
587 }
588  
589  
590 sub _array_to_hash {
591 my $self = shift;
592 my @data;
593  
594 for my $row (@_) {
595 $self->_log->debug(sprintf '$row [%s]', Dumper($row));
596  
597 my %data;
598 my $unique = 0;
599 my $m_value = scalar(@$row);
600  
601 for (my $ss_value = 0; $ss_value < $m_value; $ss_value++) {
602  
603 my $column = $self->titles->[$ss_value];
604 my $value = $row->[$ss_value];
605  
606 my $key = (exists $data{$column}) ? $column . $unique++ : $column;
607 $data{$key} = $value;
608 }
609  
610 $self->_log->debug(sprintf 'data [%s]', Dumper(\%data));
611  
612 push @data, { %data };
613  
614 %data = ();
615 }
616  
617 return @data;
618 }
619  
620  
621 sub extract_hash {
622 my $self = shift;
623  
624 $self->_log->logcroak("SYNTAX: extract_hash(sheet_name,[title_row])")
625 unless (@_ > 0);
626  
627 return $self->_array_to_hash($self->extract(@_));
628 }
629  
630  
631 sub select_hash {
632 my $self = shift;
633 my $clause = shift;
634  
635 $self->_log->logcroak("SYNTAX: select_hash(clause,[sheet_name,title_row])")
636 unless (@_ > 0);
637  
638 return $self->_array_to_hash($self->select($clause, @_));
639 }
640  
641  
642 sub select {
643 my $self = shift;
644 my $clause = shift;
645  
646 $self->_log->logcroak("SYNTAX: select(clause,[sheet_name,title_row])")
647 unless (defined $clause);
648  
649 my @pre = $self->extract(@_);
650 my (@post, @id);
651 my (@columns, @widths);
652  
653 $clause = join(',', S_RID, $clause)
654 if ($self->rowid);
655  
656 for my $column (split(/,/, $clause)) {
657 $self->_log->debug("column [$column]");
658  
659 my $id = $self->title2colid($column);
660  
661 if (defined $id) {
662 push @id, $id;
663 push @columns, $column;
664 push @widths, $self->widths->[$id];
665 } else {
666 $self->_log->logwarn("invalid column [$column]");
667 }
668 }
669  
670 $self->_log->debug(sprintf '@id [%s]', Dumper(\@id));
671  
672 my $f_no_columns = ($self->rowid) ? 1 : 0;
673  
674 unless (scalar(@columns) == $f_no_columns) { # no columns, thus no rows
675 for my $row (@pre) {
676 $self->_log->debug(sprintf 'row [%s]', Dumper($row));
677  
678 my @wanted = ();
679  
680 for my $id (@id) {
681 push @wanted, $row->[$id];
682 }
683  
684 $self->_log->debug(sprintf '@wanted [%s]', Dumper(\@wanted));
685  
686 push @post, [ @wanted ]
687 if (scalar(@wanted)); # account for null case
688 }
689 }
690  
691 $self->_log->debug(sprintf '@columns [%s]', Dumper(\@columns));
692 $self->_log->debug(sprintf '@widths [%s]', Dumper(\@widths));
693  
694 $self->titles([ @columns ]);
695 $self->widths([ @widths ]);
696  
697 return @post;
698 }
699  
700  
701 DESTROY {
702 my $self = shift;
703 -- ${ $self->{_n_objects} };
704 };
705  
706 #END { }
707  
708 1;
709  
710 __END__
↑ Summary