列表索引在python中超出范围

时间:2021-02-11 16:40:24
import glob
import xlrd

from xlwt import Workbook

wb = Workbook()

for file_name in glob.glob("foo*.xls"):
    wb_orig = xlrd.open_workbook(file_name)
    for ws_orig in wb_orig.sheets():
        ws = wb.add_sheet('{0} {1}'.format(file_name, ws_orig.name))
        for rx in range(ws_orig.nrows):
            for cx in range(ws_orig.ncols):
                ws.write(rx, cx, ws_orig.cell_value(rx,cx))

wb.save("mefoo.xls")

i tried the above code in many ways to merge multiple excel sheets into one workbook........ this code gives error as

我在很多方面尝试了上面的代码,将多个Excel工作表合并到一个工作簿中......这段代码给出了错误

Traceback (most recent call last):
  File "E:\my python\Internship\merge*.py", line 16, in <module>
    wb.save("mefoo.xls")
  File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 634, in save
    doc.save(filename, self.get_biff_data())
  File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 615, in get_biff_data
    self.__worksheets[self.__active_sheet].selected = True
IndexError: list index out of range

please help me to solve the error..

请帮我解决错误..

2 个解决方案

#1


6  

The only way that you can get that IndexError is if there are no sheets in the output workbook.

获取IndexError的唯一方法是输出工作簿中没有工作表。

You need to examine your glob.glob("foo*.xls"); it looks like it's returning no files.

你需要检查你的glob.glob(“foo * .xls”);看起来它没有返回任何文件。

#2


1  

The solution I found was to not use an absolute path in the glob.

我发现的解决方案是不在glob中使用绝对路径。

for file_name in glob.glob("C://your//full//path//here//foo*.xls"):
  #population/merging code here

wb.save("mefoo.xls")

As to why this solved the problem, I do not know. But I hope this helps somebody.

至于为什么这解决了这个问题,我不知道。但我希望这有助于某人。

#1


6  

The only way that you can get that IndexError is if there are no sheets in the output workbook.

获取IndexError的唯一方法是输出工作簿中没有工作表。

You need to examine your glob.glob("foo*.xls"); it looks like it's returning no files.

你需要检查你的glob.glob(“foo * .xls”);看起来它没有返回任何文件。

#2


1  

The solution I found was to not use an absolute path in the glob.

我发现的解决方案是不在glob中使用绝对路径。

for file_name in glob.glob("C://your//full//path//here//foo*.xls"):
  #population/merging code here

wb.save("mefoo.xls")

As to why this solved the problem, I do not know. But I hope this helps somebody.

至于为什么这解决了这个问题,我不知道。但我希望这有助于某人。