How to copy a range from one sheet to another as values using openpyxl in python

心已入冬 提交于 2019-12-11 03:27:29

问题


I have to copy a range from A1:Z100 from sheet onw of workbook 1 to sheet 1 of workbook 2?

My code :

wb = openpyxl.load_workbook('file1.xlsx')
wb1 = openpyxl.load_workbook('file2.xlsx')
sheet = wb["R"]
sheet1 = wb1["Rt"]
sheet1.cell(row=1,column=1).value = sheet.cell(row=1,column=1).value

This is not working properly. How to copy this range to that sheet?


回答1:


You can try with something like:

for i in range(1, 100):
    for j in range(1, 26):
        sheet1.cell(row=i,column=j).value = sheet.cell(row=i,column=j).value
wb1.save('file2.xlsx')



回答2:


Giving another way to do using pandas

import pandas as pd
excel = pd.read_excel('file1.xlsx', header=None)
writer = pd.ExcelWriter('file2.xlsx')
excel.loc[:99, :25].to_excel(writer, 'sheet1', index=False, header=False)

Add an openpyxl solution with data-only

wb = openpyxl.load_workbook('file1.xlsx', data_only=True)
wb1 = openpyxl.load_workbook('file2.xlsx')
sheet = wb['R']
sheet1 = wb1['Rt']
for row in sheet['A1':'Z100']:
    for cell in row:
        sheet1[cell.coordinate].value = cell.value
wb1.save('file2.xlsx')

EDIT

cell.coordinate returns value like 'A1' ,then sheet1['A1'].value is the value of cell A1



来源:https://stackoverflow.com/questions/51739488/how-to-copy-a-range-from-one-sheet-to-another-as-values-using-openpyxl-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!