Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.