簡體   English   中英

使用 Openpyxl 從特定列和行開始的現有工作表中寫入現有的 excel 文件

[英]Write to an existing excel file using Openpyxl starting in existing sheet starting at a specific column and row

我一直在搜索這個問題,從特定的行和列開始寫入現有的 Excel 工作表,但是像dataframe_to_rows這樣的方法不是從單元格中的特定位置寫入。 我現在正在使用自定義循環來編寫它,但是想知道是否有更好的方法。 循環是這樣工作的

import pandas as pd
import numpy as np
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
df = pd.DataFrame(np.random.randn(20, 4), columns=list('ABCD'))
file = "C:\\somepath\\some_existing_file.xlsx"
wb = load_workbook(filename=file, read_only=False)
ws = wb['some_existing_sheet']

##Fill up the row and column needed
stcol = 5
strow = 5

## Writing the column header
for c in range(0,len(df.columns)):
    ws[get_column_letter(c+stcol)+str(strow)].value = df.columns[c]
## Writing the data
for r in range(0,len(df)):
    for c in range(0,len(df.columns)):
       ws[get_column_letter(c+stcol)+str(strow+r+1)].value = df.iloc[r][c]
wb.save(file)

請讓我知道是否有更好的方法來寫入單元格中的特定位置。 如果結果是重復的問題,很高興合並到原始線程中。 我確實有另一種方法,但是使用 xlsx writer 但這會從現有工作表中刪除所有其他數據

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application') # opens Excel
writer = pd.ExcelWriter(file', engine='xlsxwriter')
df.to_excel(writer, sheet_name='abc', startrow=5, startcol=5,index=False)
writer.save()

代替

ws[get_column_letter(c+stcol)+str(strow)]

您可以使用

ws.cell(column=c+stcol, row=strow) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM