gnumeric2csv.pl



Hi,

here's a perl script for batch converting gnumeric files to csv files.
I hope it may be useful for someone. The usage is:

  ./gnumeric2csv.pl -sheet nameofsheet sheet.gnumeric > sheet.csv

There are dependencies to non-standard perl modules; if you don't want
to install them manually, you can call the script with

  ./gnumeric2csv.pl -install

which will use the CPAN.pm module to install the additional modules
(this will probably need superuser permissions).

Regards,
        Slaven
#!/usr/local/bin/perl -w
# -*- perl -*-

#
# $Id: gnumeric2csv.pl,v 1.5 2001/11/07 13:00:21 eserte Exp $
# Author: Slaven Rezic
#
# Copyright (C) 2001 Online Office Berlin.
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License
#
# Mail: info onlineoffice de
# WWW:  http://www.onlineoffice.de
#

BEGIN {
    if ($ARGV[0] eq '-install') {
        eval <<'EOF';
use CPAN;
install 'Text::CSV_XS';
install 'XML::Simple';
install 'Unicode::String';
EOF
        die $@ if $@;
        exit 0;
    }
}

use Text::CSV_XS;
use XML::Simple;
use Unicode::String qw(utf8);
use strict;
use Getopt::Long;

my $sheetname;
if (!GetOptions("sheet=s" => \$sheetname)) {
    die "usage $0 [-sheet sheetname] gnumericfile > csvfile";
}

my $gnumeric_file = shift || die "Gnumeric file?";

my $gnumeric_data = `zcat $gnumeric_file`;


my $ref = XMLin($gnumeric_data, keyattr => { 'gmr:Sheet' => 'gmr:Name' },
                                forcearray => [ 'gmr:Sheet', 'gmr:Cell' ]);

my $sheets = $ref->{'gmr:Sheets'}{'gmr:Sheet'};
my $sheet;
if (defined $sheetname && !exists $sheets->{$sheetname}) {
    die "The sheet $sheetname does not exist!\n";
} elsif (keys %$sheets == 1) {
    $sheet = $sheets->{(keys %$sheets)[0]};
} elsif (!defined $sheetname) {
    die "Multiple sheets in gnumeric file: " . join(", ", keys %$sheets) . ". Please specify one with the 
-sheet option.\n";
} else {
    $sheet = $sheets->{$sheetname};
}

my $cellref = $sheet->{'gmr:Cells'}{'gmr:Cell'};

my $csv = Text::CSV_XS->new({binary => 1});
my $table = [];

foreach my $cell (@$cellref) {
    $table->[$cell->{Row}][$cell->{Col}] = utf8($cell->{'gmr:Content'})->latin1;
}

for my $row (@$table) {
    $csv->combine(@$row) or die "Can't combine to CSV: @$row";
    print $csv->string,"\n";
}

__END__



-- 
Slaven Rezic | Software Developer | rezic onlineoffice de

onlineoffice GmbH | Gubener Strasse 47 | 10243 Berlin
+49 30 293 817 45 | fax +49 30 293 817 50 | http://www.onlineoffice.de



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]