[英]Use python to iterate over cells in excel range and copy values
I have 3 tables like below in excel.我在excel中有3个如下表。 This is more a python for loop question and less a excel question (but it still involves excel)
这更像是一个 python for loop 问题,而不是一个 excel 问题(但它仍然涉及 excel)
ID,Name,Age,Subject
1,abc,21,maths
2,def,28,science
3,rew,38,social
ID,Name,Age,Subject
11,adbc,21,maths
23,dedf,28,science
39,rewd,38,social
ID,Name,Age,Subject
111,ancbc,21,maths
232,dedsf,28,science
391,rewsdd,38,social
So, my table range for values is given below所以,我的值表范围如下
Table1 = D18:G20 (1st row,1st column is D18 (value is 1) and last row, last column is G20 (value is social)
Table2 = Q18:T20
Table3 = AB18:AE20
I would like to do the below我想做以下
a) Copy D18th
value to Q18
and AB18th
. a) 将
D18th
值复制到Q18
和AB18th
。
b) Similarly copy D19th
value to Q19th
and AB19th
b) 同样将
D19th
值复制到Q19th
和AB19th
c) Repeat this to copy each cell value from Table1 to Table2 and Table3 c) 重复此操作将每个单元格值从 Table1 复制到 Table2 和 Table3
So, I was trying like below (using Xlwings which allows us to copy range)所以,我尝试如下(使用允许我们复制范围的 Xlwings)
sheet1.range("D18:G18").copy()
sheet1.range("Q18:T18").paste()
sheet1.range("AB18:AE18").paste()
sheet1.range("D19:G19").copy()
sheet1.range("Q19:T19").paste()
sheet1.range("AB19:AE19").paste()
sheet1.range("D20:G20").copy()
sheet1.range("Q20:S20").paste()
sheet1.range("AB20:AE20").paste()
But the above is not elegant/efficient.但上述内容并不优雅/高效。 You can see am writing individual line for each range.
您可以看到正在为每个范围编写单独的行。
Is there any python way to do this over loop where at every iteration a specified range is copied and pasted to the provided multiple destination area是否有任何 python 方法可以在循环中执行此操作,在每次迭代中,都会将指定的范围复制并粘贴到提供的多个目标区域
update - input excel screenshot with 2 tables更新 - 输入带有 2 个表格的 excel 屏幕截图
As you rightly suggested, a for loop should suffice, a double for loop (using openpyxl) :正如您正确建议的那样,一个 for 循环就足够了,一个双 for 循环(使用 openpyxl):
from openpyxl import load_workbook
wb = load_workbook('sample.xlsx')
ws = wb['Sheet1']
source = ws['D18':'G20']
table2 = ws['Q18':'T20']
table3 = ws['AB18':'AE20']
for row1, row2, row3 in zip(source, table2, table3):
for cell1, cell2, cell3 in zip(row1, row2, row3):
cell2.value = cell1.value
cell3.value = cell1.value
wb.save('sample.xlsx')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.