Skip to content

Instantly share code, notes, and snippets.

@naoh16
Created March 5, 2012 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naoh16/1977461 to your computer and use it in GitHub Desktop.
Save naoh16/1977461 to your computer and use it in GitHub Desktop.
Convert Excel table to LaTeX table format
#!/usr/bin/perl
#
# excel_latex_copy.pl
#
# Convert Excel table to LaTeX table format
# using Win32::Clipboard (Windows only)
#
# Copyright (C) 2012- Sunao HARA, NAIST/JAPAN. All rights reserved.
# Last Modified: 2012/03/05 17:22:08.
#
use strict;
use Win32::Clipboard;
my $clip = Win32::Clipboard();
exit 1 unless $clip->IsText();
# Get and format
my $text = $clip->GetText();
$text =~ s/^ +//g; $text =~ s/ +$//g;
$text =~ s/ +\t/\t/g; $text =~ s/\t +/\t/g;
$text =~ s/\%/\\%/g;
my @lines = split(/\r\n/, $text);
# Calculate the column length
my @slen = ();
foreach my $l (@lines) {
my @a = split(/\t/, $l);
my @alen = map {length} @a;
for(my $i=0; $i<=$#alen; ++$i) {
$slen[$i] = ($alen[$i] > $slen[$i])?$alen[$i]:$slen[$i]
}
}
# Format strings
$text = "";
foreach my $l (@lines) {
my @a = split(/\t/, $l);
map {s/(^ | $)//} @a;
$text .= join ' & ', map { sprintf("%*s", $slen[$_], $a[$_])} (0 .. $#slen);
$text .= " \\\\\n";
}
# Output STDOUT
print $text;
# Return to clipboard text
#$clip->Set($text);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment