Skip to content

Instantly share code, notes, and snippets.

@noirbizarre
Created April 17, 2019 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noirbizarre/229589f0e8489f282e30a81b6be6e48a to your computer and use it in GitHub Desktop.
Save noirbizarre/229589f0e8489f282e30a81b6be6e48a to your computer and use it in GitHub Desktop.
Export LibreOffice Calc sheets to individual CSV files
'''
A LibreOffice Calc Python macro exporting each sheet to an individual CSV file.
The CSV will be named <sheet name>.csv and will be sibling the source file.
To use this macro, store this file in your LibreOffice Python Scripts dir,
ie. `~/.config/libreoffice/4/user/Scripts/python/` on Linux
'''
import os
import unicodedata
from com.sun.star.beans import PropertyValue
def csv_properties():
'''Build the dialog parameter for UTF-8 CSV'''
props = []
p = PropertyValue()
p.Name = 'FilterName'
p.Value = 'Text - txt - csv (StarCalc)'
props.append(p)
p = PropertyValue()
p.Name = 'FilterOptions'
p.Value = '59,34,76,1,,0,false,true,true,false'
props.append(p)
return tuple(props)
def export_sheets_to_csv():
'''Iter over each sheet and save it as CSV file. '''
desktop = XSCRIPTCONTEXT.getDesktop() # noqa
model = desktop.getCurrentComponent()
controller = model.getCurrentController()
dirname = os.path.dirname(model.URL)
for sheet in model.Sheets:
controller.setActiveSheet(sheet)
name = sheet.getName().lower().replace(' ', '-')
name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore')
filename = '{0}/{1}.csv'.format(dirname, name.decode('ascii'))
model.storeToURL(filename, csv_properties())
g_exportedScripts = export_sheets_to_csv,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment