我正在使用pandas库读取 .xlxs 文件并提取dataframe
。现在,我尝试创建扩展名为 .ods 的文件,并使用pyexcel_ods库将dataframe
写入文件。
这是我的代码:-
import pandas as pd
from pyexcel_ods import save_data
from collections import OrderedDict
self.current_df = pd.read_excel('filename')
data = OrderedDict()
data.update(df)
save_data("as.ods", data)
它抛出错误
{TypeError}'int'对象不可迭代
随时要求提供更多代码。
注意:-我正在使用Python 3。
答案 0 :(得分:3)
请注意,在最新版本的Pandas(当前版本为1.1)中,已实现了对pd.ExcelWriter()和pd.read_excel()之类的ODS格式的支持。您只需指定适当的引擎“ odf”即可使用OpenDocument文件格式(.odf,.ods,.odt)
答案 1 :(得分:1)
Soham尝试一下,我认为您的解决方案存在的问题是py_ods的save_data
函数无法获取所需格式的数据。
解释在注释中。
# coding: utf-8
import pandas as pd
from pyexcel_ods import save_data
from collections import OrderedDict
def save_ods_from_excel(excel_file, target_ods_file):
# First read into dataframe
df = pd.read_excel(excel_file)
# Change everything to string since we're just writing
df = df.astype(str)
# Initiliaze data to be written as an empty list, as pyods needs a list to write
whole_data_list = []
# Initiliaze the empty dict() for the data
d = OrderedDict()
# Write the columns first to be the first entries
whole_data_list.append(list(df.columns))
# loop through data frame and update the data list
for index, row in df.iterrows():
whole_data_list.append(list(row.values))
# Populate dict() with updated data list
d.update({"Moved sheet": whole_data_list})
# Finally call save_data() from pyods to store the ods file
save_data(target_ods_file, d)
进行了上述尝试
>>> save_ods_from_excel('/Users/gkm/Downloads/Financial Sample.xlsx', '/tmp/sample-financial.ods')
答案 2 :(得分:0)
尝试一下:
from collections import OrderedDict
from pyexcel_ods import get_data
current_df = pd.read_excel('array.xlsx')
data = OrderedDict()
data.update({ "Sheet_1": current_df.to_numpy().tolist() })
save_data("as.ods", data)
data = get_data("as.ods")
data
#OrderedDict([('Sheet_1',
# [['b', 121], ['c', 98], ['d', 9], ['e', 100], ['f', 45]])])