#!/usr/bin/perl

=head1 NAME

excel2csv -- dump all worksheets from an Excel file to CSV files

=head1 SYNOPSIS

F<excel2csv>
S<B<-h>>

F<excel2csv>
S<B<--man>>

F<rename>
S<B<[ -s ]>>
S<B<[ -S ]>>
S<B<[ -v ]>>
S<B<file.xls [ F<file2.xls> F<file3.xls> ... ]>>

=head1 DESCRIPTION

C<excel2csv> takes any number of Excel files on the command line, reads them, a
nd dumps each worksheet therein to a separate CSV file, named after the workshe
et.

=head1 ARGUMENTS

=over 4

=item B<-h>, B<--help>

See a synopsis.

=item B<--man>

Browse the manpage.

=back

=head1 OPTIONS

=over 4

=item B<-s>, B<--suffix>

The suffix for the CSV files generated. Default is C<.csv>.

=item B<-S>, B<--separator>

The field separator used in the generated CSV files. Default is C<;>.

=item B<-v>, B<--verbose>

Print additional information about the operations (not) executed.

=back

=head1 BUGS

CSV generation is fugded -- no quoting issues are taken into consideration. CSV
 generation should rely on one of the modules available for the purpose instead
.

=head1 AUTHORS

Drew Broadley, with contributions from Aristotle Pagaltzis, a bit of final wrapup by Hartmut Pilch

=head1 SOURCE

       http://www.wlug.org.nz/Excel2CSV

=head1 COPYRIGHT

=head1 IMPLEMENTATION

=head2 Package XLS2CSV

=cut

package XLS2CSV;
use base A2E::Prog;
use Spreadsheet::ParseExcel;

sub defvars {
    my $m = shift;
    $m->SUPER::defvars;
    $m->{konfig}->define('suffix|sfx|s=s', { DEFAULT => '.csv' });
    $m->{konfig}->define('separator|sep|S=s', { DEFAULT => ';' });
    $m->konfayl('xls2csv.konf');
    return 1;
};

sub cellval {
    my $cell = shift;
    return unless defined $cell;
    return unless ref $cell;
    my $val = $cell->Value();
    return $val;
};

sub xls2csv {
    my $m = shift;
    $m->dpuc('xls2csv', @_);
    my $excel = Spreadsheet::ParseExcel->new();
    my $fi = shift;
    my $book = $excel->Parse($fi);
    my $last_sheet = $book->{SheetCount} - 1;
    for my $worksheet ( @{ $book->{Worksheet} }[ 0 .. $last_sheet ] ) {
        next if not defined $worksheet->{MaxRow};
	next if not defined $worksheet->{MaxCol};
        $m->vecho($worksheet->{Name});
        my $fo = $worksheet->{Name} . $m->{konfig}->suffix;
        $m->open_fayl($fo, 'o', 'w');
        my @row = $worksheet->{MinRow} .. $worksheet->{MaxRow};
        my @col = $worksheet->{MinCol} .. $worksheet->{MaxCol};
        for my $row (@{$worksheet->{Cells}}[@row]) {
             my @cellvals = map { cellval $_ } @$row[@col];
	     my $line = join $m->{konfig}->separator, @cellvals;
	     $m->print_tu_fayl('o', $line . "\n");
        };
	$m->kloz_fayl('o');
    }
}

package Main;
my $p = new_ready XLS2CSV debug => $ENV{DEBUG}, verbose => $ENV{VERBOSE};
$p->xls2csv($_) for @ARGV;
$p->vecho('OK');

=head1 The END

=cut

exit 0;

# Local Variables:
# coding: utf-8
# url: http://a2e.de/adv/prg/bin/xls2csv.pl
# srcfile: /adv/prg/bin/xls2csv.pl
# mode: perl
# End:

