gpt4 book ai didi

Python - 使用 Pandas 和 openpyxl 修改现有的 excel

转载 作者:行者123 更新时间:2023-12-04 21:50:31 24 4
gpt4 key购买 nike

我有一个包含多张工作表的 Excel 文件 ( Celebrities.xlsx ),我正在尝试修改一个名为 Relationships 的工作表无需修改(或可能删除)其他工作表。这就是我所做的。

import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows

# Name of the celebrity that I want to modify
celeb_name = 'Terence Stamp'

wb = load_workbook('Celebrities.xlsx')
ws = wb['Relationships']

df = pd.read_excel('Celebrities.xlsx', sheet_name='Relationships')

# This part is trivial, but basically I'm replacing every null cell in 'Link' column with the word 'empty' (of that particular celebrity)
df.loc[(df['Celebrity Name'] == celeb_name) & (df['Link'].isnull()), 'Link'] = 'empty'

for r in dataframe_to_rows(df, index=True, header=True):
ws.append(r)

wb.save('new.xlsx')

现在脚本运行没有任何错误, new.xlsx已成功创建,但是当我尝试打开它时,它给了我这个错误:

Warning loading document new.xlsx: The data could not be loaded completely because the maximum number of rows per sheet was exceeded.



并且没有任何修改!

我可以保证这部分代码可以完美运行:
wb = load_workbook('Celebrities.xlsx')
ws = wb['Relationships']
wb.save('new.xlsx')

我想问题出在这部分代码上:
for r in dataframe_to_rows(df, index=True, header=True):
ws.append(r)

但我不知道如何解决它。

最佳答案

你在你的问题中说没有任何修改。但它有。您的代码循环遍历数据框,并在每次循环时向工作表添加一个新行。限制为 1,048,576 行,Excel 告诉您修改后的工作表超出了该限制。

关于Python - 使用 Pandas 和 openpyxl 修改现有的 excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55158855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com