Latex: Table converter


If you copy-paste a table out of open-office, it is usually one line per cell.

This Python script converts it into a LaTeX-table (without \begin and \end):

table2latex.py:

#!/usr/bin/env python

import sys

f = sys.stdin

if(len(sys.argv) < 2):

        print "First Argument is number of columns"

        sys.exit(1)

numcolumns = int(sys.argv[1])

borders = False

if len(sys.argv) > 2 and sys.argv[2] == "--with-borders":

        borders = True

i = 0

while True:

        for j in range(numcolumns):

                l = f.readline()

                if l == "":

                        sys.exit(0)

                if i == 0:

                        print "\\tablehdr{%s}" % l.strip(),

                else:

                        print "%s" % l.strip(),

                if j == numcolumns - 1:

                        print '\\\\'

                        if borders:

                                print '\hline'

                else:

                        print '&',

        i = i + 1

Use it like this (pipe in from stdin, first arg is column count):

[user@thiscomputer ~]$ seq 30 | python table2latex.py 3

\tablehdr{1} & \tablehdr{2} & \tablehdr{3} \\

4 & 5 & 6 \\

7 & 8 & 9 \\

10 & 11 & 12 \\

13 & 14 & 15 \\

16 & 17 & 18 \\

19 & 20 & 21 \\

22 & 23 & 24 \\

25 & 26 & 27 \\

28 & 29 & 30 \\

[user@thiscomputer ~]$ 

The second argument can be if borders should be used, i.e. \hline after each row.

  1. No comments yet.
(will not be published)

  1. No trackbacks yet.