【问题标题】:how to open xlsx file with python 3如何用python 3打开xlsx文件
【发布时间】:2016-09-22 21:16:06
【问题描述】:

我有一个带有 1 张纸的 xlsx 文件。 我正在尝试使用 python 3 (xlrd lib) 打开它,但我得到一个空文件!

我使用这个代码:

file_errors_location = "C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx"
workbook_errors = xlrd.open_workbook(file_errors_location)

我没有错误,但是当我输入时:

workbook_errors.nsheets

我得到“0”,即使文件有一些表格......当我输入时:

workbook_errors 

我明白了:

xlrd.book.Book object at 0x2..

有什么帮助吗?谢谢

【问题讨论】:

  • 当您调用“workbook_errors.sheets()”然后调用“workbook_errors.nsheets”时会发生什么?

标签: python-3.x xlsx xlrd


【解决方案1】:

另一种方法:

import openpyxl 
workbook_errors = openpyxl.Workbook()
workbook_errors = openpyxl.load_workbook(file_errors_location)

【讨论】:

    【解决方案2】:

    不幸的是,读取 Excel 文档所需的 python 引擎“xlrd”已明确删除对 xls 文件以外的任何内容的支持。

    所以现在你可以这样做 -

    注意:这适用于我最新版本的 Pandas(即 1.1.5)。以前,我使用的是 0.24.0 版本,但它不起作用,所以我必须更新到最新版本。

    【讨论】:

    • 刚刚使用了pandas 1.3.2版,它问我openpyxl的依赖,安装它并且pandas.read_excel在没有指定engine参数的情况下工作
    • @FlorentRoques 当你没有明确指定引擎参数时,它默认为无。在这种情况下,有一系列逻辑可以确定最适合您的文档的引擎。请查看此链接了解更多详情 - pandas.pydata.org/docs/reference/api/pandas.read_excel.html
    【解决方案3】:

    您可以像 pandas.read_csv 一样使用 Pandas pandas.read_excel

    import pandas as pd
    file_errors_location = 'C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx'
    df = pd.read_excel(file_errors_location)
    print(df)
    

    【讨论】:

    • 请注意,您需要安装库 xlrd 才能正常工作。
    • @gieldops 是对的。你可以安装xlrdpip install xlrd
    • 变优雅!您可以使用以下方法遍历行:for index, row in df.iterrows():
    【解决方案4】:

    读取xls文件有两个模块:openpyxl和xlrd

    此脚本允许您使用 xlrd 将 excel 数据转换为字典列表

    import xlrd
    
    workbook = xlrd.open_workbook('C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx')
    workbook = xlrd.open_workbook('C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx', on_demand = True)
    worksheet = workbook.sheet_by_index(0)
    first_row = [] # The row where we stock the name of the column
    for col in range(worksheet.ncols):
        first_row.append( worksheet.cell_value(0,col) )
    # tronsform the workbook to a list of dictionnary
    data =[]
    for row in range(1, worksheet.nrows):
        elm = {}
        for col in range(worksheet.ncols):
            elm[first_row[col]]=worksheet.cell_value(row,col)
        data.append(elm)
    print data
    

    【讨论】:

    • 当我输入:“worksheet = workbook.sheet_by_index(0)”时出现错误:“list index out of range....”因为如果我输入 worksheet .nsheets,我得到 0 ! !
    • 不...我现在尝试打开一个新文件,它运行良好.. 文件似乎被锁定或类似
    • 不确定.. 因为我仍然需要打开那个“锁定”的文件。
    • 根据文档,行的索引从零开始。您缺少第一行。
    猜你喜欢
    • 2018-04-08
    • 2017-06-10
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    相关资源
    最近更新 更多