Created
January 25, 2024 06:17
-
-
Save tsibley/b76aa1a117309b0d6b939c26d3fcb9db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use Module::Runtime qw< require_module >; | |
use Text::CSV; | |
my $filename = $ARGV[0]; | |
my $parser_class = $filename =~ /\.xlsx$/ | |
? "Spreadsheet::ParseXLSX" | |
: "Spreadsheet::ParseExcel"; | |
require_module($parser_class); | |
my $parser = $parser_class->new; | |
my $wb = $parser->parse($filename) || die $parser->error; | |
(my $dir = $filename) =~ s/\.[^.]*$//; | |
mkdir $dir; | |
chdir $dir; | |
for my $ws ($wb->worksheets) { | |
my $csv = Text::CSV->new({ binary => 1, eol => "\n" }); | |
my $filename = $ws->get_name . '.csv'; | |
open my $fh, '>:encoding(UTF-8)', $filename | |
or die "Couldn't open $filename: $!"; | |
my ($rmin, $rmax) = $ws->row_range; | |
my ($cmin, $cmax) = $ws->col_range; | |
for my $row (0..$rmin - 1) { | |
$csv->print($fh, [ ('') x ($cmax + 1) ]); | |
} | |
for my $row ($rmin..$rmax) { | |
my @row = (('') x $cmin); | |
for my $col ($cmin..$cmax) { | |
my $cell = $ws->get_cell($row, $col); | |
push @row, $cell ? $cell->value : ''; | |
} | |
$csv->print($fh, \@row); | |
} | |
close $fh | |
or die "Couldn't close $filename: $!"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment