我正在将数据从一个工作簿复制到另一个工作簿。问题是熊猫正在使用名称“ sheet_name1”创建一个新工作表,而不是使用“ sheet_name”。我正在使用openpyxl作为熊猫引擎。您可以提供原因吗?
input_file = "C:\Automations\FastenersAudit\ClassfiedExports\\" + str(export)
output_file = "C:\Automations\FastenersAudit\Templates\\" + str(template)
input_df = pd.read_excel(io=input_file, skiprows=1)
output_df = pd.read_excel(io=output_file, skiprows=4)
headings = list(output_df.head())
writer = pd.ExcelWriter(output_file, engine="openpyxl")
writer.book = openpyxl.load_workbook(output_file)
for each_heading in headings:
try:
output_df[each_heading] = input_df[each_heading]
except KeyError:
continue
output_df = output_df.loc[:, :'Total Attributes']
output_df = output_df.drop(labels='Total Attributes', axis=1)
output_df.to_excel(writer, sheet_name="Attribute Analysis", na_rep='', index=False, startrow=5, engine="openpyxl")
writer.save()
writer.close()
答案 0 :(得分:1)
略作编辑的版本: 非常感谢您的解决方案。稍加修改即可完美地工作。
writer.sheets = {ws.title: ws for ws in writer.book.worksheets}
for sheetname in writer.sheets:
if sheetname == 'Attribute Analysis':
output_df.to_excel(writer, sheet_name=sheetname, na_rep='', index=False, startrow=5, engine="openpyxl", header=False)
writer.save()
原始答案:
我认为您需要startrow和maxrow函数以及writer.sheets
才能读取工作表名称:
writer.sheets = {ws.title: ws for ws in book.worksheets}
for sheetname in writer.sheets:
output_df.to_excel(writer,sheet_name=sheetname,startrow=writer.sheets[sheetname].max_row, index = False,header= False)
writer.save()