PyUno 和 calc/spreadsheet:如何将单张表导出到 csv?

问题描述 投票:0回答:1

我需要通过 PyUNO 自动执行一些电子表格操作和导出,但我在将单个工作表导出到 CSV 方面遇到了困难。

我制作了一个简单的 shell 脚本,首先启动 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打开的文件名?

python csv spreadsheet pyuno
1个回答
0
投票

你有没有看过如何使用python uno打开xls文件并另存为UTF-8的csvExport的命令是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,
© www.soinside.com 2019 - 2024. All rights reserved.