用Python语言写入Excel文件

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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)