Python-无法使用XLRD模块读取xlsx工作表

时间:2018-08-14 19:19:18

标签: python xlsx xlrd

我正在尝试阅读xlsx工作表并将其附加到列表中。但是,下面的代码将引发错误。我无法解密错误是什么。 有人可以帮忙吗?

错误: TypeError: list indices must be integers or slices, not str

我的代码:

import xlrd
df = []
with xlrd.open_workbook(r'C:\Users\Tad\Documents\test.xlsx') as wb:
        with wb.get_sheet('Selected products') as sheet:
            for row in sheet.rows():
                df.append([item.v for item in row])

如果我使用“ with wb.sheet_by_name('Selected products') as sheet:”,则错误是:“ AttributeError: __enter__

1 个答案:

答案 0 :(得分:0)

请勿将xlrd用于新的Excel文件。而是使用openpyxl。

https://openpyxl.readthedocs.io/en/stable/

from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = 42

# Rows can also be appended
ws.append([1, 2, 3])

# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()

# Save the file
wb.save("sample.xlsx")