[英]How can you extract the currently-selected range of cells in LibreOffice calc via pyuno?
When using pyuno in a LibreOffice / OpenOffice calc python macro, I would like simply to be able to select a range of cells, and when the macro is run, for all of the cell data (eg as some iterable object) to be able to be retrieved within the python script, so that it can be manipulated. 在LibreOffice / OpenOffice calc python宏中使用pyuno时,我只希望能够选择一系列单元格,并且在运行宏时,对于所有单元格数据(例如,作为一些可迭代对象),可以在python脚本中检索,以便可以对其进行操作。 I have found hardly any documentation on this, and would welcome some example code that demonstrates how to do this.
我几乎没有关于此的任何文档,并且欢迎一些示例代码演示如何执行此操作。
After a very painful time of trial and error (thanks to the scant documentation and examples on pyuno usage anywhere -- please correct me if I've overlooked something), I ended up with the following code that seems to do what I'm after: 经过一段非常痛苦的尝试和错误(由于缺少有关pyuno使用的文档和示例,如果我忽略了某些内容,请纠正我),我最终得到了以下代码,该代码似乎可以满足我的要求:
import uno
doc = XSCRIPTCONTEXT.getDocument()
def mymodule():
ctrlr = doc.CurrentController
sel = ctrlr.getSelection()
x = sel.getDataArray()
# now the data is available as nested tuples in x, so do something with it
file('/tmp/out', 'w').write(repr(x))
This can be put into a python file, and stored (at least with Ubuntu 14.04) in the ~/.config/libreoffice/4/user/Scripts/python
directory, and then as long as the libreoffice-script-provider-python
package is installed, it can be run from within LibreOffice Calc via the Tools->Macros->Run Macro menu option. 可以将其放入python文件,并存储(至少在Ubuntu 14.04中)到
~/.config/libreoffice/4/user/Scripts/python
目录中,然后再存储到libreoffice-script-provider-python
包中已安装,可以通过“ 工具”->“宏”->“运行宏”菜单选项在LibreOffice Calc中运行 。 Or it can be bound to a keyboard shortcut using the Tools->Customize->Keyboard dialog. 也可以使用“ 工具”->“自定义”->“键盘”对话框将其绑定到键盘快捷键。
For a more complete example that allows one to load data from LibreOffice Calc into Octave for further analysis, see this pyuno script . 有关允许将LibreOffice Calc中的数据加载到Octave中进行进一步分析的更完整示例,请参阅此pyuno脚本 。
Or you could try something like this, which I think is more easily understood. 或者您可以尝试类似的方法,我认为这更容易理解。
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
try:
sheets = model.getSheets()
except AttributeError:
raise Exception("This script is for Calc Spreadsheets only")
#sheet = sheets.getByName('Sheet1')
sheet = model.CurrentController.getActiveSheet()
oSelection = model.getCurrentSelection()
oArea = oSelection.getRangeAddress()
first_row = oArea.StartRow
last_row = oArea.EndRow
first_col = oArea.StartColumn
last_col = oArea.EndColumn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.