简体   繁体   中英

Copying data from one worksheet to specified worksheet in another workbook

So I have one tedious task at work which involves updating one excel file with new data extracted from different systems that I'd love to have automated.

This looks like that: new_workbook[sheet1] -> pasted to the end of target_workbook[sheet1]

Format and shape of the columns is exactly the same.

I am familiar with xlwings api.copy as here

import xlwings as xw

source = r'source.xlsx'
target = r'target.xlsx'

wb = xw.Book(source)
sht = wb.sheets[0]

new_wb = xw.Book(target)
new_sht = new_wb.sheets[0]

sht.api.Copy(None, After=new_sht.api)

new_wb.save()
new_wb.close()

But this would create new worksheet in target workbook and paste the data there, not in already existing one. Is there any way to workaround this?

I think this iterative solution will be helpful for you.

#import modules
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import load_workbook

#read data from source path
df=pd.read_excel(source)

#load workbook and create sheet 
wb=load_workbook(target)
ws=wb.create_sheet("new_worksheet")

#add values in df iteratively to sheet named ws
for row in dataframe_to_rows(df,index=False,header=True):
    ws.append(row)
#save and close workbook
wb.save(target)
wb.close()

You can do it using pandas, first convert both to dataframes. Then concat them and finally convert that df to excel file.

import pandas as pd

source = pd.read_excel('source.xlsx')
target = pd.read_excel('target.xlsx')

target = pd.concat([target, source])

target.to_excel('merged.xlsx')

This will add the source data at the end of target data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM