如何使用 python 中的 openpyxl 将范围从一个 sheet 复制为另一个值
How to copy a range from one sheet to another as values using openpyxl in python
我必须复制工作簿 1 的 A1:Z100 从 sheet onw 到工作簿 2 的 sheet 1 的范围吗?
我的代码:
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
这无法正常工作。如何将此范围复制到 sheet?
你可以试试这样的东西:
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')
提供另一种使用方法 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)
添加仅数据的 openpyxl 解决方案
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')
编辑
cell.coordinate returns value like 'A1' ,那么sheet1['A1'].value就是单元格A1
的值
我必须复制工作簿 1 的 A1:Z100 从 sheet onw 到工作簿 2 的 sheet 1 的范围吗?
我的代码:
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
这无法正常工作。如何将此范围复制到 sheet?
你可以试试这样的东西:
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')
提供另一种使用方法 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)
添加仅数据的 openpyxl 解决方案
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')
编辑
cell.coordinate returns value like 'A1' ,那么sheet1['A1'].value就是单元格A1
的值