python - 通过python复制excel行

标签 python excel xlrd xlwt

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

row[0][0]=hello

row[1][0]=bye

row[2][0]=hi

我想将这三行复制到原始工作表中存在的行数中,以便修改后的工作表具有以下内容。
row[0][0]=hello

row[1][0]=bye

row[2][0]=hi

row[3][0]=hello

row[4][0]=bye

row[5][0]=hi

row[6][0]=hello

row[7][0]=bye

row[8][0]=hi

我的代码如下。
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

不知道为什么会这样。

最佳答案

问题是即使您更改循环变量 j在循环内部,该更改将被 range() 中的下一个值覆盖功能。

一个例子来说明这一点 -

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

但是您的代码取决于发生这种情况,而不是您应该尝试设置为 i+j*totalrows (每次)并从 1 开始 j .而且内循环里面的逻辑也有点不对,要靠i变量以及在新工作簿中设置值。

所以代码会变成 -
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(i+(j*totalrows),0,row)
book1.save("/Users/tusharbakaya/Desktop/test1.xls") 

或者您可以使用 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")

关于python - 通过python复制excel行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155300/

相关文章:

python - 意外的导入行为 : sys. 模块被检查两次?

python - 当 x 轴处于日期时间时,使用 Bokeh 绘制射线

python pymysql设置autocommit false失败

打印与屏幕和分页符的 Excel 条件内容/格式

python - Pandas突然无法打开Excel文件(在OLE2复合文档中找不到工作簿

Python:如何使我的四色检查器更具可读性

c# - 有没有办法在 VBA 中重载类的构造函数/初始化过程?

mysql - 如何在 SQL 查询中对单个参数应用多个 case 条件

python - 如何从Excel中提取指定行而不使用NaN

python - 在Python列表中导入Excel列