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

Python Copy specific rows and columns and update existing template file

我需要代码做什么:

代码的实际作用:

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

与我读过的以前的问题不同,我不想在更新数据时修改列数或行数,我不想将数据粘贴到新选项卡中,我这样做不想复制整个作品sheet 或 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 中的样子:

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

我已经阅读: 它有助于遍历模板文件,但它使用硬编码数据“(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)