python xlrd3使用

python 目前xlrd库已经更新到2.1.0+,2.1.0+版本得库无法操作xlsx文件,只能操作xls文件
需要安装低于1.2.0版本得xlrd库才可以,但是xlrd3可以可以支持xls和xlsx的读取,并且效率
上比openpyxl要快

# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name:         g
# Author:       yunhgu
# Date:         2022/5/11 13:44
# Description: 
# -------------------------------------------------------------------------------
import xlrd3 as xlrd


def open_excel(file):
    try:
        return xlrd.open_workbook(file)
    except Exception as e:
        print(f"打开{file}失败,错误信息:{e}")


def excel_table_by_index(file, by_index=0):
    data = open_excel(file)
    table = data.sheet_by_index(by_index)
    row_data_list = []
    for row in range(table.nrows):
        columns = table.row_values(row)  # 某一行数据
        row_data_list.append(columns)
    return row_data_list


def excel_table_by_name(file, by_name='Sheet1'):
    data = open_excel(file)
    table = data.sheet_by_name(by_name)
    row_data_list = []
    for row in range(table.nrows):
        columns = table.row_values(row)  # 某一行数据
        row_data_list.append(columns)
    return row_data_list


def main():
    tables = excel_table_by_name("test.xlsx")
    print(tables)

    tables = excel_table_by_index("test.xlsx")
    print(tables)


if __name__ == "__main__":
    main()


posted @ 2022-05-11 13:39  不能说的秘密  阅读(832)  评论(0编辑  收藏  举报