Convert SpreadSheets to CSV files with Python and pyuno
Using the OORunner class that we developed last week we'll now create a Python class for converting spreadsheets into CSV files. The converter supports any type of input spreadsheet that is supported by OpenOffice.
When run the program takes pairs of input and output files, for example:
$ python ssconverter.py file1.xls file1.csv file2.ods file2.csv
Each input file is a spreadsheet and it is converted into the corresponding output file as a CSV file.
The meat of the operation happens in the convert function from the SSConverter class. The first thing it does is start OpenOffice running using the OORunner class. It then converts the input and output file names to URLs and uses the desktop object returned by OORunner to create and load a document object. Converting the spreadsheet to a CSV file is merely a matter of saving the document to the output URL. The source code for the SSConverter class follows:
#!/usr/bin/python # # Convert spreadsheet to CSV file. # # Based on: # PyODConverter (Python OpenDocument Converter) v1.0.0 - 2008-05-05 # Copyright (C) 2008 Mirko Nasato <email@example.com> # Licensed under the GNU LGPL v2.1 - or any later version. # http://www.gnu.org/licenses/lgpl-2.1.html # import os import ooutils import uno from com.sun.star.task import ErrorCodeIOException class SSConverter: """ Spreadsheet converter class. Converts spreadsheets to CSV files. """ def __init__(self, oorunner=None): self.desktop = None self.oorunner = None def convert(self, inputFile, outputFile): """ Convert the input file (a spreadsheet) to a CSV file. """ # Start openoffice if needed. if not self.desktop: if not self.oorunner: self.oorunner = ooutils.OORunner() self.desktop = self.oorunner.connect() inputUrl = uno.systemPathToFileUrl(os.path.abspath(inputFile)) outputUrl = uno.systemPathToFileUrl(os.path.abspath(outputFile)) document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, ooutils.oo_properties(Hidden=True)) try: # Additional property option: # FilterOptions="59,34,0,1" # 59 - Field separator (semicolon), this is the ascii value. # 34 - Text delimiter (double quote), this is the ascii value. # 0 - Character set (system). # 1 - First line number to export. # # For more information see: # http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options # document.storeToURL(outputUrl, ooutils.oo_properties(FilterName="Text - txt - csv (StarCalc)")) finally: document.close(True) if __name__ == "__main__": from sys import argv from os.path import isfile if len(argv) == 2 and argv == '--shutdown': ooutils.oo_shutdown_if_running() else: if len(argv) < 3 or len(argv) % 2 != 1: print "USAGE:" print " python %s INPUT-FILE OUTPUT-FILE INPUT-FILE OUTPUT-FILE..." % argv print "OR" print " python %s --shutdown" % argv exit(255) if not isfile(argv): print "File not found: %s" % argv exit(1) try: i = 1 converter = SSConverter() while i+1 < len(argv): print '%s => %s' % (argv[i], argv[i+1]) converter.convert(argv[i], argv[i+1]) i += 2 except ErrorCodeIOException, exception: print "ERROR! ErrorCodeIOException %d" % exception.ErrCode exit(1)
As with OORunner, this code is based on PyODConverter. Next week we'll write a converter function that creates the CSV file automatically from the corresponding spreadsheet if the CSV file does not exist. In addition it will re-create the CSV file if the spreadsheet is newer than the CSV file. This way you can essentially use spreadsheets and CSV files interchangeably in your code.
Mitch Frazier is an Associate Editor for Linux Journal.
|Using Salt Stack and Vagrant for Drupal Development||May 20, 2013|
|Making Linux and Android Get Along (It's Not as Hard as It Sounds)||May 16, 2013|
|Drupal Is a Framework: Why Everyone Needs to Understand This||May 15, 2013|
|Home, My Backup Data Center||May 13, 2013|
|Non-Linux FOSS: Seashore||May 10, 2013|
|Trying to Tame the Tablet||May 08, 2013|
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- New Products
- RSS Feeds
- Tech Tip: Really Simple HTTP Server with Python
1 hour 14 min ago
- Automatically updating Guest Additions
2 hours 23 min ago
- I like your topic on android
3 hours 9 min ago
- Reply to comment | Linux Journal
3 hours 30 min ago
- This is the easiest tutorial
9 hours 45 min ago
- Ahh, the Koolaid.
15 hours 23 min ago
- git-annex assistant
21 hours 23 min ago
- direct cable connection
21 hours 45 min ago
- Agreed on AirDroid. With my
21 hours 56 min ago
- I just learned this
22 hours 23 sec ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi
It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.