Created
April 17, 2019 14:27
-
-
Save noirbizarre/229589f0e8489f282e30a81b6be6e48a to your computer and use it in GitHub Desktop.
Export LibreOffice Calc sheets to individual CSV files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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