5 my $type = $args{'type'};
6 my $header = $args{'header'};
7 my $rows = $args{'rows'};
8 my %opt = %{ $args{'opt'} };
10 #http_header('Content-Type' => 'application/excel' ); #eww
11 #http_header('Content-Type' => 'application/msexcel' ); #alas
12 #http_header('Content-Type' => 'application/x-msexcel' ); #?
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"');
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';
24 my $XLS = new IO::Scalar \$data;
25 my $workbook = Spreadsheet::WriteExcel->new($XLS)
26 or die "Error opening .xls file: $!";
28 my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
30 $worksheet->protect();
34 my $header_format = $workbook->add_format(
40 my $default_format = $workbook->add_format(locked => 0);
43 my $money_char = FS::Conf->new->config('money_char') || '$';
46 # Wrapper for $worksheet->write.
47 # Do any massaging of the value/format here.
48 my ($r, $c, $value, $format) = @_;
49 if ( $value =~ /^\Q$money_char\E(\d+\.?\d*)$/ ) {
50 # Currency: strip the symbol, clone the requested format,
51 # and format it for currency
53 if ( !exists($money_format{$format}) ) {
54 $money_format{$format} = $workbook->add_format();
55 $money_format{$format}->copy($format);
56 $money_format{$format}->set_num_format($money_char.'#0.00#');
58 $format = $money_format{$format};
60 $worksheet->write($r, $c, $value, $format);
63 $writer->( $r, $c++, $_, $header_format ) foreach @$header;
65 foreach my $row ( @$rows ) {
69 if ( $opt{'fields'} ) {
71 #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
72 #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
73 #could also translate color, size, style into xls equivalents?
74 my $formats = $opt{'xls_format'} ? [ @{$opt{'xls_format'}} ] : [];
76 foreach my $field ( @{$opt{'fields'}} ) {
78 my $xls_format = $default_format;
80 if ( my $format = shift @$formats ) {
81 $format = &{$format}($row) if ref($format) eq 'CODE';
83 $xls_format = $workbook->add_format(locked=>0, %$format);
86 if ( ref($field) eq 'CODE' ) {
87 foreach my $value ( &{$field}($row) ) {
88 if ( ref($value) eq 'ARRAY' ) {
89 $writer->($r, $c++, '(N/A)' ); #unimplemented
91 $writer->($r, $c++, $value, $xls_format );
95 $writer->( $r, $c++, $row->$field(), $xls_format );
100 # no need for each row to need a new format
101 #my $xls_format = $workbook->add_format(locked=>0);
102 $writer->( $r, $c++, $_, $default_format ) foreach @$row;
107 $workbook->close();# or die "Error creating .xls file: $!";
109 http_header('Content-Length' => length($data) );