Skip to content

Instantly share code, notes, and snippets.

@noirbizarre
Last active January 2, 2024 19:06
Show Gist options
  • Save noirbizarre/27533d83556fd010c13c994604e158a2 to your computer and use it in GitHub Desktop.
Save noirbizarre/27533d83556fd010c13c994604e158a2 to your computer and use it in GitHub Desktop.
A Python macro for LibreOffice calc exporting all the sheets from a spreadsheet to CSV files UTF-8 encoded

Manual

This macro has to be installed in your personnal user macro in:

  • ~/.config/libreoffice/4/user/Scripts/python/export_as_csvs.py on Linux
  • \AppData\Roaming\LibreOffice\4\user\Scripts\python\export_as_csvs.py on Windows
  • /Applications/LibreOffice.app/Contents/Resources/Scripts/python/export_as_csvs.py on MacOS (there may be a better alternative)

You can execute it from the menu Tools > Macros > Run macro... and then select My Macros > export_as_csv in the left column and export_sheets_to_csv in the right one and then click on Run.

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,
@MattInglisWhalen
Copy link

MattInglisWhalen commented Jan 2, 2024

Works beautifully on windows. How would I change the delimeter to be a comma instead of a semicolon?

EDIT: solved. Change 59 to 44

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment