PyUno与Calc/电子表格:如何将单个工作表导出为CSV?

0 投票
1 回答
25 浏览
提问于 2025-04-14 15:52

我想用PyUNO来自动处理一些电子表格的操作和导出,但我在把单个工作表导出为CSV文件时遇到了困难。

我写了一个简单的脚本,首先启动LibreOffice来打开一个指定的.xlsx文件,然后运行一个python3脚本来执行所有需要的操作。

现在我只需要把当前的工作表(ActiveSheet)导出为.csv文件,但我觉得PyUNO和OO UNO的文档实在太糟糕了,找不到相关的信息。

有没有人能给我指个方向?

下面是我脚本的简化版本

import socket
import uno

def init():
    # get the uno component context from the PyUNO runtime
    localContext = uno.getComponentContext()

    # create the UnoUrlResolver
    resolver = localContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", localContext )

    # connect to the running office
    ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
    smgr = ctx.ServiceManager

    # get the central desktop object
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)

    # access the current writer document
    model = desktop.getCurrentComponent()

    return model

model = init()

active_sheet = model.CurrentController.ActiveSheet

# business logic

# now I need to export active_sheet to .csv

附加问题

我怎么用PyUNO获取打开的文件名?

1 个回答

0

你有没有看看这个链接:如何使用python uno打开xls文件并保存为UTF-8格式的csv。这里提到的导出命令是storeToURL()(而storeAsURL()就像是另存为),获取当前保存的文件名的命令是getURL()

我搜索了一下,找到了这段代码,我会把它完整地展示出来,因为这看起来正是你需要的。

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,

撰写回答