Skip to content

Instantly share code, notes, and snippets.

@jprjr
Created February 28, 2014 14:41
Show Gist options
  • Save jprjr/9272287 to your computer and use it in GitHub Desktop.
Save jprjr/9272287 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use version; our $VERSION = qv('1.0.0');
use utf8;
use open qw(:std :utf8);
use Carp;
use Cwd qw(abs_path getcwd);
use English qw(-no_match_vars);
use File::Basename;
use File::Spec;
use Getopt::Long;
use Pod::Usage;
use Spreadsheet::Read;
# you'll need to install modules for your different filetypes:
# Excel: Spreadsheet::ParseExcel and Spreadsheet::ParseXLSX
# LibreOffice: Spreadsheet::ReadSXC
use Text::CSV;
my ( $script_name, $script_folder ) = fileparse( abs_path($PROGRAM_NAME) );
my $current_folder = getcwd();
my ( $help, $man, $input, $output );
$input = $ARGV[0];
$output = $ARGV[1];
GetOptions(
'help!' => \$help,
'man!' => \$man,
) or pod2usage( -verbose => 1, -exit => 1 );
if( not defined $input or not defined $output ) {
pod2usage( -verbose => 1, -exit => 1 );
}
if( defined $help ) {
pod2usage( -verbose => 1, -exit => 0 );
}
if( defined $man ) {
pod2usage( -verbose => 2, -exit => 0 );
}
print {*STDOUT} sprintf("Converting %s to csv...\n",$input);
my $workbook = ReadData($input) or croak $OS_ERROR;
my $csv_gen = Text::CSV->new();
my $newline = "\n";
foreach my $worksheet (1..$workbook->[0]{sheets}) {
my $output_name = sprintf("%s_%02d.csv",$output,$worksheet);
print {*STDOUT} sprintf("Writing sheet %d to %s\n",$worksheet,$output_name);
open(my $csv_out, '>', $output_name) or croak $OS_ERROR;
foreach my $row (Spreadsheet::Read::rows($workbook->[$worksheet]) ) {
$csv_gen->print($csv_out,$row);
print {$csv_out} $newline;
}
close($csv_out);
}
print {*STDOUT} sprintf("Complete\n");
exit 0;
__END__
=head1 NAME
ss2csv
=head1 DESCRIPTION
This converts pretty much any Spreadsheet into a series of CSV files.
=head1 USAGE
ss2csv inputfile outputprefix
=head1 ARGUMENTS
--help Print this help text
--man Display a man page
=head1 OPTIONS
None right now.
=cut
# vim:fdm=marker:syntax=perl:cc=80:fenc=utf-8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment