【问题标题】:Write Dataframe into ODS format将 Dataframe 写入 ODS 格式
【发布时间】:2019-11-18 13:24:43
【问题描述】:

我正在使用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。

【问题讨论】:

    标签: python python-3.x pandas pyexcel


    【解决方案1】:

    请注意,在最新版本的 Pandas(当前为 1.1)中,已在 pd.ExcelWriter()pd.read_excel() 等函数中实现了对 ODS 格式的支持。您只需要指定合适的引擎“odf”即可使用 OpenDocument 文件格式(.odf、.ods、.odt)

    【讨论】:

      【解决方案2】:

      Soham 试试这个,我认为你的解决方案的问题是 py_ods 的 save_data 函数没有以它需要的格式获取数据。

      解释在cmets中。

      # 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)
      

      this data from microsoft尝试上述方法

      >>> save_ods_from_excel('/Users/gkm/Downloads/Financial Sample.xlsx', '/tmp/sample-financial.ods')
      

      更多信息the pyexcel ods docs

      【讨论】:

      • 谢谢 Man.Works 完美,拯救了我的一天。
      • 太好了,很高兴我能帮上忙
      【解决方案3】:

      试试这个:

      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]])])
      
      

      【讨论】:

      • 遇到同样的错误——TypeError: 'int' object is not iterable
      猜你喜欢
      • 2022-11-06
      • 2016-09-21
      • 2018-06-05
      • 2015-09-03
      • 2023-03-18
      • 1970-01-01
      • 2016-10-16
      • 2014-12-08
      • 1970-01-01
      相关资源
      最近更新 更多