首页 > 解决方案 > 在 python 中的同一工作簿中创建 Excel 工作表

问题描述

在我的代码中需要一个建议。

我在工作簿的 sheet1 中有一个数据框:

column 1           column 2
000A0000              2
000B0000              3
000A0001              5
000B0001              1

我想要的结果:

在工作簿的第 2 页中:

column 1           column 2
 000A0000              2
 000A0001              5

在工作簿的第 3 页中:

column 1           column 2
 000B0000              3
 000B0001              1

我已经完成了编码:

import pandas as pd
file="workbook.xlxs"
print(data.sheet_names)
data=data.parse("sheet1")

substrings = ['A', 'B']

T = {x: df[df['sheet1'].str.contains(x, na=False, regex=False)] for x in substrings]

for key, var in T.items():
    var.to_excel(f'{key}.xlsx', index=False)

通过这个我可以创建新的工作簿。但我需要在同一个工作簿中创建新的工作表。

任何建议将不胜感激。

标签: pythonexcelpandas

解决方案


要将工作表添加到相同的 excel 文件使用openpyxl模块,如下所示:

import pandas as pd
import openpyxl

#reading the sheet1 using read_excel
df = pd.read_excel('workbook.xlsx', sheet_name='Sheet1')

#creating pandas ExcelWriter object and loading the excel file using `openpyxl`    
df_writer = pd.ExcelWriter('workbook.xlsx', engine='openpyxl')
excel = openpyxl.load_workbook('workbook.xlsx')
df_writer.book = excel

#checking string in column 1 and writing those to respective sheets in same workbook
for string in ['A','B']:
    df[df['column 1'].str.contains(string)].to_excel(df_writer,sheet_name=string)
#saving and closing writer
writer.save()
writer.close()

推荐阅读