Python 复制特定行和列并更新现有模板文件

标签 python excel pandas openpyxl

我需要代码做什么:

  • 复制“NewData.xlsx”中 A - D 列下的所有行,并更新名为“updated.xlsx”的“template.xlsx”副本中 A - D 列下的所有行。

代码实际上做了什么:

  • 它(成功!)在名为“updated.xlsx”的更新模板文件中创建了一个名为“NEW_DATA”的新模板表,并写入数据......全部在一个单元格中。

(我需要将大量 GPS 数据传输到现有表中以供工作 - 以防有人好奇我为什么要这样做。)

与我之前读过的问题不同,我不想在更新数据时修改列数或行数,我不想将数据粘贴到新选项卡中,我不想复制整个工作表或 xlsx 文件,我不想将数据附加到现有数据下方。

import openpyxl
import pandas as pd

# create variable df containing updated data in excel
DataAsXlsx = r'C:\Users\...\NewData.xlsx'
xl_workbook = pd.ExcelFile(DataAsXlsx)  # Load the excel workbook
df = xl_workbook.parse("Sheet")  # Parse the sheet into a dataframe

#Reads template xlsx, creates template sheet 'NEW_DATA'
template = openpyxl.load_workbook(r'C:\Users\...\template.xlsx')
template.sheetnames
sheet1 = template.worksheets[0]
sheet1.title = 'NEW_DATA'
sheet1 = template['NEW_DATA']

#^^^everything above this line works^^^


#Code below attempts to copy rows AND columns from NewData.xlsx and paste to sheet 'NEW_DATA' in updated.xlsx

for row in range(1, sheet1.max_row+1): 
   cell = sheet1.cell(row=row, column=1)
   if cell.value is not None:
        cell.value = str(df)

#This pastes ALL DATA into ColA of sheet 'NEW_DATA' in updated.xlsx

template.save('updated.xlsx')

这是 NewData.xlsx 在 Excel 中的样子:

what NewData.xlsx looks like in excel

出于调试目的,template.xlsx 可以是任何现有的 Excel 文件。

我已经读过:Update rows and column using openpyxl from python它有助于迭代模板文件,但它使用硬编码数据“(c)”,并且此逻辑不会转移到我需要的内容。

我已经阅读了这里关于 pandas 和 openpyxl 的几乎所有问题,并且还阅读了文档。我不知道下一步该做什么。

更新

根据查理的反馈,我做了以下操作:

from openpyxl import load_workbook

wb1 = load_workbook(r'C:\Users\...\NewData.xlsx')
wb2 = load_workbook(r'C:\Users\...\template.xlsx')
ws1 = wb1['Sheet']
ws2 = wb2.get_active_sheet() 

for row in ws1.iter_rows(max_col=4):
        values = (c.value for c in row)
        ws2.append(values)
ws2.save('updated.xlsx')

这会将数据附加到现有数据集的底部(它应该替换 COL A - D 中的数据)任何建议都会有所帮助 - 我非常接近!!

最终更新

HOORAY - this works!!!

import pandas as pd

#use pandas to access the new data 
DataAsXlsx = pd.read_excel(r'C:\Users\...\NewData.xlsx', sheet_name='Sheet1')

#this reads the template file
template = r'C:\Users\...\template.xlsx'
df = pd.read_excel(template)

#this creates a new document named FinalAutomatedDataSheet.xlsx
writer = pd.ExcelWriter(r'C:\Users\....\FinalAutomatedDataSheet.xlsx') 

#this line overlays the template file data onto FinalAutomatedDataSheet.xlsx
df.to_excel(writer, startcol=0,startrow=0, index=False)

#This line writes the new data to FinalAutomatedDataSheet.xlsx
#NOTE: you can SPECIFY COLUMN and ROW indices below!!:
DataAsXlsx.to_excel(writer, startcol=0,startrow=0, index=False)

writer.save()

最佳答案

您当前的代码尝试将整个数据框粘贴到单元格中。

如果您只是在工作表之间复制,那么我建议您使用 openpyxl 的只读模式来读取数据。

from openpyxl import load_workbook
wb1 = load_workbook(read_only=True)
wb2 = load_workbook(template)
ws1 = wb1['Sheet']
ws2 = wb2.create_sheet("NEW_DATA") # it's not quite clear what you want
for row in ws1.iter_rows(max_col=4):
    values = (c.value for c in row)
    ws2.append(values)

关于Python 复制特定行和列并更新现有模板文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51736793/

相关文章:

python - pandas iterrows 抛出错误

python - 切片分配的 Numpy 切片意外失败

python - pandas 中的连接表

c# - 在 Excel 中需要 12 小时格式

python - "Merging"相同大小的数据帧合并为一个数据帧

python - 对多索引 Pandas 数据框上的重复行求和

python - 在python中通过rds创建aurora数据库实例

c# - 使用C#查询两个日期之间的Excel列

vba - Excel VBA - PivotItems 返回无效值

python - 根据列名拆分 Pandas 数据框