2 # -*- coding: utf-8 -*-
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
10 # Full author contact details are available in file CREDITS
12 # This script reads a csv-table (file name.csv) and converts it into
13 # a LyX-table for versions 1.5.0 and higher (LyX table format 276).
14 # The original csv2lyx was witten by Antonio Gulino <antonio.gulino@tin.it>
15 # in Perl for LyX 1.x and modified for LyX table format 276 by the author.
19 import os, re, string, sys, unicodedata
22 sys.stderr.write(message + '\n')
25 # processing command line options
26 if len(sys.argv) == 1 or sys.argv[1] == '--help':
28 csv2lyx [options] mycsvfile mytmptable.lyx
30 This script creates a LyX document containing a table
31 from a comma-separated-value file. The LyX file has format 276
32 and can be opened with LyX 1.5.0 and newer.
35 -s separator column separator, default is Tab
36 --help usage instructions
39 If your .csv file contains special characters (e. g. umlauts,
40 accented letters, etc.) make sure it is coded in UTF-8 (unicode).
41 Else LyX will loose some cell contents.'''
44 # print len(sys.argv), sys.argv
47 if len(sys.argv) == 3:
50 elif len(sys.argv) == 5:
53 if sys.argv[1] == '-s':
54 separator = sys.argv[2]
56 if not os.path.exists(infile):
57 error('File "%s" not found.' % infile)
59 finput = open(infile, 'r')
60 rowcontent = finput.readlines()
62 num_rows = len(rowcontent) # number of lines
63 # print 'num_rows ', num_rows
65 num_cols = 1 # max columns
67 # print len(rowcontent[i]), ' ', rowcontent[i]
68 num_cols = max(num_cols, rowcontent[i].count(separator) + 1)
72 fout = open(outfile, 'w')
76 fout.write("""#csv2lyx created this file
84 \\font_typewriter default
85 \\font_default_family default
91 \\paperfontsize default
98 \\paperorientation portrait
101 \\paragraph_separation indent
105 \\paperpagestyle default
106 \\tracking_changes false
107 \\output_changes false
112 \\begin_layout Standard
114 \\begin_inset Tabular
116 fout.write('<lyxtabular version="3" rows=\"' + str(num_rows) + '\" columns=\"' + str(num_cols) + '\">\n')
117 fout.write('<features>\n')
118 #####################
123 fout.write('<column alignment="left" valignment="top" width="0pt">\n')
127 fout.write('<row>\n')
128 row = str(rowcontent[j])
129 row = string.split(row,separator)
131 ############################
132 # write contents of one line
133 ############################
136 fout.write("""<cell alignment="left" valignment="top" usebox="none">
139 \\begin_layout Standard\n""")
140 fout.write(row[i].strip('\n'))
141 fout.write('\n\\end_layout\n\n\\end_inset\n</cell>\n')
143 fout.write('</row>\n')
145 #####################
148 fout.write("""</lyxtabular>