| 1 | package Spreadsheet::Wright::JSON; | ||
| 2 | |||
| 3 | use 5.010; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | no warnings qw( uninitialized numeric ); | ||
| 7 | |||
| 8 | BEGIN { | ||
| 9 | $Spreadsheet::Wright::JSON::VERSION = '0.107'; | ||
| 10 | $Spreadsheet::Wright::JSON::AUTHORITY = 'cpan:TOBYINK'; | ||
| 11 | } | ||
| 12 | |||
| 13 | use Carp; | ||
| 14 | use JSON; | ||
| 15 | |||
| 16 | use parent qw(Spreadsheet::Wright); | ||
| 17 | |||
| 18 | sub new | ||
| 19 | { | ||
| 20 | my ($class, %args) = @_; | ||
| 21 | my $self = bless { 'options' => \%args }, $class; | ||
| 22 | $self->{'_FILENAME'} = $args{'file'} // $args{'filename'} | ||
| 23 | or croak "Need filename."; | ||
| 24 | $self->{'_WORKSHEET'} = $args{'sheet'} // 'Sheet1'; | ||
| 25 | return $self; | ||
| 26 | } | ||
| 27 | |||
| 28 | sub addsheet | ||
| 29 | { | ||
| 30 | my ($self, $caption) = @_; | ||
| 31 | $caption //= 'Sheet' . (1 + scalar keys %{$self->{'data'}}); | ||
| 32 | |||
| 33 | if (defined $self->{'data'}->{$caption}) | ||
| 34 | { | ||
| 35 | my $i = 2; | ||
| 36 | my $base = $caption; | ||
| 37 | |||
| 38 | ALTERNATIVE: while (1) | ||
| 39 | { | ||
| 40 | $caption = "$base ($i)"; | ||
| 41 | last ALTERNATIVE unless defined $self->{'data'}->{$caption}; | ||
| 42 | $i++; | ||
| 43 | } | ||
| 44 | } | ||
| 45 | |||
| 46 | $self->{'_WORKSHEET'} = $caption; | ||
| 47 | return $self; | ||
| 48 | } | ||
| 49 | |||
| 50 | sub _add_prepared_row | ||
| 51 | { | ||
| 52 | my $self = shift; | ||
| 53 | |||
| 54 | my @texts; | ||
| 55 | foreach my $cell (@_) | ||
| 56 | { | ||
| 57 | my $content = $cell->{'content'}; | ||
| 58 | $content = sprintf($content, $cell->{'sprintf'}) | ||
| 59 | if $cell->{'sprintf'}; | ||
| 60 | push @texts, $content; | ||
| 61 | } | ||
| 62 | push @{ $self->{'data'}->{$self->{'_WORKSHEET'}} }, [@texts]; | ||
| 63 | |||
| 64 | return $self; | ||
| 65 | } | ||
| 66 | |||
| 67 | sub close | ||
| 68 | { | ||
| 69 | my $self=shift; | ||
| 70 | return if $self->{'_CLOSED'}; | ||
| 71 | |||
| 72 | if (1 == scalar keys %{$self->{'data'}}) | ||
| 73 | { | ||
| 74 | $self->{'_FH'}->print( | ||
| 75 | to_json($self->{'data'}->{$self->{'_WORKSHEET'}}, $self->{'json_options'}) | ||
| 76 | ); | ||
| 77 | } | ||
| 78 | else | ||
| 79 | { | ||
| 80 | $self->{'_FH'}->print( | ||
| 81 | to_json($self->{'data'}, $self->{'json_options'}) | ||
| 82 | ); | ||
| 83 | } | ||
| 84 | |||
| 85 | $self->{'_FH'}->close if $self->{'_FH'}; | ||
| 86 | $self->{'_CLOSED'}=1; | ||
| 87 | return $self; | ||
| 88 | } | ||
| 89 | |||
| 90 | 1; |