randomfox (randomfox) wrote,

Post Daily Weigh-ins to a Google Spreadsheet

This Perl script posts a daily weigh-in to a Google Spreadsheet. You have to create a "Daily Weigh-ins" spreadsheet before the first time you run this script. After that, it adds a row to the weight table every time you run it.


#!perl -w
use strict;

# Log a daily weigh-in to a Google Spreadsheet.
# You need to at least create a spreadsheet named "Daily Weigh-ins"
# before running this script.
# Then you can add weight info as follows:
#   weighin.pl 201.0 1/24/2010
# or
#   weighin.pl 201.0
# The date defaults to today's date.

# User and password are configured in weighin.conf.
# Create that file and add these lines to it:
#   user=username
#   pass=password

use Net::Google::Spreadsheets;
use Data::Dumper;
use Config::Auto;
use POSIX;

@ARGV < 1 and die "Usage: $0 weight [date]\n";

my $weight = shift;

my $date = shift;
defined($date) or
    $date = strftime("%m/%d/%Y", localtime(time));

my $config = Config::Auto::parse("weighin.conf");

my $SPREADSHEET_NAME = 'Daily Weigh-ins';
my $WORKSHEET_NAME = 'Sheet1';
my $TABLE_NAME = 'Weight Table';

unless (defined $config->{user} and defined $config->{pass}) {
    die "user and pass not specified in config file\n";
}

my $service = Net::Google::Spreadsheets->new(
    username => $config->{user},
    password => $config->{pass}
);

my $spreadsheet = $service->spreadsheet(
    { title => $SPREADSHEET_NAME }
);

defined $spreadsheet or die "Spreadsheet '$SPREADSHEET_NAME' not found\n"; 

my $worksheet = $spreadsheet->worksheet(
    { title => $WORKSHEET_NAME }
);

defined $worksheet or die "Worksheet '$WORKSHEET_NAME' not found\n";

my $table = $spreadsheet->table(
    { title => $TABLE_NAME }
);

unless (defined $table) {
    $table = $spreadsheet->add_table(
	{
	    title => $TABLE_NAME,
	    worksheet => $worksheet,
	    columns => ['Date', 'Weight']
	}
    );
}

my $record = $table->add_record(
    { Date => $date, Weight => $weight }
);

my @records = $table->records;

for (@records < 5 ? @records : splice(@records, -5)) {
    print $_->param('Date'), '  ', $_->param('Weight'), "\n";
}

__END__

Tags: google docs, google spreadsheet, perl
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 1 comment