- #!/usr/bin/perl
- # csv_to_excel.cgi - given CSV file convert to XLS and output for download
- #
- # created: 2013-07-27
- # author: darko.prelec@gmail.com
- use 5.010;
- use strict;
- #use warnings;
- use utf8;
- our $VERSION = '1.0';
- use Carp;
- use CGI;
- use Text::CSV;
- use Excel::Writer::XLSX;
- use Scalar::Util qw/looks_like_number/;
- $SIG{__DIE__} = sub {
- use Carp;
- };
- our $FS = ';';
- our $ROOT;
- our $CGI = CGI->new;
- $ROOT = $ENV{'DOCUMENT_ROOT'};
- sub http_die {
- }
- }
- exit;
- }
- sub convert_csv_to_xlsx {
- my $content;
- my $workbook = Excel::Writer::XLSX->new($fh_excel)
- or http_die("Cannot init Excel::Writer: $!");
- my $worksheet = $workbook->add_worksheet;
- my $num_format = $workbook->add_format;
- $num_format->set_num_format("0.00");
- my $csv = Text::CSV->new({ binary => 1, sep_char => $FS })
- or http_die("Text::CSV died: " . Text::CSV->error_diag);
- my $count = 0;
- my @format_fields;
- while (my $row = $csv->getline($fh_csv)) {
- if ($count == 0) {
- for my $i (0 .. $#$row) {
- if ($row->[$i] =~ /(Koli.ina|Iznos|Osnovica za PDV)/) {
- }
- }
- # skip warnings about non-numeric value
- $count++;
- next;
- }
- for my $i (0 .. $#$row) {
- if (looks_like_number($row->[$i])
- {
- $worksheet->write_number($count, $i, $row->[$i], $num_format);
- }
- else {
- }
- }
- $count++;
- }
- }
- # only for debugging
- #$SIG{__DIE__} = sub {
- # http_die(Carp::longmess(@_));
- #};
- my $file = $CGI->param('file');
- exit;
- }
- or not -e "$ROOT$file")
- {
- "-content-type" => "text/html",
- "-status" => "404 Not Found"
- );
- exit;
- }
- my $filename = "$1.xlsx";
- my $xlsx_content = convert_csv_to_xlsx("$ROOT$file");
- }
- else {
- }