Python Excel在现有工作表中编写一个DataFrame

时间:2019-12-17 17:02:14

标签: python excel pandas

我想在现有工作表(此处为“ sheet1”)中添加一个数据框,但是代码创建了一个新的“ sheet1”。 这是我的代码:

非常感谢您的帮助

亚历克斯

import pandas as pd
import numpy as np
from openpyxl import load_workbook

path = ""
df = pd.DataFrame({'Data': [11, 12, 13, 14]})
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book
df.to_excel(writer,sheet_name="Sheet1" startrow=1, startcol=5, header=False,index=False)
writer.save()
writer.close()

2 个答案:

答案 0 :(得分:0)

我想知道您是否只带入整个xl库?我还没有尝试过熊猫,但这在我的项目路线图上。

    import openpyxl

答案 1 :(得分:0)

您可以尝试以下方法:

from openpyxl import load_workbook

wb = load_workbook("C:\text.xlsx")
sheets = wb.sheetnames
Sheet1 = wb[sheets[8]]
Sheet2 = wb[sheets[7]]
#Then update as you want it
Sheet1 .cell(row = 2, column = 4).value = 5 #This will change the cell(2,4) to 4
wb.save("HERE PUT THE NEW EXCEL PATH") 

有关更多信息:enter link description here