【问题标题】:How to write on existing excel files without losing previous information using python?如何使用 python 在现有的 excel 文件上写入而不丢失以前的信息?
【发布时间】:2018-01-21 00:42:00
【问题描述】:

我需要编写一个程序来从某个网页中提取每日报价并将它们收集到一个 Excel 文件中。我写了一些东西,它找到下一个空行并开始在上面写新的引号,但也删除了以前的行:

wb = openpyxl.load_workbook('gold_quote.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
.
.
.
z = 1
x = sheet['A{}'.format(z)].value

while x != None:
    x = sheet['A{}'.format(z)].value
    z += 1

writer = pd.ExcelWriter('quote.xlsx')
df.to_excel(writer, sheet_name='Sheet1',na_rep='', float_format=None,columns=['Date', 'Time', 'Price'], header=True,index=False, index_label=None, startrow=z-1, startcol=0, engine=None,merge_cells=True, encoding=None, inf_rep='inf', verbose=True, freeze_panes=None)
writer.save()

【问题讨论】:

  • 听起来你正在编译一个字符串列表。为什么不让它成为一个以行分隔的 txt 文件呢?每一行都可以是它自己的条目。
  • 我需要 excel 文件进行进一步处理。我可以用这段代码写在 excel 文件上,但是在每天更新之前的行将被删除。
  • 听起来类似于打开具有写入与追加状态的文件。

标签: python excel pandas append


【解决方案1】:
writer.book = wb
writer.sheets = dict((ws.title, ws) for ws in wb.worksheets)

【讨论】:

  • 在结尾部分添加此代码的效果完全相同,我是否应该从代码中删除任何内容以便在每次执行时保留以前的行?
  • 在这一行添加它:writer = pd.ExcelWriter('quote.xlsx')
  • 执行时出现此错误:xl_format = self.book.add_format() AttributeError: 'Workbook' object has no attribute 'add_format'
【解决方案2】:

问题:如何在现有的excel文件上书写而不丢失以前的信息

openpyxl 使用append 在最后使用行之后写入:

wb = openpyxl.load_workbook('gold_quote.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

rowData = ['2017-08-01', '16:31', 1.23]
sheet.append(rowData)

wb.save('gold_quote.xlsx')

【讨论】:

  • 一切看起来都不错,除非它不能附加 padnas 数据帧格式。它说无法转换为 Excel。
  • 应追加的最终数据类型为:
  • @Farhad:您必须将pandas.DataFrame 转换为listappend Row by Row from List 或iterate pandas.DataFrame
【解决方案3】:

我想通了,首先我们应该定义一个读取器来读取 excel 文件的现有数据,然后将最近从 Web 提取的数据与定义的写入器连接起来,我们应该删除重复项,否则任何时候执行程序都会有很多重复项数据。然后我们可以一起写入以前的和新的数据:

excel_reader = pd.ExcelFile('gold_quote.xlsx')
to_update = {"Sheet1": df}

excel_writer = pd.ExcelWriter('gold_quote.xlsx')

for sheet in excel_reader.sheet_names:
    sheet_df = excel_reader.parse(sheet)
    append_df = to_update.get(sheet)

    if append_df is not None:
        sheet_df = pd.concat([sheet_df, df]).drop_duplicates()

    sheet_df.to_excel(excel_writer, sheet, index=False)

excel_writer.save()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    相关资源
    最近更新 更多