python ValueError:值必须是[“字段”、“数据”、“选择”}之一

knpiaxh1  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(168)

我正在使用Excel文件,该文件具有多个包含图表和图形的工作表,并希望添加新工作表,但我收到**ValueError:值必须是[“字段”、“数据”、“选择”}**之一
我使用下面的代码参考@Stefano Fedele solution,使用Pandas在现有文件中添加新表,而不会丢失数据。

import pandas as pd
import numpy as np
from openpyxl import load_workbook

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book

x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name = 'x3')
df4.to_excel(writer, sheet_name = 'x4')
writer.close()

如何在包含图表和图形等的现有Excel中添加新工作表的解决方案?

mnemlml8

mnemlml81#

尝试单独使用openpyxl,不要将其与panda混用。ExcelWriter

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

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

book = load_workbook(path)

x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

sheet = book.create_sheet("x8")
book.active=sheet
for r in dataframe_to_rows(df3, index=False, header=True):
    sheet.append(r)

sheet = book.create_sheet("x9")
book.active=sheet
for r in dataframe_to_rows(df4, index=False, header=True):
    sheet.append(r)

book.save(path)

相关问题