合并xls输出不同

时间:2013-10-16 21:27:09

标签: python excel

我希望我的脚本输出如下:

2   11
4   12
6   13
8   14
48  15

但输出如下:

2   48
4   48
6   48
8   48
48  48

以下是代码,有人可以帮助我做错了吗:

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

1 个答案:

答案 0 :(得分: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')