![](/img/trans.png)
[英]How to use LibreOffice API (UNO) with Python + Windows?
[英]Python UNO (libreoffice): How to enable auto filters for a sheet
我有一個程序,它創建一個 CSV 文件。
現在我想使用一個 Python UNO 腳本,它應該做幾件事:
1.) 在電子表格中打開 csv 文件
2.) 為所有列啟用自動過濾器
3.)創建一個宏並將其添加到文檔中
4.) 將文件另存為 ODS 文件
這個問題只涉及2。)
1.) 正在工作
對於 3.) 我可能會創建另一個問題 1.) 正在工作(使用 pyoo 和 unotools)
到目前為止我的步驟:
我手動啟動:
libreoffice --accept='socket,host=localhost,port=2202;urp;' --norestore --nologo --nodefault
我的python腳本:
與表
import pyoo
# Step 0) connect to UNO bridge
desktop = pyoo.Desktop('localhost', 2002)
# Step 1) open the doc and get the sheet
# This works only if the field separator is a comma.
# I don't know how for example to specify tab as separator instead
doc = desktop.open_spreadsheet('tst.csv')
# I see the spreadsheet opening
sheet = doc.sheets[0] # I get an object of type Sheet
# Step2) set autofilter for active sheet
# no idea how to do
# Step3) create a macro and add it to the document
# no idea how to do but will create another question as
# soon as step2 is solved
# Step 4) save the sheet
doc.save("tst_pyoo.ods")
或者使用 unotools
import unotools
from unotools.component.calc import Calc
from unotools.unohelper import convert_path_to_url
# Step 0) connect to UNO bridge
context = unotools.connect(unotools.Socket('localhost', 2002))
# Step 1) open document
doc = Calc(ctx, convert_path_to_url('tst.csv')
# I see the spreadsheet opening
sheet = doc.get_sheet_by_index(0)
# I get an object of type unotools.component.calc.Spreadsheet
# Step2) set autofilter for active sheet
# no idea how to do
# Step3) create a macro and add it to the document
# no idea how to do but will create another question as
# soon as step2 is solved
# Step 4)
doc.store_to_url(convert_path_to_url("tst_unotools.ods"))
提前感謝您的任何反饋
這是使用直接 PyUNO 而不是包裝庫的代碼。 它改編自http://www.imaccanici.org/en.libreofficeforum.org/node/5413.html 。
import os
import uno
class UnoObjs:
"Initializes and stores UNO objects to connect to a document."""
def __init__(self, filepath=None):
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext )
self.ctx = resolver.resolve(
"uno:socket,host=localhost,port=2002;urp;"
"StarOffice.ComponentContext")
self.smgr = self.ctx.ServiceManager
desktop = self.smgr.createInstanceWithContext(
"com.sun.star.frame.Desktop", self.ctx)
if filepath:
fileUrl = uno.systemPathToFileUrl(os.path.realpath(filepath))
self.document = desktop.loadComponentFromURL(
fileUrl, "_default", 0, ())
else:
self.document = desktop.getCurrentComponent()
def add_autofilter(unoObjs):
"""This adds an autofilter by selecting only the filled spreadsheet area.
NOTE: If any cell in the header row of the selection is empty this will
trigger a popup for interactive user action (must click Yes for the
Autofilter column header message box)
"""
dispatcher = unoObjs.smgr.createInstanceWithContext(
"com.sun.star.frame.DispatchHelper", unoObjs.ctx)
controller = unoObjs.document.getCurrentController()
sheet = unoObjs.document.getSheets().getByIndex(0)
# select a sufficiently big "guess" area, hopefully
guessRange = sheet.getCellRangeByPosition(0, 0, 150, 10000)
# look up the actual used area within the guess area
cursor = sheet.createCursorByRange(guessRange)
cursor.gotoEndOfUsedArea(False)
lastcol = cursor.RangeAddress.EndColumn
lastrow = cursor.RangeAddress.EndRow
# select the filled part of the spreadsheet
actualRange = sheet.getCellRangeByPosition(0, 0, lastcol, lastrow)
controller.select(actualRange)
# add autofilter
dispatcher.executeDispatch(
unoObjs.document.getCurrentController(), ".uno:DataFilterAutoFilter",
"", 0, ())
add_autofilter(UnoObjs("tst.csv"))
諸如.uno:DataFilterAutoFilter
類的調度程序調用很難找出參數。 在大多數情況下,最好改用 UNO API 調用,例如XTextCursor 。 但是,有幾個選項可以確定調度員調用:
關於調度員調用,請參閱https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=61127 。
是否可以用python修改.ods文件中直接包含的content.xml
?
我的目標也是在 Windows 10 上的 LibreOffice 中應用自動過濾器。我找不到任何文檔。
但是我發現如果你解壓一個 .ods 文件,在 content.xml 文件中有以下幾行 xml
<table:database-ranges>
<table:database-range table:name="__Anonymous_Sheet_DB__0" table:target-range-address="Sheet1.A1:Sheet1.B3" table:display-filter-buttons="true"/>
</table:database-ranges>
有沒有辦法使用 python 的 lxml 模塊讀取和修改 content.xml 並以這種方式在 LibreOffice 中應用自動過濾器?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.