python - 在 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)
通过这个我可以创建新的工作簿。但我需要在同一个工作簿中创建新的工作表。
任何建议将不胜感激。
解决方案
要将工作表添加到相同的 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()
推荐阅读
- python - 如何在传输过程中保护 REST API 有效负载?
- google-bigquery - 我正在遭受使用 StandardSQL 连接方法的 Bigquery
- html - 用于在锚标记内获取文本值的选择器标记
- caching - 缓存替换策略
- ruby-on-rails - 如何将`where`条件应用于每条记录
- docker - docker文件错误gzip:stdin:无效的压缩数据--crc错误
- c# - C# MVC 视图模型使用连接表返回 IEnumerable 列表
- c# - 在 C# 代码函数错误超时但在 SQL Server 中它执行得很快
- php - Symfony 4 FOSUserBundle 自定义路由 - 添加前缀和子页面
- powershell - 如何使用 Powershell 过滤特定行和列的 csv 数据并计算总和?