[英]How to copy and paste data from excel to another excel using python
我想将 excel 数据从源 excel 文件复制到目标 excel 文件。 但是,我不仅仅是从源文件中复制整个数据。
我只需要从源文件中仅复制某些行和列,例如前 5 行乘 4 列(覆盖此数据,行:第 1 至第 5,列:A 至 D)并粘贴到目标 excel 文件的固定协调上,如行:第 3到第 7,列:A 到 D。下一次迭代我想将接下来的 5 行乘以 4 列(覆盖此数据,行:第 6 到第 10,列:A 到 D)复制到相同的坐标(行:第 3 到第 7,列:A 到 D)并继续从源文件复制,直到完成从源文件复制整个数据。
以下是源文件和所需目标文件的附件。
这是我尝试过的代码,但它返回奇怪的输出:
# source
filename ="C:/Users/aaa/Desktop/combine_all.xlsx"
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
# destination
filename1 ="C:/Users/aaa/Desktop/algorithm.xlsx"
wb2 = xl.load_workbook(filename1)
ws2 = wb2.active
mr = ws1.max_row
mc = ws1.max_column
try:
m = [1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96, 101, 106, 111, 116, 121, 126, 131, 136]
n = [6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96, 101, 106, 111, 116, 121, 126, 131, 136, 141]
for q in range (3, 8):
for xm, yn in zip(m, n):
for i in range (xm, yn):
for j in range (1, 5):
c = ws1.cell(row = i, column = j)
ws2.cell(row = q, column = j).value = c.value
如果有人可以帮助我,非常感谢,在此先感谢!
不知道为什么每次都复制到相同的目标范围,但试试这个
#!python
import openpyxl as xl
COPY_ROWS = 5
COPY_COLS = 4
FOLDER = 'C:/Users/aaa/Desktop/'
# source
filename1 = 'combine_all.xlsx'
wb1 = xl.load_workbook(FOLDER + filename1)
ws1 = wb1.worksheets[0]
#destination
filename2 = 'algorithm.xlsx'
wb2 = xl.load_workbook(FOLDER + filename2)
ws2 = wb2.active
r = 0
i = 1
count = 0
while r < ws1.max_row:
r += 1
for c in range(1, COPY_COLS+1):
for i in range(0,COPY_ROWS):
ws2.cell(i+3,c).value = ws1.cell(i+r,c).value
count += 1
r += i
wb1.close
wb2.save(FOLDER + "algorithm1.xlsx")
wb2.close
print("{} blocks of {} rows by {} columns copied".format(count,COPY_ROWS,COPY_COLS))
import pandas as pd
excel_file = "C:/Users/aaa/Desktop/combine_all.xlsx"
input = pd.read_excel(excel_file)
input.to_excel('output.xlsx', index=False)
看这个教程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.