Writing to Excel file in Python(用Python语言写入Excel文件)
本文介绍了用Python语言写入Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import pandas as pd
import openpyxl
filename="Tests.xlsx"
def createWorkBook():
wrkbk = openpyxl.Workbook()
ws = wrkbk.active
Sheets=["Rostered Patient","Non-Rostered Patient","Email","Error Handling"]
for sheet in Sheets:
if not sheet in wrkbk.sheetnames:
print("Created sheet: "+ sheet)
wrkbk.create_sheet(sheet)
wrkbk.save(filename)
def main():
Columns=[[""],["ID","Testing Procedure:","Pass/Fail","Issue#","Date"],[""],[""],[""]]
createWorkBook()
xl_writer = pd.ExcelWriter(filename, engine='openpyxl')
df = pd.DataFrame([["1","2","3","4","5",'6','7','8']],columns = Columns[1])
df.to_excel(xl_writer, 'Rostered Patient', index=False, startcol=1, startrow=1)
if __name__ == "__main__":
main()
我只是尝试将数据帧附加到Excel文件中的登记患者选项卡中。我想在每次运行代码时添加标题和8个id。我的问题是使用df_to_EXCEL与startrow和startcol.一起运行它。
推荐答案
您可以尝试如下重构代码:
from pathlib import Path
import openpyxl
import pandas as pd
filename="Tests.xlsx"
...
def main():
Columns = [
[""],
["ID", "Testing Procedure:", "Pass/Fail", "Issue#", "Date"],
[""],
[""],
[""],
]
# Check if the WorkBook exists and get its length
if not Path(filename):
createWorkBook()
previous_df_length = 0
else:
previous_df = pd.read_excel(io=filename, sheet_name="Rostered Patient")
previous_df_length = previous_df.shape[0] + 2
# As recommended in pandas documentation, use ExcelWriter in a context manager
with pd.ExcelWriter(filename, engine="openpyxl", mode="a") as xl_writer:
df = pd.DataFrame(
[["1", "2", "3", "4", "5", "6", "7", "8"]], columns=Columns[1]
)
df.to_excel(
xl_writer,
"Rostered Patient",
index=False,
startrow=previous_df_length,
startcol=1,
)
这篇关于用Python语言写入Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:用Python语言写入Excel文件
基础教程推荐
猜你喜欢
- 症状类型错误:无法确定关系的真值 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01