blib/lib/Catalyst/Action/Serialize/SimpleExcel.pm

filter: Statementstmt 96.5% 83 / 86 Branchbran 73.5% 25 / 34 Conditioncond 60.0% 3 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 100% 11 / 11 Podpod 100% 1 / 1 totaltotal 87.8% 123 / 140 CC 25 SCAR 22.3
CC
25
Cov
89%
_parse_entity
15.5
_add_sheet
10.0
execute
4.0
CRAP 9.3
↑ Summary
1 package Catalyst::Action::Serialize::SimpleExcel;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use parent 'Catalyst::Action';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Spreadsheet::WriteExcel ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Catalyst::Exception ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =head1 NAME
12  
13 Catalyst::Action::Serialize::SimpleExcel - Serialize to Excel files
14  
15 =cut
16  
17 2 our $VERSION = '0.015';
18  
19 =head1 SYNOPSIS
20  
21 Serializes tabular data to an Excel file. Not terribly configurable, but should
22 suffice for simple purposes.
23  
24 In your REST Controller:
25  
26 package MyApp::Controller::REST;
27  
28 use parent 'Catalyst::Controller::REST';
29 use DBIx::Class::ResultClass::HashRefInflator ();
30 use POSIX 'strftime';
31  
32 __PACKAGE__->config->{map}{'application/vnd.ms-excel'} = 'SimpleExcel';
33  
34 sub books : Local ActionClass('REST') {}
35  
36 sub books_GET {
37 my ($self, $c) = @_;
38  
39 my $books_rs = $c->model('MyDB::Book')->search({}, {
40 order_by => 'author,title'
41 });
42  
43 $books_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
44  
45 my @books = map {
46 [ @{$_}{qw/author title/} ]
47 } $books_rs->all;
48  
49 my $authors_rs = $c->model('MyDB::Author')->search({}, {
50 order_by => 'last_name,middle_name,last_name'
51 });
52  
53 $authors_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
54  
55 my @authors = map {
56 [ @{$_}{qw/first_name middle_name last_name/} ]
57 } $authors_rs->all;
58  
59 my $entity = {
60 sheets => [
61 {
62 name => 'Books',
63 header => ['Author', 'Title'], # will be bold
64 rows => \@books,
65 },
66 {
67 name => 'Authors',
68 header => ['First Name', 'Middle Name', 'Last Name'],
69 rows => \@authors,
70 },
71 ],
72 # the part before .xls, which is automatically appended
73 filename => 'myapp-books-'.strftime('%m-%d-%Y', localtime)
74 };
75  
76 $self->status_ok(
77 $c,
78 entity => $entity
79 );
80 }
81  
82 In your javascript, to initiate a file download:
83  
84 // this uses jQuery
85 function export_to_excel() {
86 $('<iframe '
87 +'src="/rest/books?content-type=application%2Fvnd.ms-excel">')
88 .hide().appendTo('body');
89 }
90  
91 Note, the content-type query param is required if you're just linking to the
92 action. It tells L<Catalyst::Controller::REST> what you're serializing the data
93 as.
94  
95 =head1 DESCRIPTION
96  
97 Your entity should be either an array of arrays, an array of arrays of arrays,
98 or a hash with the keys as described below and in the L</SYNOPSIS>.
99  
100 If entity is a hashref, keys should be:
101  
102 =head2 sheets
103  
104 An array of worksheets. Either sheets or a worksheet specification at the top
105 level is required.
106  
107 =head2 filename
108  
109 Optional. The name of the file before .xls. Defaults to "data".
110  
111 Each sheet should be an array of arrays, or a hashref with the following fields:
112  
113 =head2 name
114  
115 Optional. The name of the worksheet.
116  
117 =head2 rows
118  
119 Required. The array of arrays of rows.
120  
121 =head2 header
122  
123 Optional, an array for the first line of the sheet, which will be in bold.
124  
125 =head2 column_widths
126  
127 Optional, the widths in characters of the columns. Otherwise the widths are
128 calculated automatically from the data and header.
129  
130 If you only have one sheet, you can put it in the top level hash.
131  
132 =cut
133  
134 6 ▶sub execute {
Subroutine execute: called CC=4 SCAR=13.9
Pod documented
135 6 my $self = shift;
136 6 my ($controller, $c) = @_;
137  
138 my $stash_key = (
139 $controller->config->{'serialize'} ?
140 $controller->config->{'serialize'}->{'stash_key'} :
141 6 ▶ $controller->config->{'stash_key'}
Branch: 1 branch
BranchTrueFalseTotal
$controller->config->{'serialize'} ? : 0 6 6
Condition50%1/2
($controller->config->{'serialize'} ? $controller->config->{'serialize'}{'stash_key'} : $controller->config->{'stash_key'}) || 'rest'
l!l
60
MC/DC0%0/1
($controller->config->{'serialize'} ? $controller->config->{'serialize'}{'stash_key'} : $controller->config->{'stash_key'}) || 'rest'
($controller->config->{'serialize'} ? $controller->config->{'serialize'}{'stash_key'} : $controller->config->{'stash_key'})
Truth table50%1/2
A
A= ($controller->config->{'serialize'} ? $controller->config->{'serialize'}{'stash_key'} : $controller->config->{'stash_key'})
Aresult
11
00
142 ) || 'rest';
143  
144 6 my $data = $c->stash->{$stash_key};
145  
146 6 open my $fh, '>', \my $buf;
147 6 my $workbook = Spreadsheet::WriteExcel->new($fh);
148  
149 6 my ($filename, $sheets) = $self->_parse_entity($data);
150  
151 6 for my $sheet (@$sheets) {
152 9 $self->_add_sheet($workbook, $sheet);
153 }
154  
155 6 $workbook->close;
156  
157 6 $self->_write_file($c, $filename, $buf);
158  
159 6 return 1;
160 }
161  
162 6 ▶sub _write_file {
Subroutine _write_file: called CC=1 SCAR=0.0
163 6 my ($self, $c, $filename, $data) = @_;
164  
165 6 $c->res->content_type('application/vnd.ms-excel');
166 6 $c->res->header('Content-Disposition' =>
167 "attachment; filename=${filename}.xls");
168 6 $c->res->output($data);
169 }
170  
171 6 ▶sub _parse_entity {
Subroutine _parse_entity: called CC=13 SCAR=27.4
172 6 my ($self, $data) = @_;
173  
174 6 my @sheets;
175 6 my $filename = 'data'; # default
176  
177 6 ▶ if (ref $data eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data eq 'ARRAY') { } 3 3 6
elsif (ref $data eq 'HASH') { } 3 0 3
178 3 ▶ if (not ref $data->[0][0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $data->[0][0]) { } 2 1 3
179 2 $sheets[0] = { rows => $data };
180 }
181 else {
182 @sheets = map
183 ref $_ eq 'HASH' ? $_
184 : ref $_ eq 'ARRAY' ? { rows => $_ }
185 : Catalyst::Exception->throw(
186 1 ▶ 'Unsupported sheet reference type: '.ref($_)), @{ $data };
Branch: 2 branches
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 0 2 2
ref $_ eq 'ARRAY' ? : 2 0 2
187 }
188 }
189 elsif (ref $data eq 'HASH') {
190 3 ▶ $filename = $data->{filename} if $data->{filename};
Branch: 1 branch
BranchTrueFalseTotal
if $data->{"filename"} 3 0 3
191  
192 3 my $sheets = $data->{sheets};
193 3 my $rows = $data->{rows};
194  
195 3 ▶ if ($sheets && $rows) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sheets and $rows) 0 3 3
Condition66%2/3
$sheets and $rows
!ll&&!rl&&r
210
MC/DC0%0/2
$sheets and $rows
$sheets $rows
Truth table66%2/3
A and B
A= $sheetsB= $rows
ABresult
0X0
100
111
196 0 Catalyst::Exception->throw('Use either sheets or rows, not both.');
197 }
198  
199 3 ▶ if ($sheets) {
Branch: 2 branches
BranchTrueFalseTotal
if ($sheets) { } 1 2 3
elsif ($rows) { } 2 0 2
200 @sheets = map
201 ref $_ eq 'HASH' ? $_
202 : ref $_ eq 'ARRAY' ? { rows => $_ }
203 : Catalyst::Exception->throw(
204 1 ▶ 'Unsupported sheet reference type: '.ref($_)), @{ $sheets };
Branch: 2 branches
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 2 1 3
ref $_ eq 'ARRAY' ? : 1 0 1
205 }
206 elsif ($rows) {
207 2 $sheets[0] = $data;
208 }
209 else {
210 0 Catalyst::Exception->throw('Must supply either sheets or rows.');
211 }
212 }
213 else {
214 0 Catalyst::Exception->throw(
215 'Unsupported workbook reference type: '.ref($data)
216 );
217 }
218  
219 6 return ($filename, \@sheets);
220 }
221  
222 9 ▶sub _add_sheet {
Subroutine _add_sheet: called CC=10 SCAR=23.0
223 9 my ($self, $workbook, $sheet) = @_;
224  
225 my $worksheet = $workbook->add_worksheet(
226 $sheet->{name} ? $sheet->{name} : ()
227 9 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$sheet->{'name'} ? : 2 7 9
228  
229 9 $worksheet->keep_leading_zeros(1);
230  
231 9 my ($row, $col) = (0,0);
232  
233 9 my @auto_widths;
234  
235 # Write Header
236 9 ▶ if (exists $sheet->{header}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $sheet->{"header"}) 4 5 9
237 4 my $header_format = $workbook->add_format;
238 4 $header_format->set_bold;
239 4 for my $header (@{ $sheet->{header} }) {
240 8 ▶ $auto_widths[$col] = length $header
Branch: 1 branch
BranchTrueFalseTotal
if $auto_widths[$col] < length $header 8 0 8
241 if $auto_widths[$col] < length $header;
242  
243 8 $worksheet->write($row, $col++, $header, $header_format);
244 }
245 4 $row++;
246 4 $col = 0;
247 }
248  
249 # Write data
250 9 for my $the_row (@{ $sheet->{rows} }) {
251 18 for my $the_col (@$the_row) {
252 44 ▶ $auto_widths[$col] = length $the_col
Branch: 1 branch
BranchTrueFalseTotal
if $auto_widths[$col] < length $the_col 20 24 44
253 if $auto_widths[$col] < length $the_col;
254  
255 44 $worksheet->write($row, $col++, $the_col);
256 }
257 18 $row++;
258 18 $col = 0;
259 }
260  
261 # Set column widths
262 $sheet->{column_widths} = \@auto_widths
263 9 ▶ unless exists $sheet->{column_widths};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $sheet->{"column_widths"} 8 1 9
264  
265 9 for my $width (@{ $sheet->{column_widths} }) {
266 22 $worksheet->set_column($col, $col++, $width);
267 }
268 # Have to set the width of column 0 again, otherwise Excel loses it!
269 # I don't know why...
270 9 $worksheet->set_column(0, 0, $sheet->{column_widths}[0]);
271  
272 9 return $worksheet;
273 }
274  
275 =head1 AUTHOR
276  
277 Rafael Kitover, C<< <rkitover at cpan.org> >>
278  
279 =head1 BUGS
280  
281 Please report any bugs or feature requests to C<bug-catalyst-action-serialize-simpleexcel at rt.cpan.org>, or through
282 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Action-Serialize-SimpleExcel>. I will be notified, and then you'll
283 automatically be notified of progress on your bug as I make changes.
284  
285 =head1 SEE ALSO
286  
287 L<Catalyst>, L<Catalyst::Controller::REST>, L<Catalyst::Action::REST>,
288 L<Catalyst::View::Excel::Template::Plus>, L<Spreadsheet::WriteExcel>,
289 L<Spreadsheet::ParseExcel>
290  
291 =head1 SUPPORT
292  
293 You can find documentation for this module with the perldoc command.
294  
295 perldoc Catalyst::Action::Serialize::SimpleExcel
296  
297 You can also look for information at:
298  
299 =over 4
300  
301 =item * RT: CPAN's request tracker
302  
303 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Action-Serialize-SimpleExcel>
304  
305 =item * AnnoCPAN: Annotated CPAN documentation
306  
307 L<http://annocpan.org/dist/Catalyst-Action-Serialize-SimpleExcel>
308  
309 =item * CPAN Ratings
310  
311 L<http://cpanratings.perl.org/d/Catalyst-Action-Serialize-SimpleExcel>
312  
313 =item * Search CPAN
314  
315 L<http://search.cpan.org/dist/Catalyst-Action-Serialize-SimpleExcel/>
316  
317 =back
318  
319 =head1 COPYRIGHT & LICENSE
320  
321 Copyright (c) 2008-2011 Rafael Kitover
322  
323 This program is free software; you can redistribute it and/or modify it
324 under the same terms as Perl itself.
325  
326 =cut
327  
328 2 1; # End of Catalyst::Action::Serialize::SimpleExcel
↑ Summary