【问题标题】:Write to an existing excel file using Openpyxl starting in existing sheet starting at a specific column and row使用 Openpyxl 在现有工作表中从特定列和行开始写入现有 excel 文件
【发布时间】:2018-10-25 17:08:41
【问题描述】:

我一直在搜索这个问题以从特定的行和列开始写入现有的 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()

【问题讨论】:

  • 不用get_column_letter
  • 需要创建一个数字循环来查找每个单元格并从每个数据帧记录中分配值。不知道我是否错过了什么。

标签: python python-3.x openpyxl


【解决方案1】:

而不是

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

你可以使用

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

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多