Create tables out of csv data

From Scribus Wiki
Revision as of 21:49, 12 March 2009 by Stetters (talk | contribs) (New page: #!/usr/bin/env python # -*- coding: utf-8 -*- """ ABOUT THIS SCRIPT: Import CSV data files as tables into Scribus 1st create any frame with the desired table size on your page make shur...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
  1. !/usr/bin/env python
  2. -*- coding: utf-8 -*-

""" ABOUT THIS SCRIPT:

Import CSV data files as tables into Scribus

1st create any frame with the desired table size on your page

make shure it is selected

execute this script you will be prompted for a csv filename

the data from the csv file will be imported and a table of textboxes will be drawn on the page.


LICENSE:

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

Author: Sebastian Stetter

please report bugs to: scribusscript@sebastianstetter.de """

from __future__ import division import sys

try:

   # Please do not use 'from scribus import *' . If you must use a 'from import',
   # Do so _after_ the 'import scribus' and only import the names you need, such
   # as commonly used constants.
   import scribus

except ImportError,err:

   print "This Python script is written for the Scribus scripting interface."
   print "It can only be run from within Scribus."
   sys.exit(1)
  1. YOUR IMPORTS GO HERE #

import csv


  1. get information about the area where the bale should be drawed

def getAriaInformation():

   if scribus.selectionCount() == 1:
       AI = dict()
       areaname = scribus.getSelectedObject()
       areaposition= scribus.getPosition(areaname)
       AI["vpos"] = areaposition[1]
       AI["hpos"] = areaposition[0]
       areadimensions = scribus.getSize(areaname)
       AI["vsize"]=areadimensions[1]
       AI["hsize"]=areadimensions[0]
       scribus.deleteObject(areaname)
       return AI
       
       
   else: 
       scribus.messageBox("csv2table", "please select ONE Object to mark the drawing area for the table")
       sys.exit()
  1. get the cvs data

def getCSVdata():

   """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
   csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
   if csvfile != "":
       try:
           reader = csv.reader(file(csvfile))
           datalist=[]
           for row in reader:
               rowlist=[]
               for col in row:
                   rowlist.append(col)
               datalist.append(rowlist)
           return datalist
       except Exception,  e:
           scribus.messageBox("csv2table", "Could not open file %s"%e)
   else:
       sys.exit

def getDataInformation(list):

   """takes a 2 dimensional list object and returns the numbers of rows and cols"""
   datainfo = dict()
   datainfo["rowcount"]=len(list)
   datainfo["colcount"]= len(list[0])
   return datainfo


def cellsize(areainfo, datainfo):

   """"takes the area and data info and calculates the prper cell size"""
   csize=dict()
   csize["v"]= areainfo["vsize"] / datainfo["rowcount"]
   csize["h"]= areainfo["hsize"] / datainfo["colcount"]
   return csize
   

def main(argv):

   """This is a documentation string. Write a description of what your code
   does here. You should generally put documentation strings ("docstrings")
   on all your Python functions."""
   #########################
   #  YOUR CODE GOES HERE  #
   #########################
   userdim=scribus.getUnit() #get unit and change it to mm
   scribus.setUnit(scribus.UNIT_MILLIMETERS)
   
   ai = getAriaInformation()
   data = getCSVdata()
   di= getDataInformation(data)
   cs = cellsize(ai,di)
   
   vcellsize = cs["v"]
   hcellsize = cs["h"]
   hposition=ai["hpos"]
   vposition=ai["vpos"]
   
   objectlist=[] # here we keep a record of all the created textboxes so we can group them later
   i=0
   scribus.progressTotal(len(data))
   scribus.setRedraw(False)
   for row in data:
       for cell in row:
           textbox=scribus.createText(hposition, vposition, hcellsize, vcellsize) #create a textbox
           objectlist.append(textbox)
           scribus.insertText(cell,0, textbox)#insert the text into the textbox
           hposition=hposition+hcellsize #move the position for the next cell
       vposition=vposition+vcellsize #set vertical position for next row
       hposition=ai["hpos"] #reset vertical position for next row
       i=i+1
       scribus.progressSet(i)
   
   #scribus.groupObjects(objectlist) #pack thre whole stuff togehter ##############This causes scribus to render veeeery slowly!!!
   
   scribus.progressReset()
   scribus.setUnit(userdim) # reset unit to previous value
   scribus.docChanged(True)
   scribus.statusMessage("Done")
   scribus.setRedraw(True)

def main_wrapper(argv):

   """The main_wrapper() function disables redrawing, sets a sensible generic
   status bar message, and optionally sets up the progress bar. It then runs
   the main() function. Once everything finishes it cleans up after the main()
   function, making sure everything is sane before the script terminates."""
   try:

scribus.statusMessage("Importing .csv table...")

       scribus.progressReset()
       main(argv)
   finally:
       # Exit neatly even if the script terminated with an exception,
       # so we leave the progress bar and status bar blank and make sure
       # drawing is enabled.
       if scribus.haveDoc():
           scribus.setRedraw(True)
       scribus.statusMessage("")
       scribus.progressReset()
  1. This code detects if the script is being run as a script, or imported as a module.
  2. It only runs main() if being run as a script. This permits you to import your script
  3. and control it manually for debugging.

if __name__ == '__main__':

   main_wrapper(sys.argv)