8323f55de924056e6037fd701b8e7432706a3853
[freeside.git] / httemplate / search / elements / search-xls.html
1 <% $data %>
2 <%init>
3
4 my %args = @_;
5 my $type   = $args{'type'};
6 my $header = $args{'header'};
7 my $rows   = $args{'rows'};
8 my %opt    = %{ $args{'opt'} };    
9
10 #http_header('Content-Type' => 'application/excel' ); #eww
11 #http_header('Content-Type' => 'application/msexcel' ); #alas
12 #http_header('Content-Type' => 'application/x-msexcel' ); #?
13
14 #http://support.microsoft.com/kb/199841
15 http_header('Content-Type' => 'application/vnd.ms-excel' );
16 http_header('Content-Disposition' => 
17   'attachment;filename="'.($opt{'name'} || PL($opt{'name_singular'}) ).'.xls"');
18  
19 #http://support.microsoft.com/kb/812935
20 #http://support.microsoft.com/kb/323308
21 $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
22
23 my $data = '';
24 my $XLS = new IO::Scalar \$data;
25 my $workbook = Spreadsheet::WriteExcel->new($XLS)
26   or die "Error opening .xls file: $!";
27
28 my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
29
30 $worksheet->protect();
31
32 my($r,$c) = (0,0);
33
34 my $header_format = $workbook->add_format(
35   bold     => 1,
36   locked   => 1,
37   bg_color => 55, #22,
38   bottom   => 3,
39 );
40
41 $worksheet->write($r, $c++, $_, $header_format ) foreach @$header;
42
43 foreach my $row ( @$rows ) {
44   $r++;
45   $c = 0;
46
47   if ( $opt{'fields'} ) {
48
49     #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
50     #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
51     #could also translate color, size, style into xls equivalents?
52     my $formats = $opt{'xls_format'} ? [ @{$opt{'xls_format'}} ] : [];
53
54     foreach my $field ( @{$opt{'fields'}} ) {
55
56       my $format = shift @$formats;
57       $format = &{$format}($row) if ref($format) eq 'CODE';
58       $format ||= {};
59       my $xls_format = $workbook->add_format(locked=>0, %$format);
60
61       if ( ref($field) eq 'CODE' ) {
62         foreach my $value ( &{$field}($row) ) {
63           if ( ref($value) eq 'ARRAY' ) { 
64             $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
65           } else {
66             $worksheet->write($r, $c++, $value, $xls_format );
67           }
68         }
69       } else {
70         $worksheet->write($r, $c++, $row->$field(), $xls_format );
71       }
72     }
73
74   } else {
75     my $xls_format = $workbook->add_format(locked=>0);
76     $worksheet->write($r, $c++, $_, $xls_format ) foreach @$row;
77   }
78
79 }
80
81 $workbook->close();# or die "Error creating .xls file: $!";
82
83 http_header('Content-Length' => length($data) );
84
85 </%init>