add menu item and page for d/ling and edit rates with excel. RT#5108
[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
17 #http://support.microsoft.com/kb/812935
18 #http://support.microsoft.com/kb/323308
19 $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
20
21 my $data = '';
22 my $XLS = new IO::Scalar \$data;
23 my $workbook = Spreadsheet::WriteExcel->new($XLS)
24   or die "Error opening .xls file: $!";
25
26 my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
27
28 $worksheet->protect();
29
30 my($r,$c) = (0,0);
31
32 my $header_format = $workbook->add_format(
33   bold     => 1,
34   locked   => 1,
35   bg_color => 55, #22,
36   bottom   => 3,
37 );
38
39 $worksheet->write($r, $c++, $_, $header_format ) foreach @$header;
40
41 foreach my $row ( @$rows ) {
42   $r++;
43   $c = 0;
44
45   if ( $opt{'fields'} ) {
46
47     #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
48     #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
49     #could also translate color, size, style into xls equivalents?
50     my $formats = $opt{'xls_format'} ? [ @{$opt{'xls_format'}} ] : [];
51
52     foreach my $field ( @{$opt{'fields'}} ) {
53
54       my $format = shift @$formats;
55       $format = &{$format}($row) if ref($format) eq 'CODE';
56       $format ||= {};
57       my $xls_format = $workbook->add_format(locked=>0, %$format);
58
59       if ( ref($field) eq 'CODE' ) {
60         foreach my $value ( &{$field}($row) ) {
61           if ( ref($value) eq 'ARRAY' ) { 
62             $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
63           } else {
64             $worksheet->write($r, $c++, $value, $xls_format );
65           }
66         }
67       } else {
68         $worksheet->write($r, $c++, $row->$field(), $xls_format );
69       }
70     }
71
72   } else {
73     my $xls_format = $workbook->add_format(locked=>0);
74     $worksheet->write($r, $c++, $_, $xls_format ) foreach @$row;
75   }
76
77 }
78
79 $workbook->close();# or die "Error creating .xls file: $!";
80
81 http_header('Content-Length' => length($data) );
82  
83 </%init>