1

I want the output of my script to be like :

2   11
4   12
6   13
8   14
48  15

But output comes like:

2   48
4   48
6   48
8   48
48  48

Below is the code, can somebody please help what I'm doing wrong:

import xlwt
import xlrd
import sys ; sys.path 
#Create workbook and worksheet

wbk = xlwt.Workbook()
sheet = wbk.add_sheet('Data_1')#name of the sheet in which new data is there

row = 0

f = xlrd.open_workbook('Data_1.xls')#workbook from where data is extracted
g = xlrd.open_workbook('Data_2.xls')#workbook from where data is extracted

sheet1 = f.sheet_by_index(0)

sheet2 = g.sheet_by_index(0)

for i in xrange(5):
    temp = sheet1.row_values(i)
    print temp
    col = 0
    for element in temp:        
        sheet.write(i,col,element)
        col += 1
        i += 1

for j in xrange(5):
    temp1 = sheet2.row_values(j)
    print temp1
    col = 1
    for elements in temp1:
        sheet.write(j,col,element)
        col +=1
        j += 1

wbk.save('DATA.xls') #excel sheet name when saved in the folder
4

1 回答 1

1

在您的第二个循环中,您在变量名中有一个拼写错误。

for elements in temp1:

应该

for element in temp1:

编辑:您的示例中还有很多冗余代码。我冒昧地重写了您的程序,使其更加简洁(尽管请注意,我还没有对此进行测试):

import xlwt
import xlrd
import sys
#Create workbook and worksheet

wbk = xlwt.Workbook()
dest_sheet = wbk.add_sheet('Data_1')

for sheet_idx in range(1, 3):
  sheet = xlrd.open_workbook('Data_%d.xls' % sheet_idx).sheet_by_index(0)

  for i in range(5):
    values = sheet.row_values(i)
    for idx, element in enumerate(values):
      dest_sheet.write(i, sheet_idx+idx, element)

wbk.save('DATA.xls')
于 2013-10-16T21:30:32.963 回答