通过python复制excel行

2024-10-01 15:38:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我基本上有一个excel文件,在一个特定的表中有以下条目

row[0][0]=hello

row[1][0]=bye

row[2][0]=hi

我想将这三行复制到原始工作表中的行数中,以便修改后的工作表包含以下内容。在

^{pr2}$

我的代码如下。在

from xlutils.copy import copy
from xlrd import open_workbook
import xlwt

book=open_workbook("/Users/tusharbakaya/Desktop/test.xlsx")
book1=copy(book)
sheet=book.sheet_by_name('Sheet1')
sheet1=book1.get_sheet(0)
totalrows=sheet.nrows
print totalrows
for j in range(0,totalrows):
    for i in range(0,totalrows):
        row=sheet.cell_value(i,0)
        sheet1.write(j+totalrows,0,row)
        i+=1
    j+=totalrows
book1.save("/Users/tusharbakaya/Desktop/test1.xls") 

但是,我得到以下输出

row[0][0]=hello

row[1][0]=bye

row[2][0]=hi

row[3][0]=hello

row[4][0]=hello

row[5][0]=hello

row[6][0]=hello

不知道为什么会这样。在


Tags: fromimporthelloopenhiuserssheetrow
1条回答
网友
1楼 · 发布于 2024-10-01 15:38:45

问题是,即使您在循环内更改循环变量j,该更改也会被range()函数的下一个值覆盖。在

举个例子来说明这一点-

>>> for i in range(10):
...     print(i)
...     i = 1000
...
0
1
2
3
4
5
6
7
8
9

但是您的代码依赖于这种情况的发生,相反,您应该尝试设置为i+j*totalrows(everytime)并从1开始j。而且内部循环内部的逻辑也有点错误,您应该依赖i变量来设置new workbook中的值。在

所以代码会变成-

^{pr2}$

或者您可以使用while循环来代替for循环,并且

while循环的示例-

from xlutils.copy import copy
from xlrd import open_workbook
import xlwt

book=open_workbook("/Users/tusharbakaya/Desktop/test.xlsx")
book1=copy(book)
sheet=book.sheet_by_name('Sheet1')
sheet1=book1.get_sheet(0)
totalrows=sheet.nrows
print totalrows
j,k = 0, 0
while k < totalrows
    for i in range(0,totalrows):
        row=sheet.cell_value(i,0)
        sheet1.write(i+j,0,row)
    j+=totalrows
    k += 1
book1.save("/Users/tusharbakaya/Desktop/test1.xls")

相关问题 更多 >

    热门问题