在excel电子表格中输出的python程序

时间:2015-08-25 20:15:13

标签: python export-to-excel

我正在尝试使用Python编写从另一个电子表格中的大型Excel工作簿中检索的输出。但是,我无法,它给我一些错误,如引发ValueError("列索引(%r)而不是范围内的int(256)"%arg)ValueError:列索引(256)不是范围内的int(256),异常:意外的数据类型。 我可以在一定程度上理解这些错误,但无法纠正我的代码。我在这里写了一个小脚本。如果有人可以告诉我并纠正我在哪里出错,那将是很棒的。

import xlrd
import xlwt

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
file_location = "path/lookup_V1.xlsx"
workbook=xlrd.open_workbook(file_location)
sheet1 = workbook.sheet_by_index(0)
print sheet1.name
sheet2 = workbook.sheet_by_index(1)
print sheet2.name
print workbook.nsheets
st1c=sheet1.ncols
st2r=sheet2.nrows
st1=st1c+1
st2=st2r+1
print("fill..")  

for i in xrange(0,st1c):
    s1=sheet1.col_values(i)
    i+1
    s1.sort()
    print s1

for col in xrange(st1c):
    for row in xrange(st2r):

    print("filling sheet...")    

    col=col+1
    row=row+1
    ws.write(row,col)
    print("here")
    wb.save('testfile.xls')

1 个答案:

答案 0 :(得分:0)

试试这个:

import xlrd
import xlwt

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
file_location = "test.xls"
workbook=xlrd.open_workbook(file_location)
sheet1 = workbook.sheet_by_index(0)
st1c=sheet1.ncols
st1r=sheet1.nrows

for col in xrange(st1c):
    for row in xrange(st1r):
        value = sheet1.col_values(col, row, row + 1)
        # According to documentation : http://www.lexicon.net/sjmachin/xlrd.html#xlrd.Sheet.col_values-method
        # col_values returns a slice of the values of the cells in the given column.
        # That why we have to specify the index below, it is no elegant but it works
        ws.write(row, col, value[0]) 

wb.save('testfile.xls')

此解决方案适用于单张工作表.​​..然后您可以将其转换为函数并迭代不同的工作表和工作簿...

更优雅的解决方案:

import xlrd
import xlwt

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
file_location = "test.xls"
workbook=xlrd.open_workbook(file_location)
sheet1 = workbook.sheet_by_index(0)
st1c=sheet1.ncols
st1r=sheet1.nrows

for col in xrange(st1c):
    for row in xrange(st1r):
        # More elegant
        value = sheet1.cell_value(row, col)
        ws.write(row, col, value) 

wb.save('testfile.xls')