简体   繁体   English

如何使用 python 在 libreoffice calc 中编写 pandas 数据框?

[英]how to write pandas dataframe in libreoffice calc using python?

I am using the following code in ubuntu 20.我在 ubuntu 20 中使用以下代码。

import pyoo
import os
import uno
import pandas as pd
os.system("/usr/lib/libreoffice/program/soffice.bin --headless --invisible --nocrashreport --nodefault --nofirststartwizard --nologo --norestore --accept='socket,host=localhost,port=2002,tcpNoDelay=1;urp;StarOffice.ComponentContext'")
df=pd.Dataframe()
df['Name']=['Anil','Raju','Arun']
df['Age']=['32','34','45']
desktop = pyoo.Desktop('localhost', 2002)
doc = desktop.open_spreadsheet("/home/vivek/Documents/Libre python trial/oi_data.ods")
sh1=doc.sheets['oi_data']
sh1[1,4].value=df
doc.save()

It gives all data in a single cell as a string:它将单个单元格中的所有数据作为字符串提供:

'Name age0 Anil 321 Raju 342 Arun 45'

I want to write a DataFrame in LibreOffice Calc in columns & rows of sheet like this :我想在 LibreOffice Calc 中的列和行中编写一个 DataFrame,如下所示:

   Name  age
0  Anil  32
1  Raju  34
2  Arun  45
example code used in xlwings in window os just for reference (I want to achieve same with simple code in Libreoffice calc in ubuntu/Linux, if possible..)
import pandas as pd
import xlwings as xlw

# Connecting with excel workbook
file=xlw.Book("data.xlsx") 
# connection with excel sheet
sh1=file.sheets('sheet1')

df=pd.DataFrame()
df['Name']=['Anil','Raju','Arun']
df['Age']=['32','34','45']

sh1.range('A4').value=df

From the pyoo documentation , a range of values is set with a list of lists.pyoo 文档中,使用列表列表设置了一系列值。

sheet[1:3,0:2].values = [[3, 4], [5, 6]]

To get a list of lists from a dataframe, the following code is recommended at How to convert a Python Dataframe to List of Lists?要从数据框中获取列表列表,建议在如何将 Python 数据框转换为列表列表中使用以下代码? :

lst = [df[i].tolist() for i in df.columns]

EDIT :编辑

Write a function called insertDf() that does the two things above, calculating the required indices.编写一个名为insertDf()的函数,它执行上述两件事,计算所需的索引。 Then instead of sh1.range('A4').value=df , write insertDf(df,'A4',sh1) .然后代替sh1.range('A4').value=df ,写insertDf(df,'A4',sh1)

Or perhaps more elegant is to create a class called CalcDataFrame that extends pandas.DataFrame to add a method called writeCells() .或者更优雅的方法是创建一个名为 CalcDataFrame 的类,该类扩展 pandas.DataFrame 以添加一个名为writeCells()的方法。

Also, it would be easier to write location arguments as (row number, column number) instead of a 'column letters&row number' combined string.此外,将位置参数写为(行号,列号)而不是“列字母和行号”组合字符串会更容易。

df = CalcDataFrame()
df['Name']=['Anil','Raju','Arun']
df['Age']=['32','34','45']
df.writeCells(sh1,1,4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM