RSS
 

Perl, from Excel to MySQL

10 Mar

One of the reasons I like Perl – it’s really fast on solving daily routines. The request was to get a list of shipping flags from one of the websites to Excel and paste it to the site’s database. Quick and dirty solution:

#!/usr/bin/perl
 
use strict;
use warnings;
use DBI;
use Spreadsheet::ParseExcel;
 
my $file = 'flags.xls';
 
my $xl_parser = Spreadsheet::ParseExcel->new();
 
my $workbook = $xl_parser->Parse($file);
my $worksheet = $workbook->worksheet('Sheet1');
 
my ($c_min,$c_max) = $worksheet->col_range();
my ($r_min,$r_max) = $worksheet->row_range();
 
my @flags;  # used for storing an array of flags;
 
for my $row($r_min..$r_max) {
 
    for my $col($c_min..$c_max) {
 
        my $cell = $worksheet->get_cell($row,$col);
        my $val = $cell->value;
 
        $val =~ s/^\s+(.*?)\s$//g;
 
        push @flags, $val;
        #some extras on different cells/etc/
 
    }   
}
 
my $dsn = "DBI:mysql:database=db_blah;host=host;port=blah_port";
my $dbh = DBI->connect( $dsn, 'usr_blah', 'pwd_blah') || die("Couldn't connect to database\n");
 
 
$dbh->do("INSERT INTO flags(name) VALUES(".$dbh->quote($_).")") for @flags;
 

Tags: , ,

Leave a Reply