使用python

时间:2015-08-04 00:19:29

标签: excel python-2.7 xlrd xlwt

我在Excel中可能有一千张发票,所有发票都有B2中的客户/名称,地址分为B3和B4,B3具有数字和街道名称,以及B4中的城市,州和邮政编码。我要做的是打开每个excel文件(都在同一目录中)并提取名称和地址,以创建一个包含信息的新电子表格。

这是我到目前为止所做的:

import glob
from xlrd import open_workbook, XL_CELL_TEXT
from xlwt import Workbook
from tempfile import TemporaryFile

invoices = glob.glob("C:\emma\*.xls")
wbook = Workbook()
wsheet = wbook.add_sheet('Sheet 1')
R = 0

for x in invoices:
    rbook = open_workbook(x)
    rsheet = rbook.sheet_by_index(1)
    ncell = rsheet.cell(1,1)
    acell1 = rsheet.cell(1,2)
    acall2 = rsheet.cell(1,3)
    name = ncell.value
    address = acell1.value + " " + acell2.value

    wsheet.write(R,0,name)
    wsheet.write(R,1,address)

    R = R + 1

wbook.save('addresses.xls')
wbook.save(TemporaryFile())

目前它不起作用。这是我得到的错误:

Traceback (most recent call last):
  File "C:\emma\emma.py", line 14, in <module>
    ncell = rsheet.cell(1,1)
  File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 399, in cell
    self._cell_types[rowx][colx],
IndexError: list index out of range

我不太确定导致此错误的原因。

1 个答案:

答案 0 :(得分:0)

蒂姆·威廉姆斯是正确的,将rbook.sheet_by_index(1)调整为rbook.sheet_by_index(0)使其正常工作,并修复错误acall2 = rseet.cell(1,3)