[英]How can I copy columns from one excel sheet to another with python using openpyxl Library?
I am new to programming.我是编程新手。 I am trying to copy columns from one excel sheet to another but I'm having problem with my code as only the last column data is being copied to the destination file.
我正在尝试将列从一张 excel 工作表复制到另一张,但我的代码有问题,因为只有最后一列数据被复制到目标文件。 I've attached the code and the result i kept getting.
我附上了代码和我不断得到的结果。
Jan_2020 ="C:\\Users\\yaxee\\OneDrive\\Desktop\\NBET
Extraction data\\JANUARY 2020.xlsx"
wb1 = xl.load_workbook(Jan_2020)
ws1 = wb1.worksheets[0]
Extraction_WB ="C:\\Users\\yaxee\\OneDrive\\Desktop\\ExtractionWB.xlsx"
wb2 = xl.load_workbook(Extraction_WB)
ws2 = wb2.worksheets[0]
#copy from wb1
for i in range(4, 34):
c = ws1.cell(row = i, column = 4)
#paste in ws2
for j in range(3, 33):
ws2.cell(row = j, column = 4).value = c.value
wb2.save(str(Extraction_WB))
If I understand your need, you need to put the second loop inside the first loop for copy the whole range of rows.如果我理解您的需要,您需要将第二个循环放在第一个循环中以复制整个行范围。 Would this work?
这行得通吗? Kr.
氪
#copy from wb1
for i in range(4, 34):
c = ws1.cell(row = i, column = 4)
#paste in ws2
for j in range(3, 33):
ws2.cell(row = j, column = 4).value = c.value
wb2.save(str(Extraction_WB))
You don't need two loops.你不需要两个循环。 You are just constantly overriding the value of
c
until it has the last value of the column.您只是不断地覆盖
c
的值,直到它具有该列的最后一个值。
Then, you simply write that value to all rows of the second sheet.然后,您只需将该值写入第二张工作表的所有行。
Instead, use one loop, to read a single value from the current row, and write it to the corresponding row in the second sheet:相反,使用一个循环,从当前行读取单个值,并将其写入第二张工作表中的相应行:
for row in range(4, 34):
#copy from wb1
c = ws1.cell(row=row, column=4)
#paste in ws2
ws2.cell(row=row-1, column=4, value=c.value)
If you have some general transformation between the sheets, a more general approach as follows:如果您在工作表之间有一些通用的转换,则更通用的方法如下:
step = 2
read_start_row = 4
write_start_row = 3
amount_of_rows = 30
for i in range(0, amount_of_rows, step):
#copy from wb1
c = ws1.cell(row=read_start_row+i, column=4)
#paste in ws2
ws2.cell(row=write_start_row+(i/step), column=4, value=c.value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.